JAVA中AES对称加密和解密以及与Python兼容

引言:本文主要解决Java中用AES加密及解密,同时可通过Python脚本对Java加密后的字符进行解密的操作。

由于近期工作中用到需要使用Java对一串密钥进行加密,并且后台通过Python语言读取加密后的密钥并解密,搜索了很多文章,索性最后实现了,自己整理一下。

Java语言实现AES加密及解密

  1 import java.io.IOException;
  2 import java.io.UnsupportedEncodingException;
  3 import java.security.InvalidAlgorithmParameterException;
  4 import java.security.InvalidKeyException;
  5 import java.security.NoSuchAlgorithmException;
  6 
  7 import javax.crypto.BadPaddingException;
  8 import javax.crypto.Cipher;
  9 import javax.crypto.IllegalBlockSizeException;
 10 import javax.crypto.NoSuchPaddingException;
 11 import javax.crypto.spec.IvParameterSpec;
 12 import javax.crypto.spec.SecretKeySpec;
 13 
 14 import org.apache.commons.lang.StringUtils;
 15 
 16 import sun.misc.BASE64Decoder;
 17 import sun.misc.BASE64Encoder;
 18 
 19 /**
 20  * <p>Title: TestAES3</p>
 21  * <p>Description: </p>
 22  * <p>Copyright: Copyright (c) 2012 All rights reserved.</p>
 23  * <p>Company: Neusoft Corporation, China, Ltd.</p>
 24  * @author chendch
 25  *
 26  */
 27 public class TestAES3
 28 {
 29   private String ALGO      = "AES";
 30   private String ALGO_MODE = "AES/CBC/NoPadding";
 31   private String akey      = "keyskeyskeyskeys";
 32   private String aiv       = "keyskeyskeyskeys";
 33   private String padding   = " ";
 34   private int    blockSize = 16;
 35 
 36   /**
 37    * @param content
 38    * @return password
 39    * @throws NoSuchAlgorithmException
 40    * @throws NoSuchPaddingException
 41    * @throws UnsupportedEncodingException 
 42    * @throws InvalidAlgorithmParameterException 
 43    * @throws InvalidKeyException 
 44    * @throws BadPaddingException 
 45    * @throws IllegalBlockSizeException 
 46    */
 47   public String encrypt(String content)
 48     throws NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
 49     BadPaddingException
 50   {
 51     String encryptContent = content;
 52     if (encryptContent.length() < blockSize)
 53     {
 54       encryptContent = StringUtils.rightPad(content, blockSize, padding);
 55       System.out.println("补位后:" + encryptContent);
 56     }
 57 
 58     Cipher cipher = Cipher.getInstance(ALGO_MODE);
 59     SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
 60     IvParameterSpec ivspec = new IvParameterSpec(aiv.getBytes("utf-8"));
 61     cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
 62     byte[] byteEncode = encryptContent.getBytes("utf-8");
 63     byte[] byteAES = cipher.doFinal(byteEncode);
 64 
 65     String AESEncode = new String(new BASE64Encoder().encode(byteAES));
 66 
 67     return AESEncode;
 68   }
 69 
 70   /**
 71    * @param content
 72    * @return content
 73    * @throws NoSuchAlgorithmException
 74    * @throws NoSuchPaddingException
 75    * @throws InvalidKeyException
 76    * @throws InvalidAlgorithmParameterException
 77    * @throws IllegalBlockSizeException
 78    * @throws BadPaddingException
 79    * @throws IOException
 80    */
 81   public String decrypt(String content)
 82     throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
 83     BadPaddingException, IOException
 84   {
 85     byte[] byte_content = new BASE64Decoder().decodeBuffer(content);
 86 
 87     Cipher cipher = Cipher.getInstance(ALGO_MODE);
 88     SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
 89     IvParameterSpec ivspec = new IvParameterSpec(aiv.getBytes("utf-8"));
 90 
 91     cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
 92 
 93     byte[] byte_decode = cipher.doFinal(byte_content);
 94     String AES_decode = new String(byte_decode, "utf-8");
 95     return AES_decode.trim();
 96   }
 97 
 98   /**
 99    * @param args
100    * @throws NoSuchAlgorithmException
101    * @throws NoSuchPaddingException
102    * @throws BadPaddingException 
103    * @throws IllegalBlockSizeException 
104    * @throws InvalidAlgorithmParameterException 
105    * @throws InvalidKeyException 
106    * @throws IOException 
107    */
108   public static void main(String[] args)
109     throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException,
110     BadPaddingException, IOException
111   {
112     TestAES3 testAES3 = new TestAES3();
113     String content = "chenduoc";
114     System.out.println("加密前:" + content);
115 
116     String encryptContent = testAES3.encrypt(content);
117     System.out.println("加密后:" + encryptContent);
118 
119     String decryptContent = testAES3.decrypt(encryptContent);
120     System.out.println("解密后:" + decryptContent);
121   }
122 }

Python实现AES加密及解密

#!/usr/bin/python
#coding=utf-8

from Crypto.Cipher import AES
import base64

BLOCK_SIZE = 16
PADDING = " "
key = "keyskeyskeyskeys"
iv = "keyskeyskeyskeys"

pad_it = lambda s : s+(BLOCK_SIZE - len(s)) * PADDING

def encrypt(content):
    generator = AES.new(key, AES.MODE_CBC, iv)  
    encrypt_content = generator.encrypt(pad_it(content))
    encode_content = base64.b64encode(encrypt_content)
    
    return encode_content

def decrypt(content):  
    generator = AES.new(key, AES.MODE_CBC, iv)  
    decode_content = base64.b64decode(content)
    decrypt_content = generator.decrypt(decode_content)

    return decrypt_content.rstrip(PADDING)

content = "neteye"
print "加密前:",content

encrypt_contnet = encrypt(content)
print "加密后:",encrypt_contnet

decrypt_content = decrypt(encrypt_contnet)
print "解密后:",decrypt_content

注意点:Java中定义的key和iv变量和python中定义的必须一致,且加密的字符串需满足16位或24位等,不满足时需要进行补位,以上程序都已实现且可用。

原文地址:https://www.cnblogs.com/chen-dch/p/7716668.html