利用Java如何实现一个AES256加密解密功能-创新互联
创新互联www.cdcxhl.cn八线动态BGP香港云服务器提供商,新人活动买多久送多久,划算不套路!
汉台网站建设公司创新互联建站,汉台网站设计制作,有大型网站制作公司丰富经验。已为汉台成百上千家提供企业网站建设服务。企业网站搭建\成都外贸网站建设公司要多少钱,请找那个售后服务好的汉台做网站的公司定做!利用Java如何实现一个AES256加密解密功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
一.代码
package com.handler; import java.io.UnsupportedEncodingException; import java.security.Key; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AES256Encryption{ public static final String KEY_ALGORITHM="AES"; public static final String CIPHER_ALGORITHM="AES/ECB/PKCS7Padding"; public static byte[] initkey() throws Exception{ //实例化密钥生成器 Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyGenerator kg=KeyGenerator.getInstance(KEY_ALGORITHM, "BC"); kg.init(256); kg.init(128); SecretKey secretKey=kg.generateKey(); return secretKey.getEncoded(); } public static byte[] initRootKey() throws Exception{ return new byte[] { 0x08, 0x08, 0x04, 0x0b, 0x02, 0x0f, 0x0b, 0x0c, 0x01, 0x03, 0x09, 0x07, 0x0c, 0x03, 0x07, 0x0a, 0x04, 0x0f, 0x06, 0x0f, 0x0e, 0x09, 0x05, 0x01, 0x0a, 0x0a, 0x01, 0x09, 0x06, 0x07, 0x09, 0x0d }; } public static Key toKey(byte[] key) throws Exception{ SecretKey secretKey=new SecretKeySpec(key,KEY_ALGORITHM); return secretKey; } public static byte[] encrypt(byte[] data,byte[] key) throws Exception{ Key k=toKey(key); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC"); cipher.init(Cipher.ENCRYPT_MODE, k); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data,byte[] key) throws Exception{ Key k =toKey(key); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); Cipher cipher=Cipher.getInstance(CIPHER_ALGORITHM, "BC"); cipher.init(Cipher.DECRYPT_MODE, k); return cipher.doFinal(data); } public static void main(String[] args) throws UnsupportedEncodingException{ String str="芸sweet"; //打印原文 System.out.println("原文:"+str); //密钥 byte[] key; try { //生成随机密钥 key = AES256Encryption.initkey(); //打印密钥 System.out.print("密钥:"); for(int i = 0;i System.out.printf("%x", key[i]); } System.out.print("n"); //加密 byte[] data=AES256Encryption.encrypt(str.getBytes(), key); //打印密文 System.out.print("加密后:"); for(int i = 0;i System.out.printf("%x", data[i]); } System.out.print("n"); //解密密文 data=AES256Encryption.decrypt(data, key); //打印原文 System.out.println("解密后:"+new String(data)); } catch (Exception e) { e.printStackTrace(); }
本文标题:利用Java如何实现一个AES256加密解密功能-创新互联
文章出自:http://ybzwz.com/article/dscpoo.html