js前台使用公钥加密,后台java解密
问题是:
String result = request.getParameter("encryedPwd");
byte[] en_result = new BigInteger(result, 16).toByteArray();
这里:byte[] en_result = new BigInteger(result, 16).toByteArray();
有的时候你会发现数组长度129,第一个元素为0,这肯定是不正确的!
解决办法自己写一个hex to byte[]的方法,就不出现上面的问题了。
/**
* 16进制 To byte[]
* @param hexString
* @return byte[]
*/
public static byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* Convert char to byte
* @param c char
* @return byte
*/
private static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}