【发布时间】:2021-11-03 16:13:52
【问题描述】:
我试图将java 代码转换为python。试图为此目的使用pycryptodome 库。这是java 代码:
try {
String data= "shouldEncryptDATA";
String bas64ed= "";
int len12 = Integer.parseInt("12");
byte[] randomparam= new byte[len12];
new SecureRandom().nextBytes(randomparam);
SecretKeySpec secretKeySpec= new SecretKeySpec("1f1f7892GKG38815".getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(1, secretKeySpec, new GCMParameterSpec(Integer.parseInt("16") * 8, randomparam));
byte[] bytedata= cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
byte[] newbytearray= new byte[bytedata.length + len12];
System.arraycopy(randomparam, 0, newbytearray, 0, len12);
System.arraycopy(bytedata, 0, newbytearray, len12, bytedata.length);
bas64ed= Base64.getEncoder().encodeToString(newbytearray);
System.out.println("bas64ed: "+bas64ed);
System.out.println(URLEncoder.encode(bas64ed, "UTF-8"));
} catch (Exception unused_ex) {
System.out.println();
System.out.println("ERROR: " + unused_ex);
}
到目前为止,我尝试在python 代码下方模仿java 代码:
import base64
from Crypto.Cipher import AES
import urllib.parse
from Crypto.Random import get_random_bytes
data= "shouldEncryptDATA"
key = b '1f1f7892GKG38815'
len12 = 12
v1 = bytearray(len12)
cipher = AES.new(key, AES.MODE_GCM, nonce=get_random_bytes(12) )
ciphertext, tag = cipher.encrypt_and_digest(data.encode("utf8"))
base64ed = ""
for x in cipher.nonce, ciphertext, tag:
base64ed += base64.b64encode(x).decode('utf-8')
urlencoded = urllib.parse.quote_plus(base64ed+"\n")
print(urlencoded )
上面的python 代码生成一个output,但问题是当我将输出提供给decryption 代码时,我得到了MAC check Failed。所以我意识到我在python 代码中的实现有点问题,因为当Java 代码的输出传递给decryption 代码时,它可以工作并解密数据。那么如何正确地将Java 加密代码转换为Python?使用Pycryptodome 或任何其他合适的库。
【问题讨论】:
标签: java python encryption aes-gcm pycryptodome