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);
   }

}

測試如下:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章