Keep on going, never give up.

Java AES加密解密实现

本文总结Java AES加密解密应用实例,Java加密解密库都很完善,所以,调用方法也都非常简单,但Java代码以低效率著称,所以,对时效性要求太高的尽量避开Java层而使用C/C++等程序实现。C/C++ AES算法实现可参考天缘前一篇文章《AES CBC和CTR加解密实例》。

基础知识,AES模式区别:AES CFB/OFB/ECB/CBC/CTR优缺点

Java示例代码如下:

默认使用AES128 ECB/NoPadding,具体参数设置可参考文末地址。因为是NoPadding,所以,要求输入的数据长度必须为16Byte倍数。如果使用CBC模式,还需附带IV参量。

import java.security.SecureRandom;
import java.security.Key;
import java.security.Security;

import javax.crypto.SecretKey;  
import javax.crypto.SecretKeyFactory;
import javax.crypto.KeyGenerator;
import javax.crypto.Cipher;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.spec.IvParameterSpec;

//AES 128
public class ComCipher {
	private byte[] btAESKey	= new byte[16];//128 bits AES
	private Cipher 		  cObj;
	private SecretKeySpec 	sAesKey;
	
	public ComCipher(){
		int i=0;
		for(i=0;i<16;i++)
			btAESKey[i]=0x01;
	}

	public void AESInit()  throws Exception{
		sAesKey  = new SecretKeySpec(btAESKey, "AES");
		cObj = Cipher.getInstance("AES/ECB/NoPadding");//NoPadding PKCS5Padding
	}
	
    //AES Encrypt content
    public byte[] AESEncrypt(byte[] btCont)  throws Exception {
       	cObj.init(Cipher.ENCRYPT_MODE, sAesKey);
        return cObj.doFinal(btCont);
    }	

    //AES Decrypt content 
    public byte[] AESDecrypt(byte[] btCont)  throws Exception {
    	cObj.init(Cipher.DECRYPT_MODE, sAesKey);
        return cObj.doFinal(btCont);
    }	
	
}

用法如下:

	ComCipher ObjCipher = new ComCipher();
	try {
		int iLen=8;
		byte[] c1 = new byte[iLen];
		for(int k=0;k<iLen;k++)
			c1[k]=0x01;
		ObjCipher.AESInit();
	        byte[] resC = ObjCipher.AESEncrypt(c1);
		System.out.println("AESEnc:"+HexToString(resC,resC.length));
	        byte[] resD = ObjCipher.AESDecrypt(resA);
		System.out.println("AESDec:"+HexToString(resD,resD.length));
	 } catch (Exception e1) {
            e1.printStackTrace();
	 }	

上述代码中,HexToString打印Byte数组到字符串,源码略。

示例比较结果(顺序为:明文、密钥、加密方法、加密结果):

SOURCE:1111111111111111

PASSWD:8888888888888888

METHOD:128位AES/ECB/PKCS5Padding

RESULT:9F1D54A6A3AC2637217EBF9E8A04A01C7DA918723FEE1CD054EBEF46C620DA51

METHOD:256位AES/ECB/PKCS5Padding

RESULT:356617045B4D39F98DEA0A89DC6C88ED258DEE6834CD12CFF4751C5EB557EADC

参考资料:

http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

http://docs.oracle.com/javase/7/docs/api/java/security/Key.html

http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Cipher

http://stackoverflow.com/questions/9381270/aes-cbc-pkcs5padding-java-encrypting-error-javax-crypto-badpaddingexception-g 

相关评论(0):  

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

最新文章

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载也必须遵循“署名-非商业用途-保持一致”的创作共用协议. 返回顶部
Copyright@2005-2016 Metsky.com, All rights Reserved.