当前位置:首页 > 开发 > 编程语言 > 加密解密 > 正文

DES加密工具类

发表于: 2013-10-08   作者:songchuanlu   来源:转载   浏览:
摘要: import java.security.Provider; import java.security.Security; import javax.crypto.Cipher; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.SecretKeySpec; /** * DES加密工具类 *
import java.security.Provider;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * DES加密工具类
 * 
 * @author 宋陆
 * @date 2013-10-8
 * @version 1.0
 */
public class DesUtil {

    private static final String KEY = "chuanlu";

    public static String encrypt(String strDataToEncrypt) {
        byte[] key = KEY.getBytes();

        Provider sunJCE = new com.sun.crypto.provider.SunJCE();
        Security.addProvider(sunJCE);

        String strAlgorithm = "DES";
        SecretKeySpec keySpec = null;
        DESKeySpec deskey = null;
        String strResult = "";

        try {
            deskey = new DESKeySpec(key);
            keySpec = new SecretKeySpec(deskey.getKey(), "DES");

            Cipher cipher = Cipher.getInstance(strAlgorithm);

            cipher.init(Cipher.ENCRYPT_MODE, keySpec);

            byte[] utf8 = strDataToEncrypt.getBytes("UTF8");

            byte[] enc = cipher.doFinal(utf8);

            strResult = new sun.misc.BASE64Encoder().encode(enc);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return strResult;
    }

    /**
     * This function decrypt a given string using the DES algorithm.
     * 
     * @param strDataToDecrypt
     *            The String to decrypt
     * @param strKey
     *            The generated key used to decrypt
     * @return The encrypted string
     */
    public static String decrypt(String strDataToDecrypt) {
        byte[] key = KEY.getBytes();
        Provider sunJCE = new com.sun.crypto.provider.SunJCE();
        Security.addProvider(sunJCE);

        String strAlgorithm = "DES";
        SecretKeySpec keySpec = null;
        DESKeySpec deskey = null;
        String strResult = "";

        try {
            deskey = new DESKeySpec(key);
            keySpec = new SecretKeySpec(deskey.getKey(), "DES");

            Cipher cipher = Cipher.getInstance(strAlgorithm);
            cipher.init(Cipher.DECRYPT_MODE, keySpec);

            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(strDataToDecrypt);

            byte[] utf8 = cipher.doFinal(dec);

            return new String(utf8, "UTF8");
        }

        catch (Exception e) {
            e.printStackTrace();
        }

        return strResult;
    }
}

 

DES加密工具类

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号