1. 程式人生 > >Java Des加密解密工具類

Java Des加密解密工具類

原文連結:

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("需要解密的字串");