我尝试执行AES .NET
中讨论的相同步骤但没有成功,我似乎无法让java和slowAes玩toghter ...附件是我的代码我很抱歉我无法添加更多这是我第一次尝试处理加密会欣赏任何帮助
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;
}
返回的字节不同 提前谢谢。
答案 0 :(得分:2)
您在CBC模式和PKC5Padding中使用AES加密数据,但您只使用普通AES进行解密。在您的解密方法中,您需要使用“AES / CBC / PKCS5Padding”创建密码,就像在加密方法中一样。