1. 概述
使用 后台单点登录插件 加密用户名登录的话,访问链接为:http://ip:port/工程名/decision?ssoToken=xxx,本文告诉用户如何生成 ssoToken ,并给出 Java 示例代码。
2. 操作步骤
需安装后台单点登录插件,该插件具体介绍请参见:后台单点登录插件
2.1 生成 RSA Key
超管进入平台,点击「管理系统>系统管理>集成后台单点登录>用户名加密>生成RSA Key>保存」。如下图所示:
注:本步骤生成的 public Key 在本文 2.2 节将用到。
2.2 新建 Java 文件
2.2.1 未开启 ssoToken 超时设置功能
新建 Java 文件,命名为 RsaEncrypt.java 。完整的 Java 代码如下所示:
import org.jetbrains.annotations.Nullable;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
/**
* @author Afly
* created on 2021-11-09
*/
public class RsaEncrypt {
private static final int FRAGMENT_LENGTH = 245;
public static void main(String[] args) throws UnsupportedEncodingException {
String text = System.getProperty("text");
String key = System.getProperty("publicKey");
String username = text == null ? "Alice" : text;
String defaultKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwnj5y3LGoPEvPhA5/rZXd9PYyQyrC1fr\r\n" +
"Wk4NUcWv40ICCbvsiN8duPh06PTHEtZAM+NpCQXetbNcdqYcOmY4taTmmWiZ43jBwL1Bn05eB5r2\r\n" +
"LDmo+X3IOV03VB6J9KFFcGG2W5qy+OKdp5UsuhhIMh0Jw7KhTWmYSMl7BafyOIlraMKmw45srwqG\r\n" +
"xVr6KbV7DBvHg7uagU5RwfpsGgKThkO4VKTTrnj4nZwWdJn3XEwAC2nLFoJrD+XrepkTOKufY0hP\r\n" +
"vTKKgjpPOkysDBUERGW/0f99dTrekKb/TRRoD6FOIB9a/kLE1rElLNGB19mG9w095SCgOaOYIg82\r\n" +
"Nati1wIDAQAB";
//从插件配置页面获取
String publicKey = key == null ? defaultKey : key;
//加密后的ssoToken,可以在前台界面进行解密测试
String encrypt = encrypt(username, publicKey);
System.out.println("encrypted username: " + encrypt);
//encode后的token,可以直接放于url上进行单点
String encode = URLEncoder.encode(encrypt, "UTF-8");
System.out.println("ssoToken: " + encode);
}
/**
* 加密方法.
*
* @param plainText 要加密的文本
* @param customPublicKey 公钥,可以从插件配置页面获取
* @return base64编码的加密字符串
*/
public static String encrypt(String plainText, String customPublicKey) {
return encrypt(plainText, string2PublicKey(customPublicKey));
}
public static byte[] encrypt(byte[] plainTextData, Key publicKey) {
if (plainTextData.length == 0) {
return plainTextData;
}
try {
Cipher c1 = Cipher.getInstance("RSA");
c1.init(Cipher.ENCRYPT_MODE, publicKey);
return dealEncryptFragment(plainTextData, c1);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String encrypt(String plainText, Key publicKey) {
if (plainText == null || "".equals(plainText)) {
return plainText;
}
byte[] publicEncrypt = encrypt(plainText.getBytes(StandardCharsets.UTF_8), publicKey);
return Base64.getEncoder().encodeToString(publicEncrypt);
}
public static PublicKey string2PublicKey(String pubStr) {
try {
byte[] keyBytes = base642Byte(pubStr);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return keyFactory.generatePublic(keySpec);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] base642Byte(String base64Key) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
return decoder.decodeBuffer(base64Key);
}
private static byte[] dealEncryptFragment(byte[] data, Cipher cipher) throws IllegalBlockSizeException, BadPaddingException {
byte[] result = new byte[]{};
int i;
for (i = 0; i < data.length; i += FRAGMENT_LENGTH) {
byte[] fragment = subarray(data, i, i + FRAGMENT_LENGTH);
byte[] update = cipher.doFinal(fragment);
result = addAll(result, update);
}
return result;
}
public static byte[] subarray(@Nullable byte[] array, int startIndexInclusive, int endIndexExclusive) {
if (array == null) {
return null;
} else {
if (startIndexInclusive < 0) {
startIndexInclusive = 0;
}
if (endIndexExclusive > array.length) {
endIndexExclusive = array.length;
}
int newSize = endIndexExclusive - startIndexInclusive;
if (newSize <= 0) {
return new byte[0];
} else {
byte[] subarray = new byte[newSize];
System.arraycopy(array, startIndexInclusive, subarray, 0, newSize);
return subarray;
}
}
}
public static byte[] addAll(@Nullable byte[] array1, @Nullable byte... array2) {
if (array1 == null) {
return clone(array2);
} else if (array2 == null) {
return clone(array1);
} else {
byte[] joinedArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
return joinedArray;
}
}
public static byte[] clone(@Nullable byte[] array) {
return array == null ? null : (byte[]) array.clone();
}
static abstract class CharacterDecoder {
public CharacterDecoder() {
}
protected abstract int bytesPerAtom();
protected abstract int bytesPerLine();
protected void decodeBufferPrefix(PushbackInputStream var1, OutputStream var2) throws Exception {
}
protected void decodeBufferSuffix(PushbackInputStream var1, OutputStream var2) throws Exception {
}
protected int decodeLinePrefix(PushbackInputStream var1, OutputStream var2) throws Exception {
return this.bytesPerLine();
}
protected void decodeLineSuffix(PushbackInputStream var1, OutputStream var2) throws Exception {
}
protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws Exception {
throw new Exception();
}
protected int readFully(InputStream var1, byte[] var2, int var3, int var4) throws Exception {
for(int var5 = 0; var5 < var4; ++var5) {
int var6 = var1.read();
if (var6 == -1) {
return var5 == 0 ? -1 : var5;
}
var2[var5 + var3] = (byte)var6;
}
return var4;
}
public void decodeBuffer(InputStream var1, OutputStream var2) throws Exception {
int var4 = 0;
PushbackInputStream var5 = new PushbackInputStream(var1);
this.decodeBufferPrefix(var5, var2);
while(true) {
try {
int var6 = this.decodeLinePrefix(var5, var2);
int var3;
for(var3 = 0; var3 + this.bytesPerAtom() < var6; var3 += this.bytesPerAtom()) {
this.decodeAtom(var5, var2, this.bytesPerAtom());
var4 += this.bytesPerAtom();
}
if (var3 + this.bytesPerAtom() == var6) {
this.decodeAtom(var5, var2, this.bytesPerAtom());
var4 += this.bytesPerAtom();
} else {
this.decodeAtom(var5, var2, var6 - var3);
var4 += var6 - var3;
}
this.decodeLineSuffix(var5, var2);
} catch (Exception var8) {
this.decodeBufferSuffix(var5, var2);
return;
}
}
}
public byte[] decodeBuffer(String var1) throws Exception {
byte[] var2 = new byte[var1.length()];
var1.getBytes(0, var1.length(), var2, 0);
ByteArrayInputStream var3 = new ByteArrayInputStream(var2);
ByteArrayOutputStream var4 = new ByteArrayOutputStream();
this.decodeBuffer(var3, var4);
return var4.toByteArray();
}
public byte[] decodeBuffer(InputStream var1) throws Exception {
ByteArrayOutputStream var2 = new ByteArrayOutputStream();
this.decodeBuffer(var1, var2);
return var2.toByteArray();
}
public ByteBuffer decodeBufferToByteBuffer(String var1) throws Exception {
return ByteBuffer.wrap(this.decodeBuffer(var1));
}
public ByteBuffer decodeBufferToByteBuffer(InputStream var1) throws Exception {
return ByteBuffer.wrap(this.decodeBuffer(var1));
}
}
static class BASE64Decoder extends CharacterDecoder {
private static final char[] pem_array = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'};
private static final byte[] pem_convert_array = new byte[256];
byte[] decode_buffer = new byte[4];
public BASE64Decoder() {
}
protected int bytesPerAtom() {
return 4;
}
protected int bytesPerLine() {
return 72;
}
protected void decodeAtom(PushbackInputStream var1, OutputStream var2, int var3) throws Exception {
byte var5 = -1;
byte var6 = -1;
byte var7 = -1;
byte var8 = -1;
if (var3 < 2) {
throw new Exception("BASE64Decoder: Not enough bytes for an atom.");
} else {
int var4;
do {
var4 = var1.read();
if (var4 == -1) {
throw new Exception();
}
} while(var4 == 10 || var4 == 13);
this.decode_buffer[0] = (byte)var4;
var4 = this.readFully(var1, this.decode_buffer, 1, var3 - 1);
if (var4 == -1) {
throw new Exception();
} else {
if (var3 > 3 && this.decode_buffer[3] == 61) {
var3 = 3;
}
if (var3 > 2 && this.decode_buffer[2] == 61) {
var3 = 2;
}
switch(var3) {
case 4:
var8 = pem_convert_array[this.decode_buffer[3] & 255];
case 3:
var7 = pem_convert_array[this.decode_buffer[2] & 255];
case 2:
var6 = pem_convert_array[this.decode_buffer[1] & 255];
var5 = pem_convert_array[this.decode_buffer[0] & 255];
default:
switch(var3) {
case 2:
var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
break;
case 3:
var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
break;
case 4:
var2.write((byte)(var5 << 2 & 252 | var6 >>> 4 & 3));
var2.write((byte)(var6 << 4 & 240 | var7 >>> 2 & 15));
var2.write((byte)(var7 << 6 & 192 | var8 & 63));
}
}
}
}
}
static {
int var0;
for(var0 = 0; var0 < 255; ++var0) {
pem_convert_array[var0] = -1;
}
for(var0 = 0; var0 < pem_array.length; ++var0) {
pem_convert_array[pem_array[var0]] = (byte)var0;
}
}
}
}
需注意以下几点:
1)String username = text == null ? "Alice" : text;代码中的 Alice 需换为自己工程中要加密的用户名。
2)String defaultKey 后的值,需更换为自己工程中生成的 public Key ,public Key 生成方法请参见本文 2.1 节内容。
2.2.2 开启 ssoToken 超时设置功能
插件 1.1.0 版本增加了「ssoToken 超时设置」功能,ssoToken 加密前的格式如下所示,其中 username 为用户名,issueTime 为当前毫秒时间戳。
{
"username": "1",
"issueTime":1640832102097
}
2.3 编译 Java 代码
编译Java程序 ,将生成 encrypted username、ssoToken。如下图所示:
注:encrypted username 后的值,为加密用户名。
2.4 效果查看
2.4.1 验证加解密流程是否正确
超管进入平台,点击「管理系统>系统管理>集成后台单点登录」,将生成的 encrypted username 放到「解密测试」框中,点击「解码」按钮,若能成功解密出用户名,代表加解密的流程是正确的。如下图所示:
2.4.2 使用 ssoToken 进行后台单点登录
访问链接:http://ip:port/工程名/decision?ssoToken=xxx,实现用户名加密的后台单点登录。如下图所示:
3. 注意事项
可以通过启动参数 text 、publicKey,如 :java -Dtext=文本 -DpublicKey=公钥 RsaEncrypt来自定义加密文本和公钥,其他工程调用可以直接调用RsaEncrypt#encrypt(java.lang.String, java.lang.String)方法,按需要进行一次 urlencode 。
本文 2.2 节代码编译后,将生成 3 个 class 文件。如下图所示:
1)未开启 ssoToken 超时设置功能
若直接编译本文 2.2 节代码,cmd 进入 class 文件所在目录,执行java -Dtext=用户名 RsaEncrypt即可生成encrypted username、ssoToken。
若在 2.2 节代码基础上加上包名,例如package 包名;,则需要进入包名对应的目录下,执行java -Dtext=用户名 包名.RsaEncrypt即可生成 encrypted username、ssoToken。如下图所示:
2)开启 ssoToken 超时设置功能
注:下面执行语句中 username 为用户名,issueTime 为当前毫秒时间戳;下面执行语句只生成有用的 ssoToken 。
若直接编译本文 2.2 节代码,cmd 进入 class 文件所在目录,执行java -Dtext="{\"username\": \"1\",\"issueTime\": 1640832102097}" RsaEncrypt即可生成支持超时的 ssoToken 。
若在 2.2 节代码基础上加上包名,例如package 包名;,则需要进入包名对应的目录下,执行java -Dtext="{\"username\": \"1\",\"issueTime\": 1640832102097}" 包名.RsaEncrypt即可生成支持超时的 ssoToken 。如下图所示: