MD5加密、DES加解密、RSA加解密

1.MD5加密:

java.security.MessageDigest

jdk1.6描述:

此 MessageDigest 类为应用程序提供信息摘要算法的功能,如 MD5 或 SHA 算法。信息摘要是安全的单向哈希函数,它接收任意大小的数据,并输出固定长度的哈希值。

MessageDigest 对象开始被初始化。该对象通过使用 update 方法处理数据。任何时候都可以调用 reset 方法重置摘要。一旦所有需要更新的数据都已经被更新了,应该调用 digest 方法之一完成哈希计算。 

public static String MD5(String str) {
if (str == null)
return null;
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(str.getBytes("UTF-8"));
byte[] digest = md5.digest();
StringBuffer hexString = new StringBuffer();
String strTemp;
for (int i = 0; i < digest.length; i++) {
strTemp = Integer.toHexString((digest[i] & 0x000000FF) | 0xFFFFFF00).substring(6);
hexString.append(strTemp);
}
return hexString.toString();
} catch (Exception e) {
e.printStackTrace();
}
return str;
}


2.DES加解密

/**
* DES加密
*/
public static String desEncrypt(String source, String desKey) throws Exception {
try {
// 从原始密匙数据创建DESKeySpec对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(desKey.getBytes()));
// Cipher对象实际完成加密操作
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, securekey);
// 现在,获取数据并加密
byte[] destBytes = cipher.doFinal(source.getBytes());
StringBuilder hexRetSB = new StringBuilder();
for (byte b : destBytes) {
String hexString = Integer.toHexString(0x00ff & b);
hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
}
return hexRetSB.toString();
} catch (Exception e) {
throw new Exception("DES加密发生错误", e);
}
}


/**
* DES解密
*/
public static String desDecrypt(String source, String desKey) throws Exception {
// 解密数据
byte[] sourceBytes = new byte[source.length() / 2];
for (int i = 0; i < sourceBytes.length; i++) {
sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
}
try {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey securekey = keyFactory.generateSecret(new DESKeySpec(desKey.getBytes()));
Cipher cipher = Cipher.getInstance("DES");
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, securekey);
// 现在,获取数据并解密
byte[] destBytes = cipher.doFinal(sourceBytes);
return new String(destBytes);
} catch (Exception e) {
throw new Exception("DES解密发生错误", e);
}
}


猜你喜欢

转载自blog.csdn.net/hansplay/article/details/72531654