importjava.security.InvalidKeyException;
importjava.security.Key;
importjava.security.NoSuchAlgorithmException;
importjavax.crypto.*;
importjavax.crypto.spec.*;
/**
*
*@authorwchun
*
*AES128演算法,加密模式為ECB,填充模式為pkcs7(實際就是pkcs5)
*
*
*/
publicclassAES{
staticfinalStringalgorithmStr="AES/ECB/PKCS5Padding";
;
staticprivateCiphercipher;
staticbooleanisInited=false;
//初始化
staticprivatevoidinit()
{
//初始化keyGen
try{
keyGen=KeyGenerator.getInstance("AES");
}catch(NoSuchAlgorithmExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
keyGen.init(128);
//初始化cipher
try{
cipher=Cipher.getInstance(algorithmStr);
}catch(NoSuchAlgorithmExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
isInited=true;
}
publicstaticbyte[]GenKey()
{
if(!isInited)//如果沒有初始化過,則初始化
{
init();
}
returnkeyGen.generateKey().getEncoded();
}
publicstaticbyte[]Encrypt(byte[]content,byte[]keyBytes)
{
byte[]encryptedText=null;
if(!isInited)//為初始化
{
init();
}
Keykey=newSecretKeySpec(keyBytes,"AES");
try{
cipher.init(Cipher.ENCRYPT_MODE,key);
}catch(InvalidKeyExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
try{
encryptedText=cipher.doFinal(content);
}catch(IllegalBlockSizeExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(BadPaddingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnencryptedText;
}
//解密為byte[]
publicstaticbyte[]DecryptToBytes(byte[]content,byte[]keyBytes)
{
byte[]originBytes=null;
if(!isInited)
{
init();
}
Keykey=newSecretKeySpec(keyBytes,"AES");
try{
cipher.init(Cipher.DECRYPT_MODE,key);
}catch(InvalidKeyExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
//解密
try{
originBytes=cipher.doFinal(content);
}catch(IllegalBlockSizeExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}catch(BadPaddingExceptione){
//TODOAuto-generatedcatchblock
e.printStackTrace();
}
returnoriginBytes;
}
}
② 請教個關於Java實現AES加解密的問題
JDK對DESede演算法的支持
密鑰長度:128位
工作模式:ECB/CBC/PCBC/CTR/CTS/CFB/CFB8 to CFB128/OFB/OBF8 to OFB128
填充方式:Nopadding/PKCS5Padding/ISO10126Padding/
AES加密解密的java實現:
package com.kongxincai.encanddec;import java.security.Key;import java.security.NoSuchAlgorithmException;import javax.crypto.Cipher;import javax.crypto.KeyGenerator;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;public class AESCoder { private static final String KEY_ALGORITHM = "AES"; private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";//默認的加密演算法
public static byte[] initSecretKey() { //返回生成指定演算法密鑰生成器的 KeyGenerator 對象
KeyGenerator kg = null; try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace(); return new byte[0];
} //初始化此密鑰生成器,使其具有確定的密鑰大小 //AES 要求密鑰長度為 128
kg.init(128); //生成一個密鑰
SecretKey secretKey = kg.generateKey(); return secretKey.getEncoded();
} private static Key toKey(byte[] key){ //生成密鑰
return new SecretKeySpec(key, KEY_ALGORITHM);
} public static byte[] encrypt(byte[] data,Key key) throws Exception{ return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] encrypt(byte[] data,byte[] key) throws Exception{ return encrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] encrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{ //還原密鑰
Key k = toKey(key); return encrypt(data, k, cipherAlgorithm);
} public static byte[] encrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //實例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm); //使用密鑰初始化,設置為加密模式 cipher.init(Cipher.ENCRYPT_MODE, key); //執行操作
return cipher.doFinal(data);
} public static byte[] decrypt(byte[] data,byte[] key) throws Exception{ return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] decrypt(byte[] data,Key key) throws Exception{ return decrypt(data, key,DEFAULT_CIPHER_ALGORITHM);
} public static byte[] decrypt(byte[] data,byte[] key,String cipherAlgorithm) throws Exception{ //還原密鑰
Key k = toKey(key); return decrypt(data, k, cipherAlgorithm);
} public static byte[] decrypt(byte[] data,Key key,String cipherAlgorithm) throws Exception{ //實例化
Cipher cipher = Cipher.getInstance(cipherAlgorithm); //使用密鑰初始化,設置為解密模式 cipher.init(Cipher.DECRYPT_MODE, key); //執行操作
return cipher.doFinal(data);
} private static String showByteArray(byte[] data){ if(null == data){ return null;
}
StringBuilder sb = new StringBuilder("{"); for(byte b:data){
sb.append(b).append(",");
}
sb.deleteCharAt(sb.length()-1);
sb.append("}"); return sb.toString();
} public static void main(String[] args) throws Exception { byte[] key = initSecretKey();
System.out.println("key:"+showByteArray(key));
Key k = toKey(key); //生成秘鑰
String data ="AES數據";
System.out.println("加密前數據: string:"+data);
System.out.println("加密前數據: byte[]:"+showByteArray(data.getBytes()));
System.out.println(); byte[] encryptData = encrypt(data.getBytes(), k);//數據加密
System.out.println("加密後數據: byte[]:"+showByteArray(encryptData));// System.out.println("加密後數據: hexStr:"+Hex.encodeHexStr(encryptData)); System.out.println(); byte[] decryptData = decrypt(encryptData, k);//數據解密
System.out.println("解密後數據: byte[]:"+showByteArray(decryptData));
System.out.println("解密後數據: string:"+new String(decryptData));
}
}
③ JAVA AES加密
這篇文章有詳細的AES演算法的使用講解,希望可以幫助到你,https://blog.csdn.net/xingkong_hdc/article/details/79413462
④ 一段簡單的java語言逐句分析
1、KeyGenerator kgen = KeyGenerator.getInstance("AES"); //實例化一個用AES加密演算法的密鑰生成器
2、kgen.init(128, new SecureRandom(password.getBytes())); //使用用戶提供的password初始化此密鑰生成器,使其具有確定的密鑰大小128位元組長。
3、SecretKey secretKey = kgen.generateKey(); //生成一個密鑰。
4、byte[] enCodeFormat = secretKey.getEncoded(); //返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回 null。
5、SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES"); //根據給定的。
6、enCodeFormat位元組數組構造一個用AES演算法加密的密鑰。
7、Cipher cipher = Cipher.getInstance("AES");// 創建密碼器 。
8、byte[] byteContent = content.getBytes("utf-8"); //使用給定的 UTF-8編碼將此 String
編碼到 byte 序列,並將結果存儲到byteContent 數組。
9、cipher.init(Cipher.ENCRYPT_MODE, key);// 以加密的方式用密鑰初始化此 Cipher。
10、byte[] result = cipher.doFinal(byteContent); 按byteContent單部分操作加密指定的。
11、return result; // 加密 返回加密過後的byteContent
12、建議:下載個jdk中文文檔。自己對照就會了。
⑤ java實現ase加密解密
這個演算法java SDK自帶的額 參考代碼如下:
/**解密
*@paramcontent待解密內容
*@parampassword解密密鑰
*@return
*/
publicstaticbyte[]decrypt(byte[]content,Stringpassword){
try{
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
kgen.init(128,newSecureRandom(password.getBytes()));
SecretKeysecretKey=kgen.generateKey();
byte[]enCodeFormat=secretKey.getEncoded();
SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");
Ciphercipher=Cipher.getInstance("AES");//創建密碼器
cipher.init(Cipher.DECRYPT_MODE,key);//初始化
byte[]result=cipher.doFinal(content);
returnresult;//加密
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(InvalidKeyExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
returnnull;
}
/**
*加密
*
*@paramcontent需要加密的內容
*@parampassword加密密碼
*@return
*/
publicstaticbyte[]encrypt(Stringcontent,Stringpassword){
try{
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
kgen.init(128,newSecureRandom(password.getBytes()));
SecretKeysecretKey=kgen.generateKey();
byte[]enCodeFormat=secretKey.getEncoded();
SecretKeySpeckey=newSecretKeySpec(enCodeFormat,"AES");
Ciphercipher=Cipher.getInstance("AES");//創建密碼器
byte[]byteContent=content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE,key);//初始化
byte[]result=cipher.doFinal(byteContent);
returnresult;//加密
}catch(NoSuchAlgorithmExceptione){
e.printStackTrace();
}catch(NoSuchPaddingExceptione){
e.printStackTrace();
}catch(InvalidKeyExceptione){
e.printStackTrace();
}catch(UnsupportedEncodingExceptione){
e.printStackTrace();
}catch(IllegalBlockSizeExceptione){
e.printStackTrace();
}catch(BadPaddingExceptione){
e.printStackTrace();
}
returnnull;
}
http://blog.csdn.net/hbcui1984/article/details/5201247
圖像界面的話就不說了
⑥ java如何用Aes加密和解密
你解密的key必須是加密的key啊
你看看,你解密的時候又KeyGenerator.getInstance("AES").generateKey();這是重新搞了回一個key啊,當然解答不出來了
我估計你這代碼人家原先是寫在一起的吧,加密完了再直接解密給你看,人家只generateKey一次,自然很順利,你分成了兩個例子,居然分別generateKey,自然失敗
⑦ JAVA AES演算法,詳細點。
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
/**
* This program generates a AES key, retrieves its raw bytes, and
* then reinstantiates a AES key from the key bytes.
* The reinstantiated key is used to initialize a AES cipher for
* encryption and decryption.
*/
public class AES {
/**
* Turns array of bytes into string
*
* @param buf Array of bytes to convert to hex string
* @return Generated hex string
*/
public static String asHex (byte buf[]) {
StringBuffer strbuf = new StringBuffer(buf.length * 2);
int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception {
String message="This is just an example";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted =
cipher.doFinal((args.length == 0 ?
"This is just an example" : args[0]).getBytes());
System.out.println("encrypted string: " + asHex(encrypted));
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original =
cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Original string: " +
originalString + " " + asHex(original));
}
}
參看 SUN的文檔http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
⑧ java的aes加密成多少位數
深圳遠標幫你:
1.默認 Java 中僅支持 128 位密鑰,當使用 256 位密鑰的時候,會報告密鑰長度錯誤
Invalid AES key length
你需要下載一個支持更長密鑰的包。這個包叫做 Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files 6
看一下你的 JRE 環境,將 JRE 環境中 lib\lib\security 中的同名包替換掉。
2. Base64 問題
// 編碼
String asB64 = new Base64().encodeToString("some string".getBytes("utf-8"));
System.out.println(asB64); // 輸出為: c29tZSBzdHJpbmc=
解碼
// 解碼
byte[] asBytes = new Base64().getDecoder().decode("c29tZSBzdHJpbmc=");
System.out.println(new String(asBytes, "utf-8")); // 輸出為: some string
如果你已經使用 Java 8,那麼就不需要再選用第三方的實現了,在 java.util 包中已經包含了 Base64 的處理。
編碼的方式
// 編碼
String asB64 = Base64.getEncoder().encodeToString("some string".getBytes("utf-8"));
System.out.println(asB64); // 輸出為: c29tZSBzdHJpbmc=
解碼處理
// 解碼
byte[] asBytes = Base64.getDecoder().decode("c29tZSBzdHJpbmc=");
System.out.println(new String(asBytes, "utf-8")); // 輸出為: some string
3. 關於 PKCS5 和 PKCS7 填充問題
PKCS #7 填充字元串由一個位元組序列組成,每個位元組填充該填充位元組序列的長度。
假定塊長度為 8,數據長度為 9,
數據: FF FF FF FF FF FF FF FF FF
PKCS7 填充: FF FF FF FF FF FF FF FF FF 07 07 07 07 07 07 07
簡單地說, PKCS5, PKCS7和SSL3, 以及CMS(Cryptographic Message Syntax)
有如下相同的特點:
1)填充的位元組都是一個相同的位元組
2)該位元組的值,就是要填充的位元組的個數
如果要填充8個位元組,那麼填充的位元組的值就是0×8;
要填充7個位元組,那麼填入的值就是0×7;
…
如果只填充1個位元組,那麼填入的值就是0×1;
這種填充方法也叫PKCS5, 恰好8個位元組時還要補8個位元組的0×08
正是這種即使恰好是8個位元組也需要再補充位元組的規定,可以讓解密的數據很確定無誤的移除多餘的位元組。
比如, Java中
Cipher.getInstance(「AES/CBC/PKCS5Padding」)
這個加密模式
跟C#中的
RijndaelManaged cipher = new RijndaelManaged();
cipher.KeySize = 128;
cipher.BlockSize = 128;
cipher.Mode = CipherMode.CBC;
cipher.Padding = PaddingMode.PKCS7;
的加密模式是一樣的
因為AES並沒有64位的塊, 如果採用PKCS5, 那麼實質上就是採用PKCS7