最近在调试一个加密和解密的接口,用 ruby 加密,然后用 java 解密,在用 java 解密时错误。然后调试中分别用 ruby 和 java 给数据加密,看是否一致,结果发现加密的结果也不一致,大神帮看看是什么原因
data = "45b00417-f7ca-4f53-bced-c1743d85604"
cipher = OpenSSL::Cipher::AES.new(128, :CBC)
cipher.encrypt
key = "quck7295abvdefgh"
iv = "abcdefgh3762quck"
encrypted = cipher.update(data) + cipher.final
Base64.encode64(encrypted)
使用相同的 key 来加密 ruby 加密后结果为:
双次加密后结果:"EAhESILT2j/MSa1CykE7yqtX7N8XvPVzrzewJoELRuPj+rK8DeSuxROD/uOq\nLqhy\n"
java 加密后结果为:
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class CipherUtil {
private final static byte[] KEY = "quck7295abvdefgh".getBytes();
private final static byte[] IV = "abcdefgh3762quck".getBytes();
public static byte[] encryption(byte[] data) throws Exception {
return cipherIV(Cipher.ENCRYPT_MODE, data);
}
public static byte[] decryption(byte[] data) throws Exception {
return cipherIV(Cipher.DECRYPT_MODE, data);
}
private static byte[] cipherIV(int mode, byte[] data) throws Exception {
SecretKeySpec sekey = new SecretKeySpec(KEY, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, sekey, new IvParameterSpec(IV));
byte[] decrypted = cipher.doFinal(data);
return decrypted;
}
private static byte[] cipher(int mode, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(mode, new SecretKeySpec(KEY, "AES"));
byte[] decrypted = cipher.doFinal(data);
return decrypted;
}
public static void main(String[] args) throws Exception {
String str = "45b00417-f7ca-4f53-bced-c1743d85604";
byte[] b = encryption(str.getBytes());
String str1 = new String(Base64.encodeToString(b));
System.out.println(str);
System.out.println(str1);
System.out.println(new String(decryption(Base64.decode(str1))));
}
}
双次加密后:2TStMVj6tPz8m4o0hjSY/GwTfx4UXFfDti9yhiJ6fr2tQFQsfNDG4Mqb3wpNy6x1
还有就是,ruby 加密后所谓的标准填充模式是什么啊?