javaaes128
❶ 如何把以下 java AES-128-CBC 加密方法改為 php 的實現
$key = hash('md5', $key, true);
$iv = '';
$size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$input = Security::pkcs5_pad($input, $size);
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $input, MCRYPT_MODE_CBC, $iv);
// output wd/OTHoIXwgHGDHcj8OTgg==
echo base64_encode($encrypted);
❷ 怎麼把php AES128的代碼轉成java
publicclassSimpleCrypto{
publicstaticStringencrypt(Stringseed,Stringcleartext)throwsException{
byte[]rawKey=getRawKey(seed.getBytes());
byte[]result=encrypt(rawKey,cleartext.getBytes());
returntoHex(result);
}
publicstaticStringdecrypt(Stringseed,Stringencrypted)throwsException{
byte[]rawKey=getRawKey(seed.getBytes());
byte[]enc=toByte(encrypted);
byte[]result=decrypt(rawKey,enc);
returnnewString(result);
}
privatestaticbyte[]getRawKey(byte[]seed)throwsException{
KeyGeneratorkgen=KeyGenerator.getInstance("AES");
SecureRandomsr=SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(128,sr);//
SecretKeyskey=kgen.generateKey();
byte[]raw=skey.getEncoded();
returnraw;
}
privatestaticbyte[]encrypt(byte[]raw,byte[]clear)throwsException{
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE,skeySpec);
byte[]encrypted=cipher.doFinal(clear);
returnencrypted;
}
privatestaticbyte[]decrypt(byte[]raw,byte[]encrypted)throwsException{
SecretKeySpecskeySpec=newSecretKeySpec(raw,"AES");
Ciphercipher=Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE,skeySpec);
byte[]decrypted=cipher.doFinal(encrypted);
returndecrypted;
}
publicstaticStringtoHex(Stringtxt){
returntoHex(txt.getBytes());
}
publicstaticStringfromHex(Stringhex){
returnnewString(toByte(hex));
}
publicstaticbyte[]toByte(StringhexString){
intlen=hexString.length()/2;
byte[]result=newbyte[len];
for(inti=0;i<len;i++)
result[i]=Integer.valueOf(hexString.substring(2*i,2*i+2),16).byteValue();
returnresult;
}
publicstaticStringtoHex(byte[]buf){
if(buf==null)
return"";
StringBufferresult=newStringBuffer(2*buf.length);
for(inti=0;i<buf.length;i++){
appendHex(result,buf[i]);
}
returnresult.toString();
}
privatefinalstaticStringHEX="0123456789ABCDEF";
privatestaticvoidappendHex(StringBuffersb,byteb){
sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
}
}
❸ 請教個關於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密碼演算法
1. AES加密字元串
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者
kgen.init(128, new SecureRandom(password.getBytes()));// 利用用戶密碼作為隨機數初始化出
// 128位的key生產者
//加密沒關系,SecureRandom是生成安全隨機數序列,password.getBytes()是種子,只要種子相同,序列就一樣,所以解密只要有password就行
SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰
byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰,如果此密鑰不支持編碼,則返回
// null。
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化為加密模式的密碼器
byte[] result = cipher.doFinal(byteContent);// 加密
return result;
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
2. AES解密
public static byte[] decrypt(byte[] content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 創建AES的Key生產者
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();// 根據用戶密碼,生成一個密鑰
byte[] enCodeFormat = secretKey.getEncoded();// 返回基本編碼格式的密鑰
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");// 轉換為AES專用密鑰
Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
cipher.init(Cipher.DECRYPT_MODE, key);// 初始化為解密模式的密碼器
byte[] result = cipher.doFinal(content);
return result; // 明文
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
❺ 求一個java演算法,用128位密鑰的AES加密128位明文,得出的密文還是128位...很著急,非常感謝各位大神,求救!
/**
* 加密
*
* @param content 需要加密的內容
* @param password 加密密碼
* @return
*/
public static byte[] encrypt(String content, String password) {
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(password.getBytes()));
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES");// 創建密碼器
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
byte[] result = cipher.doFinal(byteContent);
return result; // 加密
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return null;
}
❻ JAVA實現AES加密疑問么
和加密沒關系,SecureRandom是生成安全隨機數序列,password.getBytes()是種子,只要種子相同,序列就一樣,所以解密只要有password就行,可以復原這個序列
❼ 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
❽ 用JAVA實現了AES128加密,求用C語言解密的代碼,謝謝各位大神了!
http://blog.chen777.com/2015/10/13/Java%E4%B8%8EC-AES%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86/#more
不知道適合你用嗎,我以前是用這種方式實現的。
❾ java實現aes加密或者解密,不用工具包的怎麼做
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;
}
}