欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Des加密解密工具类

程序员文章站 2022-03-12 19:37:02
...

原文链接:

1、http://www.java2s.com/Code/Java/Security/EncryptingaStringwithDES.htm

2、http://www.avajava.com/tutorials/lessons/how-do-i-encrypt-and-decrypt-files-using-des.html

工具类:

package com.parcool.ssm.utils;

import com.parcool.ssm.common.Constants;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;

/**
 * Created by tanyi on 2017/6/12.
 */
public class DesEncryptDecrypt {
    private static DesEncryptDecrypt ourInstance = new DesEncryptDecrypt();

    public static DesEncryptDecrypt getInstance() {
        return ourInstance;
    }
    private Cipher ecipher,dcipher;


    private DesEncryptDecrypt(){
        DESKeySpec dks;
        try {
            //Constants.EncryptDecryptKEY是我一个常量类中的字符串而已,它就是加密解密的**。请自行替换。
            dks = new DESKeySpec(Constants.EncryptDecryptKEY.getBytes());
            SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
            SecretKey desKey = skf.generateSecret(dks);
            ecipher = Cipher.getInstance("DES");
            dcipher = Cipher.getInstance("DES");
            ecipher.init(Cipher.ENCRYPT_MODE, desKey);
            dcipher.init(Cipher.DECRYPT_MODE, desKey);
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        }

    }

    public String encrypt(String str) throws Exception {
        // Encode the string into bytes using utf-8
        byte[] utf8 = str.getBytes("UTF8");
        // Encrypt
        byte[] enc = ecipher.doFinal(utf8);
        // Encode bytes to base64 to get a string
        return new sun.misc.BASE64Encoder().encode(enc);
    }

    public String decrypt(String str) throws Exception {
        // Decode base64 to get bytes
        byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
        byte[] utf8 = dcipher.doFinal(dec);
        // Decode using utf-8
        return new String(utf8, "UTF8");
    }
}

使用方法:

加密:

String encryptedStr = DesEncryptDecrypt.getInstance().encrypt("需要加密的字符串");
解密:

String decryptedStr = DesEncryptDecrypt.getInstance().decrypt("需要解密的字符串");


相关标签: des DesEncrypt