首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将此Java加密代码转换为python

如何将此Java加密代码转换为python
EN

Stack Overflow用户
提问于 2021-09-06 15:12:01
回答 1查看 180关注 0票数 1

我试图将java代码转换为python。尝试将pycryptodome库用于此目的。这是java代码:

代码语言:javascript
复制
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);
}

到目前为止,我已经尝试了下面的来模仿java代码之上的代码:

代码语言:javascript
复制
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或任何其他合适的库。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-06 15:33:06

Python代码中的bug处于连接状态,它必须是:

代码语言:javascript
复制
base64ed = base64.b64encode(cipher.nonce + ciphertext + tag).decode('utf-8')

在此修复之后,如果将两种代码的密文与相同的输入数据(特别是相同的IV)进行比较,它们是相同的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69076789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档