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