資源描述:
《AES加密算法的java實現(xiàn).doc》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、packagecom.encryp;importjava.security.InvalidKeyException;importjava.security.NoSuchAlgorithmException;importjava.security.Security;importjavax.crypto.BadPaddingException;importjavax.crypto.Cipher;importjavax.crypto.IllegalBlockSizeException;importjavax.crypto.KeyGenerator;i
2、mportjavax.crypto.NoSuchPaddingException;importjavax.crypto.SecretKey;publicclassEncrypAES{//KeyGenerator提供對稱密鑰生成器的功能,支持各種算法privateKeyGeneratorkeygen;//SecretKey負責保存對稱密鑰privateSecretKeydeskey;//Cipher負責完成加密或解密工作privateCipherc;//該字節(jié)數(shù)組負責保存加密的結(jié)果privatebyte[]cipherByte;publicEnc
3、rypAES()throwsNoSuchAlgorithmException,NoSuchPaddingException{Security.addProvider(newcom.sun.crypto.provider.SunJCE());//實例化支持DES算法的密鑰生成器(算法名稱命名需按規(guī)定,否則拋出異常)keygen=KeyGenerator.getInstance("AES");//生成密鑰deskey=keygen.generateKey();//生成Cipher對象,指定其支持的DES算法c=Cipher.getInstance(
4、"AES");}/***對字符串加密**@paramstr*@return*@throwsInvalidKeyException*@throwsIllegalBlockSizeException*@throwsBadPaddingException*/publicbyte[]Encrytor(Stringstr)throwsInvalidKeyException,IllegalBlockSizeException,BadPaddingException{//根據(jù)密鑰,對Cipher對象進行初始化,ENCRYPT_MODE表示加密模式c.init
5、(Cipher.ENCRYPT_MODE,deskey);byte[]src=str.getBytes();//加密,結(jié)果保存進cipherBytecipherByte=c.doFinal(src);returncipherByte;}/***對字符串解密**@parambuff*@return*@throwsInvalidKeyException*@throwsIllegalBlockSizeException*@throwsBadPaddingException*/publicbyte[]Decryptor(byte[]buff)throw
6、sInvalidKeyException,IllegalBlockSizeException,BadPaddingException{//根據(jù)密鑰,對Cipher對象進行初始化,DECRYPT_MODE表示加密模式c.init(Cipher.DECRYPT_MODE,deskey);cipherByte=c.doFinal(buff);returncipherByte;}/***@paramargs*@throwsNoSuchPaddingException*@throwsNoSuchAlgorithmException*@throwsBadP
7、addingException*@throwsIllegalBlockSizeException*@throwsInvalidKeyException*/publicstaticvoidmain(String[]args)throwsException{EncrypAESde1=newEncrypAES();Stringmsg="郭XX-搞笑相聲全集";byte[]encontent=de1.Encrytor(msg);byte[]decontent=de1.Decryptor(encontent);System.out.println("明文
8、是:"+msg);System.out.println("加密后:"+newString(encontent));System.out.println