DES加密 version2

来源:互联网 发布:四种软件体系结构 编辑:程序博客网 时间:2024/06/05 05:22
import java.security.Key;import java.util.Date;import javax.crypto.Cipher;public class DESEncrypt {private static Key getKey(byte[] arrBTmp) throws Exception {// 创建一个空的8位字节数组(默认值为0)byte[] arrB = new byte[8];// 将原始字节数组转换为8位for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) {arrB[i] = arrBTmp[i];}// 生成密钥Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES");return key;}public static byte[] encrypt(byte[] contentBytes, byte[] keyBytes) {byte[] hasEncrypt = null;try {Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.ENCRYPT_MODE, getKey(keyBytes));hasEncrypt = cipher.doFinal(contentBytes);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return hasEncrypt;}public static byte[] decrypt(byte[] contentBytes, byte[] keyBytes) {byte[] hasDecrypt = null;try {Cipher cipher = Cipher.getInstance("DES");cipher.init(Cipher.DECRYPT_MODE, getKey(keyBytes));hasDecrypt = cipher.doFinal(contentBytes);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return hasDecrypt;}}


Test:

String content = "DES加密";String uuid = UUID.randomUUID().toString();String a = Base64.encodeBytes(DESEncrypt.encrypt(content.getBytes("UTF-8"),uuid.getBytes("UTF-8")));System.out.println("DES Encrypt..." + a);//先Base64解码,再DES解密String b = new String(DESEncrypt.decrypt(Base64.decode(a), uuid.getBytes("UTF-8")),"UTF-8");System.out.println("DES decrypt..." + b);

Console

DES Encrypt...hqPYNk/ewpBdzaxNm4tqDQ==DES decrypt...DES加密


原创粉丝点击