AES encryption and decryption: Python and Java implement AES mutual encryption and decryption

antecedent

It is necessary to use Python and Java to implement the same AES encryption and decryption algorithm, so that the ciphertext encrypted by the Python version can be decrypted by the Java code, and vice versa.

Python implementation

Python is version 3.6

 
  1. # -*- coding: utf-8 -*-

  2. import base64

  3. from Crypto.Cipher import AES

  4. from urllib import parse

  5.  
  6. AES_SECRET_KEY = 'lingyejunAesTest' #此处16|24|32个字符

  7. IV = "1234567890123456"

  8.  
  9. # padding算法

  10. BS = len(AES_SECRET_KEY)

  11. pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)

  12. unpad = lambda s: s[0:-ord(s[-1:])]

  13.  
  14.  
  15. class AES_ENCRYPT(object):

  16. def __init__(self):

  17. self.key = AES_SECRET_KEY

  18. self.mode = AES.MODE_CBC

  19.  
  20. #加密函数

  21. def encrypt(self, text):

  22. cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))

  23. self.ciphertext = cryptor.encrypt(bytes(pad(text), encoding="utf8"))

  24. #AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码

  25. return base64.b64encode(self.ciphertext)

  26.  
  27. #解密函数

  28. def decrypt(self, text):

  29. decode = base64.b64decode(text)

  30. cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))

  31. plain_text = cryptor.decrypt(decode)

  32. return unpad(plain_text)

  33.  
  34. if __name__ == '__main__':

  35. aes_encrypt = AES_ENCRYPT()

  36. my_email = "[email protected]"

  37. e = aes_encrypt.encrypt(my_email)

  38. d = aes_encrypt.decrypt(e)

  39. print(my_email)

  40. print(e)

  41. print(d)

 

Java implementation

 
  1. import sun.misc.BASE64Decoder;

  2. import sun.misc.BASE64Encoder;

  3.  
  4. import javax.crypto.Cipher;

  5. import javax.crypto.spec.IvParameterSpec;

  6. import javax.crypto.spec.SecretKeySpec;

  7.  
  8. public class AesTest {

  9.  
  10. /**

  11. * 加密用的Key 可以用26个字母和数字组成

  12. * 此处使用AES-128-CBC加密模式,key需要为16位。

  13. */

  14. private static String sKey = "lingyejunAesTest";

  15. private static String ivParameter = "1234567890123456";

  16.  
  17. // 加密

  18. public static String encrypt(String sSrc) throws Exception {

  19. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  20. byte[] raw = sKey.getBytes();

  21. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

  22. IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度

  23. cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

  24. byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

  25. return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。

  26. }

  27.  
  28. // 解密

  29. public static String decrypt(String sSrc) {

  30. try {

  31. byte[] raw = sKey.getBytes("ASCII");

  32. SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

  33. Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

  34. IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());

  35. cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

  36. byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密

  37. byte[] original = cipher.doFinal(encrypted1);

  38. String originalString = new String(original, "utf-8");

  39. return originalString;

  40. } catch (Exception ex) {

  41. return null;

  42. }

  43. }

  44.  
  45. public static void main(String[] args) {

  46. String email = "[email protected]";

  47. try {

  48. String sec = encrypt(email);

  49. System.out.println(sec);

  50. System.out.println(decrypt("CcOtM9WXv0N+Owh/xxedZJnuNUaTU7y3aUBESQLUvVM="));

  51. } catch (Exception e) {

  52. e.printStackTrace();

  53. }

  54. }

  55. }

Then put the key encrypted by the Java code into Python for decryption

That's it, the conversion of AES between Java and Python is realized.

Reprinted at: https://www.cnblogs.com/lingyejun/p/10971308.html

 

 


Python3.6 and Java implement AES mutual encryption and decryption

 

Install the Crypto module

pip install pycryptodome
  • After the installation is successful, you  导入模块报错 need to modify the installation package name
# 找到安装包路径
# C:\python36\Lib\site-packages
# 在这个目录你找到这个文件夹的名字:crypto
# 将这个文件夹的名字改为: Crypto

Python version

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES

# 此处16|24|32个字符 默认16
AES_KEY = "aesencryptiontst"
IV = "1234567890123456"

# Padding算法
BS = len(AES_KEY)
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1:])]


class AESEncrypt(object):
    def __init__(self):
        self.key = AES_KEY
        self.mode = AES.MODE_CBC

    # 加密函数
    def encrypt(self, text):
        cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
        self.ciphertext = cryptor.encrypt(bytes(pad(text), encoding="utf8"))
        # AES加密时候得到的字符串不一定是ascii字符集的,输出到终端或者保存时候可能存在问题,使用base64编码
        return base64.b64encode(self.ciphertext)

    # 解密函数
    def decrypt(self, text):
        decode = base64.b64decode(text)
        cryptor = AES.new(self.key.encode("utf8"), self.mode, IV.encode("utf8"))
        plain_text = cryptor.decrypt(decode)
        return unpad(plain_text)


if __name__ == '__main__':
    aes_encrypt = AESEncrypt()
    # 加密文本
    aes_text = "aestest"
    encrypt = aes_encrypt.encrypt(aes_text)
    aes_encrypt = aes_encrypt.decrypt(encrypt)
    print("加密文本: ", aes_text)
    print("加密后: ", encrypt)
    print("解密后: ", aes_encrypt)

Java version

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
 
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
 
public class AesTest {
 
    /**
     * 加密用的Key 可以用26个字母和数字组成
     * 此处使用AES-128-CBC加密模式,key需要为16位。
     */
    private static String sKey = "aesencryptiontst";
    private static String ivParameter = "1234567890123456";
 
    // 加密
    public static String encrypt(String sSrc) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = sKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());//使用CBC模式,需要一个向量iv,可增加加密算法的强度
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
        return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    }
 
    // 解密
    public static String decrypt(String sSrc) {
        try {
            byte[] raw = sKey.getBytes("ASCII");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);//先用base64解密
            byte[] original = cipher.doFinal(encrypted1);
            String originalString = new String(original, "utf-8");
            return originalString;
        } catch (Exception ex) {
            return null;
        }
    }
 
    public static void main(String[] args) {
        String aes_text = "aestest";
        try {
            String sec = encrypt(aes_text);
            System.out.println(sec);
            System.out.println(decrypt("CcOtM9WXv0N+Owh/xxedZJnuNUaTU7y3aUBESQLUvVM="));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Guess you like

Origin blog.csdn.net/zzddada/article/details/115356025