常用对称加密算法
基于“对称密钥”的加密算法主要有DES、3DES(TripleDES)、AES、RC2、RC4、RC5和Blowfish等。本文只介绍最常用的对称加密算法DES、3DES(TripleDES)和AES。
Java中的MD5实现
package amigo.endecrypt;
import java.security.MessageDigest;
/**
* 采用MD5加密
* @author Xingxing,Xie
* @datetime 2014-5-31
*/
public class MD5Util {
/***
* MD5加密 生成32位md5码
* @param 待加密字符串
* @return 返回32位md5码
*/
public static String md5Encode(String inStr) throws Exception {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 测试主函数
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception {
String str = new String("amigoxiexiexingxing");
System.out.println("原始:" + str);
System.out.println("MD5后:" + md5Encode(str));
}
}
测试结果:
原始:amigoxiexiexingxing
MD5后:e9ac094091b96b84cca48098bc21b1d6
Java中的SHA实现
package amigo.endecrypt;
import java.security.MessageDigest;
/**
* 采用SHAA加密
* @author Xingxing,Xie
* @datetime 2014-6-1
*/
public class SHAUtil {
/***
* SHA加密 生成40位SHA码
* @param 待加密字符串
* @return 返回40位SHA码
*/
public static String shaEncode(String inStr) throws Exception {
MessageDigest sha = null;
try {
sha = MessageDigest.getInstance("SHA");
} catch (Exception e) {
System.out.println(e.toString());
e.printStackTrace();
return "";
}
byte[] byteArray = inStr.getBytes("UTF-8");
byte[] md5Bytes = sha.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16) {
hexValue.append("0");
}
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 测试主函数
* @param args
* @throws Exception
*/
public static void main(String args[]) throws Exception {
String str = new String("amigoxiexiexingxing");
System.out.println("原始:" + str);
System.out.println("SHA后:" + shaEncode(str));
}
}
测试结果如下所示:
原始:amigoxiexiexingxing
SHA后:04f79f496dd6bdab3439511606528a4ad9caac5e
Java中的DES实现
DES加密算法(ECB、无填充)的Java实现如下
package amigo.endecrypt;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.apache.commons.codec.binary.Base64;
public class DESUtil {
//算法名称
public static final String KEY_ALGORITHM = "DES";
//算法名称/加密模式/填充方式
//DES共有四种工作模式-->>ECB:电子密码本模式、CBC:加密分组链接模式、CFB:加密反馈模式、OFB:输出反馈模式
public static final String CIPHER_ALGORITHM = "DES/ECB/NoPadding";
/**
*
* 生成密钥key对象
* @param KeyStr 密钥字符串
* @return 密钥对象
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws Exception
*/
private static SecretKey keyGenerator(String keyStr) throws Exception {
byte input[] = HexString2Bytes(keyStr);
DESKeySpec desKey = new DESKeySpec(input);
//创建一个密匙工厂,然后用它把DESKeySpec转换成
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(desKey);
return securekey;
}
private static int parse(char c) {
if (c >= 'a') return (c - 'a' + 10) & 0x0f;
if (c >= 'A') return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
// 从十六进制字符串到字节数组转换
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}
/**
* 加密数据
* @param data 待加密数据
* @param key 密钥
* @return 加密后的数据
*/
public static String encrypt(String data, String key) throws Exception {
Key deskey = keyGenerator(key);
// 实例化Cipher对象,它用于完成实际的加密操作
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
SecureRandom random = new SecureRandom();
// 初始化Cipher对象,设置为加密模式
cipher.init(Cipher.ENCRYPT_MODE, deskey, random);
byte[] results = cipher.doFinal(data.getBytes());
// 该部分是为了与加解密在线测试网站(http://tripledes.online-domain-tools.com/)的十六进制结果进行核对
for (int i = 0; i < results.length; i++) {
System.out.print(results[i] + " ");
}
System.out.println();
// 执行加密操作。加密后的结果通常都会用Base64编码进行传输
return Base64.encodeBase64String(results);
}
/**
* 解密数据
* @param data 待解密数据
* @param key 密钥
* @return 解密后的数据
*/
public static String decrypt(String data, String key) throws Exception {
Key deskey = keyGenerator(key);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
//初始化Cipher对象,设置为解密模式
cipher.init(Cipher.DECRYPT_MODE, deskey);
// 执行解密操作
return new String(cipher.doFinal(Base64.decodeBase64(data)));
}
public static void main(String[] args) throws Exception {
String source = "amigoxie";
System.out.println("原文: " + source);
String key = "A1B2C3D4E5F60708";
String encryptData = encrypt(source, key);
System.out.println("加密后: " + encryptData);
String decryptData = decrypt(encryptData, key);
System.out.println("解密后: " + decryptData);
}
}
测试结果:
原文: amigoxie
97 -15 32 -117 -57 -42 -90 75
加密后: YfEgi8fWpks=
解密后: amigoxie
Java中的3DES实现
3DES的在Java的实现与DES类似,如下代码为3DES加密算法、CBC模式、NoPadding填充方式的加密解密结果,参考代码如下所示:
package amigo.endecrypt;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public class ThreeDESUtil {
// 算法名称
public static final String KEY_ALGORITHM = "desede";
// 算法名称/加密模式/填充方式
public static final String CIPHER_ALGORITHM = "desede/CBC/NoPadding";
/**
* CBC加密
* @param key 密钥
* @param keyiv IV
* @param data 明文
* @return Base64编码的密文
* @throws Exception
*/
public static byte[] des3EncodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Key deskey = keyGenerator(new String(key));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.ENCRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
for (int k = 0; k < bOut.length; k++) {
System.out.print(bOut[k] + " ");
}
System.out.println("");
return bOut;
}
/**
*
* 生成密钥key对象
* @param KeyStr 密钥字符串
* @return 密钥对象
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
* @throws Exception
*/
private static Key keyGenerator(String keyStr) throws Exception {
byte input[] = HexString2Bytes(keyStr);
DESedeKeySpec KeySpec = new DESedeKeySpec(input);
SecretKeyFactory KeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
return ((Key) (KeyFactory.generateSecret(((java.security.spec.KeySpec) (KeySpec)))));
}
private static int parse(char c) {
if (c >= 'a') return (c - 'a' + 10) & 0x0f;
if (c >= 'A') return (c - 'A' + 10) & 0x0f;
return (c - '0') & 0x0f;
}
// 从十六进制字符串到字节数组转换
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++) {
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b[i] = (byte) ((parse(c0) << 4) | parse(c1));
}
return b;
}
/**
* CBC解密
* @param key 密钥
* @param keyiv IV
* @param data Base64编码的密文
* @return 明文
* @throws Exception
*/
public static byte[] des3DecodeCBC(byte[] key, byte[] keyiv, byte[] data) throws Exception {
Key deskey = keyGenerator(new String(key));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(keyiv);
cipher.init(Cipher.DECRYPT_MODE, deskey, ips);
byte[] bOut = cipher.doFinal(data);
return bOut;
}
public static void main(String[] args) throws Exception {
byte[] key = "6C4E60E55552386C759569836DC0F83869836DC0F838C0F7".getBytes();
byte[] keyiv = { 1, 2, 3, 4, 5, 6, 7, 8 };
byte[] data = "amigoxie".getBytes("UTF-8");
System.out.println("data.length=" + data.length);
System.out.println("CBC加密解密");
byte[] str5 = des3EncodeCBC(key, keyiv, data);
System.out.println(new sun.misc.BASE64Encoder().encode(str5));
byte[] str6 = des3DecodeCBC(key, keyiv, str5);
System.out.println(new String(str6, "UTF-8"));
}
}
测试结果如下所示:
data.length=8
CBC加密解密
-32 6 108 42 24 -112 -66 -34
4AZsKhiQvt4=
amigoxie
AES加密
...............
某些方面的实际应用
MD5是常用的加密算法,也经常用于校验信息完整,如文件的完整性。用术语讲,MD5是一种消息摘要算法(Message Digest Algorithm)。另外还有一种常用的消息摘要算法SHA1。如果想了解这些的话,可以去百度百科:MD5、SHA1、消息摘要算法。
Java已经实现了MD5、SHA1算法。利用java.security.MessageDigest类就可以获取字符串和文件的MD5以及SHA1结果。
1.字符串的MD5(下面的代码有详细注释)
public static String stringMD5(String input) {
try {
// 拿到一个MD5转换器(如果想要SHA1参数换成”SHA1”)
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
// 输入的字符串转换成字节数组
byte[] inputByteArray = input.getBytes();
// inputByteArray是输入字符串转换得到的字节数组
messageDigest.update(inputByteArray);
// 转换并返回结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 字符数组转换成字符串返回
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
}
}
//下面这个函数用于将字节数组换成成16进制的字符串
public static String byteArrayToHex(byte[] byteArray) {
// 首先初始化一个字符数组,用来存放每个16进制字符
char[] hexDigits = {'0','1','2','3','4','5','6','7','8','9', 'A','B','C','D','E','F' };
// new一个字符数组,这个就是用来组成结果字符串的(解释一下:一个byte是八位二进制,也就是2位十六进制字符(2的8次方等于16的2次方))
char[] resultCharArray =new char[byteArray.length * 2];
// 遍历字节数组,通过位运算(位运算效率高),转换成字符放到字符数组中去
int index = 0;
for (byte b : byteArray) {
resultCharArray[index++] = hexDigits[b>>> 4 & 0xf];
resultCharArray[index++] = hexDigits[b& 0xf];
}
// 字符数组组合成字符串返回
return new String(resultCharArray);
}
从上面代码可以看出,使用MessageDigest对字符串进行MD5算法的步骤是,先将字符串转换成字节数组,在进行MD5算法,最后返回的也是一个字节数组,要我们自己转成32位的字符串。
2.文件MD5
对文件进行MD5也可以像字符串MD5一样的,首先要把文件转成字节数组,后面和字符串MD5完全一样。
但是如果是一个特别大的文件,一下子把一个文件的数组全部读到内存中,那么估计内存也吃不消。
对于大文件,可以使用DigestInputStream。
public static String fileMD5(String inputFile) throws IOException {
// 缓冲区大小(这个可以抽出一个参数)
int bufferSize = 256 * 1024;
FileInputStream fileInputStream = null;
DigestInputStream digestInputStream = null;
try {
// 拿到一个MD5转换器(同样,这里可以换成SHA1)
MessageDigest messageDigest =MessageDigest.getInstance("MD5");
// 使用DigestInputStream
fileInputStream = new FileInputStream(inputFile);
digestInputStream = new DigestInputStream(fileInputStream,messageDigest);
// read的过程中进行MD5处理,直到读完文件
byte[] buffer =new byte[bufferSize];
while (digestInputStream.read(buffer) > 0);
// 获取最终的MessageDigest
messageDigest= digestInputStream.getMessageDigest();
// 拿到结果,也是字节数组,包含16个元素
byte[] resultByteArray = messageDigest.digest();
// 同样,把字节数组转换成字符串
return byteArrayToHex(resultByteArray);
} catch (NoSuchAlgorithmException e) {
return null;
} finally {
try {
digestInputStream.close();
} catch (Exception e) {
}
try {
fileInputStream.close();
} catch (Exception e) {
}
}
}
上面的方法本人亲测过大小约4G的文件,得出的MD5值和网上下载的一个MD5小工具得到的MD5值一样,说明上面的方式没有什么问题。不过取大文件的MD5很慢,4G的文件跑一下要一分钟(I5处理器 6G内存 64位XP系统 本本)。
附1:我在网上还看到一种给文件MD5的方式
public static String getFileMD5String(File file) throws IOException {
FileInputStream in = new FileInputStream(file);
FileChannel ch = in.getChannel();
MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,
file.length());
messagedigest.update(byteBuffer);
return byteArrayToHex(messagedigest.digest());
}
我也尝试过这样的方式,但是如果文件大于2G,那么这种方式会出现异常。所以不推荐。
附2:测试文件MD5的main方法
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
try {
System.out.println(fileMD5("E:/软件/VS2008ProEdition90DayTrialCHSX1435983.iso"));
} catch (IOException e) {
e.printStackTrace();
}
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) / 1000);
}
SHA-1和MD5的比较
因为二者均由MD4导出,SHA-1和MD5彼此很相似。相应的,他们的强度和其他特性也是相似,但还有以下几点不同:
1)对强行攻击的安全性:最显著和最重要的区别是SHA-1摘要比MD5摘要长32 位。使用强行技术,产生任何一个报文使其摘要等于给定报摘要的难度对MD5是2^128数量级的操作,而对SHA-1则是2^160数量级的操作。这样,SHA-1对强行攻击有更大的强度。
2)对密码分析的安全性:由于MD5的设计,易受密码分析的攻击,SHA-1显得不易受这样的攻击。
3)速度:在相同的硬件上,SHA-1的运行速度比MD5慢。
附录:
《加密解密在线测试网站》:3DES Encryption – Easily encrypt or decrypt strings or files
参考链接:
Java利用MessageDigest提供的MD5算法加密字符串或文件 - 代码ok - 博客园
常用加密算法的Java实现总结(一)——单向加密算法MD5和SHA - 阿蜜果 - BlogJava
常用加密算法的Java实现总结(二)——对称加密算法DES、3DES和AES - 阿蜜果 - BlogJava
Java利用MessageDigest获取字符串或文件MD5详解 - JAVA编程语言程序开发技术文章 - 红黑联盟
Java利用MessageDigest获取字符串或文件MD5详解 - 鼠穴 - OSCHINA - 中文开源技术交流社区