private static String module = "已知modile";
private static String exponentString = "AQAB";
public static String encrypt(String json) {
try {
byte[] modulusBytes = Base64.decode(module);
byte[] exponentBytes = Base64.decode(exponentString);
BigInteger modulus = new BigInteger(1, modulusBytes);
BigInteger exponent = new BigInteger(1, exponentBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, exponent);
RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
// RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulus, exponent);
// KeyFactory fact = KeyFactory.getInstance("RSA");
// PublicKey pubKey = fact.generatePublic(rsaPubKey);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
int inputLen = json.getBytes("utf-8").length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int MAX_ENCRYPT_BLOCK = 117;//单块最大长度
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(json.getBytes("utf-8"), offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(json.getBytes("utf-8"), offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
System.out.println(Base64.encode(encryptedData));
return Base64.encode(encryptedData);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @param args
*/
public static void main(String[] args) {
Map<String,String> result=new HashMap<String,String>();
String json="{\"token\":\"0ff178a3-808c-4590-9cda-186b2e0a38c3\",\"cellphone\":\"188XXXX333\",\"name\":\"管理员\"}";
String en = encrypt(json);
System.out.println(en);
byte[] enTest = null;
try {
enTest = Base64.decode(en);
} catch (Base64DecodingException e) {
e.printStackTrace();
}
System.out.println(enTest.length);
// System.out.println(en.length);
// System.out.println(new String(Dencrypt(en)));
System.out.println(new String(Dencrypt(enTest)));
}
main方法执行加密解密都没问题 c#端也可以解密出来,但是使用springweb就不得行了,加密出来是一个不变的固定字符串,也解不出来。我打断点查看差异,发现main方法时RSAPublicKey为十进制,springweb下为16进制,不知道为什么。运行环境为jdk1.6
main方法:
web方法下: