[英]AES Encryption in Java porting to Python
我在 Java 中有一個現有系統,我正在嘗試移植到 Python 執行 AES 加密,如下所示:
public static String encrypt(String text, SecretKey secretKey) throws Exception {
byte[] cipherText = null;
String encryptedString = null;
// get an RSA cipher object and print the provider
Cipher cipher = Cipher.getInstance(SYMMETRIC_KEY_ALGORITHM); // AES
// encrypt the plain text using the public key
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
cipherText = cipher.doFinal(text.getBytes());
encryptedString = Base64.getEncoder().encodeToString(cipherText);
return encryptedString;
}
我遇到的問題是嘗試使用 Python 和 Cryptography 庫來獲得相同的 AES 設置組合以獲得相同的結果:
我從看似已失效的 PyCrypto 庫中看到了很多示例,我什至無法將它們安裝在我的 Windows 系統上,工作量要少得多。
我最近的嘗試是這樣的,我確實得到了加密,但它與 Java AES output 不匹配:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
key = b'Some random key '
cipher = Cipher(algorithms.AES(key), modes.GCM(b'000000000000'))
encryptor = cipher.encryptor()
ct = encryptor.update(ENC_MESSAGE)
base64EncodedStr = base64.b64encode(ct).decode('utf-8')
print('BASE64:', base64EncodedStr)
您需要兩個版本之間的所有內容都完全相同。 目前這不是真的; 解決這個問題。
您的 java 代碼使用:
對於其中的大多數,我根本無法告訴你; 您粘貼的代碼不足。 例如,AES 密鑰大小以及密鑰是否實際上相同? 我不知道——你告訴我。 您是如何制作SecretKey key
object 的?
我對 python 不太熟悉,但它確實看起來像你對它進行 base64 編碼,然后再次解碼。 那是..不,不要那樣做。 您的 java 代碼進行編碼,僅此而已。 您的 python 代碼應該 base64 編碼,就是這樣。
我很確定 python 也默認為 PKCS5Padding。
這使得 java 和 python 之間 100% 不匹配的編碼模式給出了您粘貼的少量代碼以及構建密鑰的方式。 如果您要加密的文本不是純 ASCII,則字符集編碼很可能也會造成差異。
這是加密貨幣。 一個微小的差異,輸出就會完全不同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.