DES 加密解密类

//tomcat6,jdk 1.5测试通过

//CryptoUtils.java类源码

package Inc;

import java.io.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.*;
import java.security.spec.*;
import com.sun.crypto.provider.SunJCE;
import java.io.Serializable;

public class CryptoUtils {   
  
    private static final String KEY = "13123131316768686868657464646446242423423";   
       
    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;   
    }   
}  
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值