参考博客:https://blog.csdn.net/weixin_42068117/article/details/80084034
工作中开发人员用的是Java,但是写mock用的是Python,所以Java的加密解密算法转Python遇到了不少坑。下面以AES算法为例说明一下。
Java加密:
1 /** 2 * aes加密-128位 3 * 4 */ 5 public static String AesEncrypt(String content ,String key){ 6 if (StringUtils.isEmpty(key) || key.length() != 16) { 7 throw new RuntimeException("密钥长度为16位"); 8 } 9 try { 10 String iv = key; 11 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 12 int blockSize = cipher.getBlockSize(); 13 byte[] dataBytes = content.getBytes("utf-8"); 14 int plaintextLength = dataBytes.length; 15 if (plaintextLength % blockSize != 0) { 16 plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); 17 } 18 byte[] plaintext = new byte[plaintextLength]; 19 System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); 20 SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); 21 IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); 22 cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); 23 byte[] encrypted = cipher.doFinal(plaintext); 24 return byte2Hex(encrypted); 25 26 } catch (Exception e) { 27 throw new RuntimeException("aes加密发生错误", e); 28 } 29 }
Java解密:
1 // ==Aes加解密================================================================== 2 /** 3 * aes解密-128位 4 */ 5 public static String AesDecrypt(String encryptContent, String password) { 6 if (StringUtils.isEmpty(password) || password.length() != 16) { 7 throw new RuntimeException("密钥长度为16位"); 8 } 9 try { 10 String key = password; 11 String iv = password; 12 byte[] encrypted1 = hex2Bytes(encryptContent); 13 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); 14 SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); 15 IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); 16 cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); 17 byte[] original = cipher.doFinal(encrypted1); 18 return new String(original,"UTF-8").trim(); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 throw new RuntimeException("aes解密发生错误", e); 22 } 23 }
对应Python加密:
1 def aes_encrypt(data, key): 2 """aes加密函数,如果data不是16的倍数【加密文本data必须为16的倍数!】,那就补足为16的倍数 3 :param key: 4 :param data: 5 """ 6 cipher = AES.new(key, AES.MODE_CBC, key) # 设置AES加密模式 此处设置为CBC模式 7 block_size = AES.block_size 8 # 判断data是不是16的倍数,如果不是用b' '补足 9 if len(data) % block_size != 0: 10 add = block_size - (len(data) % block_size) 11 else: 12 add = 0 13 data += b'