java 和Python ASE加密解密

java实现


@Slf4j
public class AESUtil {

  private static String ivParameter = "t234DsfDgdKKAVDd";
  private static String salt = "Loefcodr046DKRVd";

  /**
   * 解密.
   */
  public String decrypt(String sSrc) {
    try {
      byte[] raw = salt.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;
    }
  }

  /**
   * 加密.
   * @param sSrc sSrc.
   * @return String.
   */
  public String encrypt(String sSrc) {
    try {
      Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      byte[] raw = salt.getBytes();
      SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

      //使用CBC模式,需要一个向量iv,可增加加密算法的强度
      IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
      cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
      byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));
      return new BASE64Encoder().encode(encrypted);//此处使用BASE64做转码。
    } catch (Exception ex) {
      return null;
    }
  }
}

Python实现

# -*- coding: utf-8 -*-
import base64
from Crypto.Cipher import AES
from urllib import parse

AES_SECRET_KEY = 'lingyejunAesTest' #此处16|24|32个字符
IV = "qqqqqqqqqqqqqqqq"

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


class AES_ENCRYPT(object):
    def __init__(self):
        self.key = AES_SECRET_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 = AES_ENCRYPT()
    my_email = "notice-dev_0000050052_0187957896_5e1f11f2146e87000163d083"
    e = aes_encrypt.encrypt(my_email)
    d = aes_encrypt.decrypt(e)
    print(my_email)
    print(e)
    print(d)
发布了46 篇原创文章 · 获赞 1 · 访问量 5122

猜你喜欢

转载自blog.csdn.net/poplarandwillow/article/details/104003000