DES加密简单封装成工具类方式二

DES是一种对称的加密方式,即需要相同的密钥进行加密解密。为了方便日后使用,此处将DES的加解密方法进行了封装,参数和返回值统一String数据类型。代码较为简单,不多解释,如有不对的地方,望多多指教。

package encrypt;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import org.apache.commons.codec.binary.Base64;
import java.security.Key;
import java.security.SecureRandom;

public class DESUtils {

    private static Key key;
    private static String KEY_STR = "aaaaaaaaaa"; //密钥
    private static String CHARSET_NAME = "UTF-8"; //编码格式
    private static String ALGORITHM = "DES";

    //初始化
    static {
        try {
            KeyGenerator generator = KeyGenerator.getInstance(ALGORITHM);
            SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
            secureRandom.setSeed(KEY_STR.getBytes());
            generator.init(secureRandom);
            key = generator.generateKey();
            generator = null;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //输入原文加密,返回密文字符串
    public static String getEncryptString(String str) {
        Base64 base64encoder = new Base64();
        try {
            byte[] bytes = str.getBytes(CHARSET_NAME);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return base64encoder.encodeToString(doFinal);
        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e);
        }
    }

    //输入密文,解密的原文 字符串
    public static String getDecryptString(String str) {
        Base64 base64decoder = new Base64();
        try {
            byte[] bytes = base64decoder.decodeBase64(str);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] doFinal = cipher.doFinal(bytes);
            return new String(doFinal, CHARSET_NAME);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    public static void main(String[] args) {
        String password = "roodfdfddfdadfad大t";
        System.out.println("===明文===:"+password);
        String password_Encrypt = getEncryptString(password);
        System.out.print("===密文===:"+password_Encrypt);
        String password_decrypt = getDecryptString(password_Encrypt);
        System.out.println("===原文===:"+password_decrypt);
   }

}

测试如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值