文章摘要:java数据加密怎么做 Java数据加密
在java中对数据进行加密的方法 1.使用MD5编码加密 public static String md5En […]
在java中对数据进行加密的方法
1.使用MD5编码加密
public static String md5Encode(String text) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] digest = md.digest(text.getBytes());
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
String hexString = Integer.toHexString(b & 0xFF);
if (hexString.length() == 1) {
hexString = "0" + hexString;
}
sb.append(hexString);
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
logger.error(e);
}
return null;
}
输入:123456abcdef,输出:6f3b8ded65bd7a4db11625ac84e579bb
2.使用DES加密
private final static byte[] KEY_BYTES = "Vp6fhlFXKpGW8k6QPRg7Q6Jb7HyAhRi6MIhJ2YtGD3Zl26eTthJTj5PnIjXH5EI4".getBytes();
public static byte[] encryptDES(byte[] content, byte[] key) {
try {
SecureRandom random = new SecureRandom();
DESKeySpec desKey = new DESKeySpec(key);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(desKey);
// DES 是加密方式, EBC 是工作模式, PKCS5Padding 是填充模式
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
return cipher.doFinal(content);
} catch (Exception e) {
logger.error(e);
}
return null;
}
输入:123456abcdef,输出:j1kR1+ZraO2Tg78dHueoTg==