DES算法

作者: piozeer | 来源:发表于2017-03-04 13:56 被阅读0次

    数据加密标准(英语:Data Encryption Standard,缩写为 DES)是一种对称密钥加密块密码算法,1976年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),随后在国际上广泛流传开来。它基于使用56位密钥的对称算法。这个算法因为包含一些机密设计元素,相对短的密钥长度以及怀疑内含美国国家安全局(NSA)的后门而在开始时有争议,DES因此受到了强烈的学院派式的审查,并以此推动了现代的块密码及其密码分析的发展。                                                                                                                                                ---维基百科 

    一、DES简介

    1、DES:数据加密标准,是对称加密算法领域中的典型算法

    2、特点:秘钥偏短(56位),生命周期短

    3、JDK内部提供了算法的实现

    二、相关代码

    1、生成密钥

    public static byte[] getKey() throws Exception

    {

    KeyGenerator keyGen = KeyGenerator.getInstance("DES");

    keyGen.init(56);

    SecretKey secretKey = keyGen.generateKey();

    return secretKey.getEncoded();

    }

    2、DES加密

    /**

    * DES加密

    * @param data 要加密的原始数据

    * @param key  密钥

    * @return 加密后的数据

    * @throws Exception

    */

    public static byte[] encrypt(byte[] data, byte[] key) throws Exception

    {

    SecretKey secretKey = new SecretKeySpec(key, "DES");

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    return cipher.doFinal(data);

    }

    3、DES解密

    /**

    * DES解密

    * @param data 要解密的数据

    * @param key  密钥

    * @return 解密后的数据

    * @throws Exception

    */

    public static byte[] decrypt(byte[] data, byte[] key) throws Exception

    {

    SecretKey secretKey = new SecretKeySpec(key, "DES");

    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    return cipher.doFinal(data);

    }

    4、字节转十六进制

    /**

    * 字节转十六进制

    *

    * @param resultBytes

    *            输入源

    * @return 十六进制字符串

    */

    public static String fromBytesToHex(byte[] resultBytes) {

    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < resultBytes.length; i++) {

    if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) {

    builder.append("0").append(Integer.toHexString(0xFF & resultBytes[i]));

    } else {

    builder.append(Integer.toHexString(0xFF & resultBytes[i]));

    }

    }

    return builder.toString();

    }

    相关文章

      网友评论

          本文标题:DES算法

          本文链接:https://www.haomeiwen.com/subject/fpbdgttx.html