Java常见加密解密方式
本文主要介绍一种对称加密和一种单向加密
AES => 对称加密
MD5 => 非对称加密
AES
* 对称加密
* AES(AdvancedEncryption Standard,高级数据加密标准)
* 算法支持128位、192位和256位的秘钥长度,加密速度比DES和DESede都快,至今还没有被破解的报道。
* 经过验证,目前采用的AES算法能够有效抵御已知的针对DES算法的所有攻击方法,如部分差分攻击、相关秘钥攻击等。
* AES算法因秘钥建立时间短、灵敏性好、内存需求低等优点,在各个领域得到广泛的研究与应用。
* JDK8支持128位、192位和256位长度的AES秘钥,
*
* 下面举个JDK8实现AES的128位加密的例子
* 其中customKey 是密钥,128位即16字节, word 就是需要加密的字符串
加密
java
public static String encrypt(String customKey, String word) throws Exception {
String algorithm = "AES";
String transformation = "AES";
SecretKey secretKey = new SecretKeySpec(customKey.getBytes(StandardCharsets.UTF_8), "AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), algorithm);
// System.out.println("AES秘钥:" + Base64.getEncoder().encodeToString(secretKey.getEncoded()));
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypt = cipher.doFinal(word.getBytes());
// System.out.println("AES加密结果:" + Base64.getEncoder().encodeToString(encrypt));
return Base64.getEncoder().encodeToString(encrypt);
}
解密
java
public static String decrypt(String customKey ,String word) throws Exception {
String algorithm = "AES";
String transformation = "AES";
SecretKey secretKey = new SecretKeySpec(customKey.getBytes(StandardCharsets.UTF_8), "AES");
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), algorithm);
// System.out.println("AES秘钥:" + Base64.getEncoder().encodeToString(secretKey.getEncoded()));
Cipher cipher = Cipher.getInstance(transformation);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypt = cipher.doFinal(Base64.getDecoder().decode(word));
// System.out.println("AES解密结果:" + new String(decrypt));
return new String(decrypt);
}
演示
java
public static void main(String[] args) throws Exception {
String word = "admin123";
String key = "abcdefgh01234567";
String encrypt = encrypt(key, word);
String decrypt = decrypt(key, encrypt);
System.out.println(encrypt);
System.out.println(decrypt);
}
MD5
加密
java
public static String getMD5(String password){
String secretKey = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
String result = buf.toString();
String md5up32 = result;
String md5down32 = result.toUpperCase();
String md5up16 = buf.toString().substring(8, 24);
String md5down16 = buf.toString().substring(8, 24).toUpperCase();
secretKey = md5up32;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return secretKey;
}