java数据加密怎么做

1279
2021/1/11 17:48:34
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

java数据加密怎么做

在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==

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java深拷贝实现的方法是什么