- 浏览: 28003 次
- 性别:
- 来自: 上海
文章分类
最新评论
加密
代码有详细解释,不多废话。
/**
* 加密
*
* @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代码
/**
* 加密
*
* @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;
}
/**
* 加密
*
* @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;
}
2.2 解密
代码有详细注释,不多废话
注意:解密的时候要传入byte数组
view plain copy to clipboard print ?
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte [] decrypt( byte [] 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" ); // 创建密码器
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代码
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] 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");// 创建密码器
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;
}
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] 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");// 创建密码器
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;
}
2.3 测试代码
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
//解密
byte [] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
Java代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
//解密
byte[] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
//解密
byte[] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
输出结果如下:
加密前:test
解密后:test
2.4 容易出错的地方
但是如果我们将测试代码修改一下,如下:
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult, "utf-8" );
//解密
byte [] decryptResult = decrypt(encryptResultStr.getBytes( "utf-8" ),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Javascript代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult,"utf-8");
//解密
byte[] decryptResult = decrypt(encryptResultStr.getBytes("utf-8"),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult,"utf-8");
//解密
byte[] decryptResult = decrypt(encryptResultStr.getBytes("utf-8"),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
则,系统会报出如下异常:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法:
2.4.1将二进制转换成16进制
view plain copy to clipboard print ?
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr( byte buf[]) {
StringBuffer sb = new StringBuffer();
for ( int i = 0 ; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF );
if (hex.length() == 1 ) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
Java代码
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
2.4.2 将16进制转换为二进制
view plain copy to clipboard print ?
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte [] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1 )
return null ;
byte [] result = new byte [hexStr.length()/ 2 ];
for ( int i = 0 ;i< hexStr.length()/ 2 ; i++) {
int high = Integer.parseInt(hexStr.substring(i* 2 , i* 2 + 1 ), 16 );
int low = Integer.parseInt(hexStr.substring(i* 2 + 1 , i* 2 + 2 ), 16 );
result[i] = (byte ) (high * 16 + low);
}
return result;
}
Java代码
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
然后,我们再修订以上测试代码,如下:
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte [] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte [] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
Java代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
测试结果如下:
加密前:test
加密后:73C58BAFE578C59366D8C995CD0B9D6D
解密后:test
2.5 另外一种加密方式
还有一种加密方式,大家可以参考如下:
view plain copy to clipboard print ?
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte [] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES" );
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding" );
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代码
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
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;
}
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
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;
}
这种加密方式有两种限制
密钥必须是16位的
待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常:
javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
要解决如上异常,可以通过补全传入加密内容等方式进行避免。
代码有详细解释,不多废话。
/**
* 加密
*
* @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代码
/**
* 加密
*
* @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;
}
/**
* 加密
*
* @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;
}
2.2 解密
代码有详细注释,不多废话
注意:解密的时候要传入byte数组
view plain copy to clipboard print ?
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte [] decrypt( byte [] 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" ); // 创建密码器
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代码
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] 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");// 创建密码器
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;
}
/**解密
* @param content 待解密内容
* @param password 解密密钥
* @return
*/
public static byte[] decrypt(byte[] 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");// 创建密码器
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;
}
2.3 测试代码
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
//解密
byte [] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
Java代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
//解密
byte[] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
//解密
byte[] decryptResult = decrypt(encryptResult,password);
System.out.println("解密后:" + new String(decryptResult));
输出结果如下:
加密前:test
解密后:test
2.4 容易出错的地方
但是如果我们将测试代码修改一下,如下:
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult, "utf-8" );
//解密
byte [] decryptResult = decrypt(encryptResultStr.getBytes( "utf-8" ),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Javascript代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult,"utf-8");
//解密
byte[] decryptResult = decrypt(encryptResultStr.getBytes("utf-8"),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
try {
String encryptResultStr = new String(encryptResult,"utf-8");
//解密
byte[] decryptResult = decrypt(encryptResultStr.getBytes("utf-8"),password);
System.out.println("解密后:" + new String(decryptResult));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
则,系统会报出如下异常:
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
这主要是因为加密后的byte数组是不能强制转换成字符串的,换言之:字符串和byte数组在这种情况下不是互逆的;要避免这种情况,我们需要做一些修订,可以考虑将二进制数据转换成十六进制表示,主要有如下两个方法:
2.4.1将二进制转换成16进制
view plain copy to clipboard print ?
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr( byte buf[]) {
StringBuffer sb = new StringBuffer();
for ( int i = 0 ; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF );
if (hex.length() == 1 ) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
Java代码
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
/**将二进制转换成16进制
* @param buf
* @return
*/
public static String parseByte2HexStr(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
2.4.2 将16进制转换为二进制
view plain copy to clipboard print ?
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte [] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1 )
return null ;
byte [] result = new byte [hexStr.length()/ 2 ];
for ( int i = 0 ;i< hexStr.length()/ 2 ; i++) {
int high = Integer.parseInt(hexStr.substring(i* 2 , i* 2 + 1 ), 16 );
int low = Integer.parseInt(hexStr.substring(i* 2 + 1 , i* 2 + 2 ), 16 );
result[i] = (byte ) (high * 16 + low);
}
return result;
}
Java代码
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**将16进制转换为二进制
* @param hexStr
* @return
*/
public static byte[] parseHexStr2Byte(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length()/2];
for (int i = 0;i< hexStr.length()/2; i++) {
int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
然后,我们再修订以上测试代码,如下:
view plain copy to clipboard print ?
String content = "test" ;
String password = "12345678" ;
//加密
System.out.println("加密前:" + content);
byte [] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte [] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte [] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
Java代码
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
String content = "test";
String password = "12345678";
//加密
System.out.println("加密前:" + content);
byte[] encryptResult = encrypt(content, password);
String encryptResultStr = parseByte2HexStr(encryptResult);
System.out.println("加密后:" + encryptResultStr);
//解密
byte[] decryptFrom = parseHexStr2Byte(encryptResultStr);
byte[] decryptResult = decrypt(decryptFrom,password);
System.out.println("解密后:" + new String(decryptResult));
测试结果如下:
加密前:test
加密后:73C58BAFE578C59366D8C995CD0B9D6D
解密后:test
2.5 另外一种加密方式
还有一种加密方式,大家可以参考如下:
view plain copy to clipboard print ?
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte [] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES" );
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding" );
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代码
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
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;
}
/**
* 加密
*
* @param content 需要加密的内容
* @param password 加密密码
* @return
*/
public static byte[] encrypt2(String content, String password) {
try {
SecretKeySpec key = new SecretKeySpec(password.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
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;
}
这种加密方式有两种限制
密钥必须是16位的
待加密内容的长度必须是16的倍数,如果不是16的倍数,就会出如下异常:
javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
at com.sun.crypto.provider.SunJCE_f.a(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
要解决如上异常,可以通过补全传入加密内容等方式进行避免。
相关推荐
总的来说,理解并正确使用Java实现AES加密和解密,需要注意秘钥的生成、工作模式的选择、填充方式以及字符编码的一致性,这样才能确保数据的安全传输和正确解密。通过实际操作和实践,你可以更深入地掌握这些知识点...
java实现aes加解密
Java实现AES加密算法Java实现AES加密算法
JAVA 实现 AES 加密算法代码 JAVA 实现 AES 加密算法代码是指使用 JAVA 语言来实现高级加密标准(Advanced Encryption Standard,AES)的加密算法。AES 已经变成目前对称加密中最流行算法之一,能够使用 128、192 ...
在Java中实现AES(Advanced Encryption Standard)...总之,Java中的AES加密和解密涉及到密钥生成、密码器的使用以及数据的转换。在实现过程中,还需要考虑安全性、性能和兼容性等问题,确保加密算法的有效性和安全性。
这个RAR文件"JAVA实现AES加密算法"很可能是包含了一个示例项目,展示如何在JAVA中具体实现AES加密算法,对于初学者来说,是一个很好的学习资源。通过阅读和理解代码,你可以更深入地了解AES的工作原理,以及如何在...
AES高级加密标准,在密码学中又称Rijndael加密法,是美国联邦政府采用的一种...本软件是用java语言开发,实现了AES算法对文件的加密和解密,并在界面上加了进度条,来提示用户加密解密的进度。如果不足之处,欢迎留言。
在提供的两个文件`AES加密1.java`和`AES加密2.java`中,可能包含了上述两种方式的实现。它们可能涵盖了密钥生成、初始化向量(IV)的使用、不同加密模式的选择以及如何处理加密过程中可能遇到的异常。通过阅读和理解...
本篇文章将深入探讨如何在Java中实现AES加密解密,并介绍相关的关键知识点。 首先,我们需要理解AES加密的基本原理。AES是一种块密码,它以固定大小的数据块(128位)为单位进行操作。加密和解密过程都基于一系列...
采用固定AES密钥加密,AES使用PKCS5规则进行补位,加密模式使用AES-ECB
`java_aes加密_demo`表示这是一个Java AES加密的示例项目,而`js_aes加密算法`表明还有JavaScript版本的AES加密实现。 这个压缩包文件可能包含了Java实现AES加密和解密的代码示例,适合初学者了解和学习AES加密的...
Java实现AES加密算法的简单示例主要涉及到的是高级加密标准(AES)在Java编程语言中的应用。AES是一种广泛使用的块加密标准,它基于密码值的置换和替代操作,用于保护数据的安全。AES已被美国联邦政府采纳,取代了...
**AES加密算法** AES,全称为“Advanced Encryption Standard”,即高级加密标准,是目前广泛使用的...通过`secret`这个文件名,可能包含了具体实现AES加密的Java代码示例,你可以查阅这个文件以获得更详细的信息。
本篇将详细介绍Java实现AES加密解密的原理与实践。 AES是一种块密码,它以128位(16字节)的数据块作为处理单位,通过多次替换、置换等操作来实现加密。AES有三个关键参数:密钥长度(128、192或256位)、轮数(10...
在提供的"demo"文件中,可能包含了具体的项目结构、配置文件、源代码等,这些内容可以帮助进一步理解和实现这个Java前后端通讯AES加密及解密的案例。实际操作时,需要根据文件内容进行相应的集成和调试。
aes加密
java实现aes加密,采用cbc模式,PKCS5Padding填充,key ALLINPAYRISKERR0,偏移量IV 0000000000000000,hex输出 。
AES(Advanced Encryption Standard...总结,AES加密在前端JavaScript和后端Java中的实现涉及选择合适的库,管理密钥和IV,以及使用相应的加密和解密方法。确保在实际应用中遵循安全标准,以保护数据的机密性和完整性。
本资源是一个关于Java实现AES加密解密的示例,适用于开发人员在进行数据安全处理时参考。 AES的核心是基于块加密,它将原始数据分成128位的块进行操作。该算法包含多个轮的替换、置换和混淆操作,使得加密后的数据...