微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

AES GCM 解密用 Java 加密的 Python 中的文本

如何解决AES GCM 解密用 Java 加密的 Python 中的文本

请帮助在 Python 中为以下 aes-gcm 获取等效的解密代码

private static final String IV = "0123456789ABCDEF0123456789ABCDEF";
private static final String IV = "0123456789ABCDEF";
private static final String ALGORITHMSTR = "AES/GCM/nopadding";
private static final String DEFAULT_CODING = "utf-8";
private static final String KEY = "super secret";

private String encrypt(String valuetoEnrypt) {
String encryptKey = "";
        encryptKey = KEY;
        byte[] input = valuetoEncrypt.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(encryptKey.getBytes("UTF-8"));
        String myHash = DatatypeConverter.printHexBinary(thedigest).toLowerCase();
        
        //System.out.println("HASH :: "+myHash);    
        SecretKeySpec skc = new SecretKeySpec(myHash.getBytes(),"AES");
        GCMParameterSpec ivspec = new GCMParameterSpec(128,(IV.getBytes(DEFAULT_CODING)));
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE,skc,ivspec);
        byte[] cipherText = new byte[cipher.getoutputSize(input.length)];
        int ctLength = cipher.update(input,input.length,cipherText,0);
        ctLength += cipher.doFinal(cipherText,ctLength);
        return Base64.getEncoder().encodetoString(cipherText);
}
public static String decrypt(String valuetoDecrypt) throws Exception {
        String decryptKey = KEY;
        byte[] keyb = decryptKey.getBytes(DEFAULT_CODING);
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] thedigest = md.digest(keyb);
        String myHash = DatatypeConverter.printHexBinary(thedigest).toLowerCase();
        SecretKeySpec skey = new SecretKeySpec(myHash.getBytes(),(IV.getBytes(DEFAULT_CODING)));
        Cipher dcipher = Cipher.getInstance(ALGORITHMSTR);
        dcipher.init(Cipher.DECRYPT_MODE,skey,ivspec);
        byte[] clearbyte = dcipher.doFinal(Base64.getDecoder().decode(valuetoDecrypt));
        return new String(clearbyte,DEFAULT_CODING);
}

代码适用于任何密钥长度的加密和解密。我需要Python中的等效代码,它可以解密通过上述Java加密方法加密的文本。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。