欢迎光临
我们一直在努力

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

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。