目前有java有加密和解密代码,因为不了解AES,js这块代码不知道如何写,试了好多都匹配不上java的加密和解密的值,有大亻老的看看吗?
// 加密
public static String encrypt(String key, String cleartext) {
try {
byte[] raw = InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(key.getBytes(), 32);
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(cleartext.getBytes());
return parseByte2HexStr(encrypted);
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
public static String parseByte2HexStr(byte buf[]) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
// 解密
public static String decrypt1(String key, String encrypted) {
try {
byte[] enc = parseHexStr2Byte(encrypted);
byte[] raw = InsecureSHA1PRNGKeyDerivator.deriveInsecureKey(key.getBytes(), 32);
SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
Cipher cipher = Cipher.getInstance(AES);
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(enc);
return new String(decrypted);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1) {
return null;
}
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2),16);
result[i] = (byte) (high * 16 + low);
}
return result;
}