我尝试实现了与AES .NET中讨论的步骤相同的步骤
但如果没有成功,我似乎无法让java和slowAes更好地合作……附件是我的代码,很抱歉我不能添加更多,这是我第一次尝试处理加密问题,如果有任何帮助,我将不胜感激
private static final String ALGORITHM = "AES";
private static final byte[] keyValue = getKeyBytes("12345678901234567890123456789012");
private static final byte[] INIT_VECTOR = new byte[16];
private static IvParameterSpec ivSpec = new IvParameterSpec(INIT_VECTOR);
public static void main(String[] args) throws Exception {
String encoded = encrypt("watson?");
System.out.println(encoded);
}
private static Key generateKey() throws Exception {
Key key = new SecretKeySpec(keyValue, ALGORITHM);
// SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// key = keyFactory.generateSecret(new DESKeySpec(keyValue));
return key;
}
private static byte[] getKeyBytes(String key) {
byte[] hash = DigestUtils.sha(key); // key.getBytes()
byte[] saltedHash = new byte[16];
System.arraycopy(hash, 0, saltedHash, 0, 16);
return saltedHash;
}
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, key,ivSpec);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = new BASE64Encoder().encode(encValue);
return encryptedValue;
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}返回的字节数不同,提前谢谢。
发布于 2010-11-02 13:13:54
您在CBC模式和PKC5Padding中使用AES加密数据,但只使用纯AES进行解密。在decrypt方法中,您需要使用"AES/CBC/PKCS5Padding“创建Cipher,就像在encrypt方法中一样。
https://stackoverflow.com/questions/3032832
复制相似问题