常見的幾種安全加密算法

本文整理了常見的安全算法,包括MD5、SHA、DES、AES、RSA等,並寫了完整的工具類(Java 版),工具類包含測試,大家可以放心使用。

一、數字摘要算法

數字摘要也稱爲消息摘要,它是一個唯一對應一個消息或文本的固定長度的值,它由一個單向Hash函數對消息進行計算而產生。如果消息在傳遞的途中改變了,接收者通過對收到消息採用相同的Hash重新計算,新產生的摘要與原摘要進行比較,就可知道消息是否被篡改了,因此消息摘要能夠驗證消息的完整性。消息摘要採用單向Hash函數將需要計算的內容”摘要”成固定長度的串,這個串亦稱爲數字指紋。這個串有固定的長度,且不同的明文摘要成密文,其結果總是不同的(相對的),而同樣的明文其摘要必定一致。這樣這串摘要便可成爲驗證明文是否是”真身”的”指紋”了。

1. Md5

MD5即Message Digest Algorithm 5(信息摘要算法5),是數字摘要算法一種實現,用於確保信息傳輸完整性和一致性,摘要長度爲128位。 MD5由MD4、 MD3、 MD2改進而來,主要增強算法複雜度和不可逆性,該算法因其普遍、穩定、快速的特點,在產業界得到了極爲廣泛的使用,目前主流的編程語言普遍都已有MD5算法實現。

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Message Digest Algorithm 5(信息摘要算法5)
 */
public class MD5Util {
    /**
     * Constructs the MD5Util object and sets the string whose MD5Util is to be
     * computed.
     * 
     * @param inStr
     *    the <code>String</code> whose MD5Util is to be computed
     */


    public final static String COMMON_KEY="zhongzhuoxin#@!321";
    public MD5Util() {

    }

    public final static String str2MD5(String inStr) {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        try {
            byte[] strTemp = inStr.getBytes("UTF-8");
            MessageDigest mdTemp = MessageDigest.getInstance("MD5");
            mdTemp.update(strTemp);
            byte[] md = mdTemp.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }




    //--MD5Util
    private static final char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    public static String toHexString(byte[] b) { // String to byte
        StringBuilder sb = new StringBuilder(b.length * 2);
        for (int i = 0; i < b.length; i++) {
            sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]);
            sb.append(HEX_DIGITS[b[i] & 0x0f]);
        }
        return sb.toString();
    }

    public static String AndroidMd5(String s) {
        try {
            // Create MD5Util Hash
            MessageDigest digest = MessageDigest
                    .getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            return toHexString(messageDigest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return "";
    }

    public static void main(String[] args) {

        String m = MD5Util.str2MD5("swwwwwwwwwwdkinner");

        System.out.print(m.length() + "    ");
        System.out.println(m);

    }
}

2.SHA

SHA的全稱是Secure Hash Algorithm,即安全散列算法。 1993年,安全散列算法(SHA)由美國國家標準和技術協會(NIST)提出,並作爲聯邦信息處理標準(FIPS PUB 180)公佈, 1995年又發佈了一個修訂版FIPS PUB 180-1,通常稱之爲SHA-1。 SHA-1是基於MD4算法的,現在已成爲公認的最安全的散列算法之一,並被廣泛使用。SHA-1算法生成的摘要信息的長度爲160位,由於生成的摘要信息更長,運算的過程更加複雜,在相同的硬件上, SHA-1的運行速度比MD5更慢,但是也更爲安全。



import com.google.common.base.Strings;

import java.security.MessageDigest;

/**
 * SHA的全稱是Secure Hash Algorithm,即安全散列算法
 * Created by fangzhipeng on 2017/3/21.
 */
public class SHAUtil {

    /**
     * 定義加密方式
     */
    private final static String KEY_SHA = "SHA";
    private final static String KEY_SHA1 = "SHA-1";
    /**
     * 全局數組
     */
    private final static String[] hexDigits = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

    /**
     * 構造函數
     */
    public SHAUtil() {

    }

    /**
     * SHA 加密
     * @param data 需要加密的字節數組
     * @return 加密之後的字節數組
     * @throws Exception
     */
    public static byte[] encryptSHA(byte[] data) throws Exception {
        // 創建具有指定算法名稱的信息摘要
//        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA1);
        // 使用指定的字節數組對摘要進行最後更新
        sha.update(data);
        // 完成摘要計算並返回
        return sha.digest();
    }

    /**
     * SHA 加密
     * @param data 需要加密的字符串
     * @return 加密之後的字符串
     * @throws Exception
     */
    public static String encryptSHA(String data) throws Exception {
        // 驗證傳入的字符串
        if (Strings.isNullOrEmpty(data)) {
            return "";
        }
        // 創建具有指定算法名稱的信息摘要
        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);
        // 使用指定的字節數組對摘要進行最後更新
        sha.update(data.getBytes());
        // 完成摘要計算
        byte[] bytes = sha.digest();
        // 將得到的字節數組變成字符串返回
        return byteArrayToHexString(bytes);
    }

    /**
     * 將一個字節轉化成十六進制形式的字符串
     * @param b 字節數組
     * @return 字符串
     */
    private static String byteToHexString(byte b) {
        int ret = b;
        //System.out.println("ret = " + ret);
        if (ret < 0) {
            ret += 256;
        }
        int m = ret / 16;
        int n = ret % 16;
        return hexDigits[m] + hexDigits[n];
    }

    /**
     * 轉換字節數組爲十六進制字符串
     * @param bytes 字節數組
     * @return 十六進制字符串
     */
    private static String byteArrayToHexString(byte[] bytes) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < bytes.length; i++) {
            sb.append(byteToHexString(bytes[i]));
        }
        return sb.toString();
    }

    /**
     * 測試方法
     * @param args
     */
    public static void main(String[] args) throws Exception {
        String key = "123";
        System.out.println(encryptSHA(key));
    }
}

二、對稱加密

對稱加密算法是應用較早的加密算法,技術成熟。在對稱加密算法中,數據發送方將明文(原始數據)和加密密鑰一起經過特殊加密算法處理後,生成複雜的加密密文進行發送,數據接收方收到密文後,若想讀取原文,則需要使用加密使用的密鑰及相同算法的逆算法對加密的密文進行解密,才能使其恢復成可讀明文。在對稱加密算法中,使用的密鑰只有一個,發送和接收雙方都使用這個密鑰對數據進行加密和解密,這就要求加密和解密方事先都必須知道加密的密鑰。

1. DES算法

1973 年,美國國家標準局(NBS)在認識到建立數據保護標準既明顯又急迫的情況下,開始徵集聯邦數據加密標準的方案。 1975 年3月17日, NBS公佈了IBM公司提供的密碼算法,以標準建議的形式在全國範圍內徵求意見。經過兩年多的公開討論之後, 1977 年7月15日, NBS宣佈接受這建議,作爲聯邦信息處理標準46 號數據加密標準(Data Encryptin Standard),即DES正式頒佈,供商業界和非國防性政府部門使用。DES算法屬於對稱加密算法,明文按64位進行分組,密鑰長64位,但事實上只有56位參與DES運算(第8、 16、 24、 32、 40、 48、 56、 64位是校驗位,使得每個密鑰都有奇數個1),分組後的明文和56位的密鑰按位替代或交換的方法形成密文。由於計算機運算能力的增強,原版DES密碼的密鑰長度變得容易被暴力破解,因此演變出了3DES算法。 3DES是DES向AES過渡的加密算法,它使用3條56位的密鑰對數據進行三次加密,是DES的一個更安全的變形。


import java.io.IOException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;


import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Data Encryptin Standard
 * 數據加密標準
 */
public class DESUtil {


    private final static String DES = "DES";

    /**
     * Description 根據鍵值進行加密
     *
     * @param data
     * @param key  加密鍵byte數組
     * @return
     * @throws Exception
     */
    public static String encrypt(String data, String key) throws Exception {
        byte[] bt = encrypt(data.getBytes(), key.getBytes());
        String strs = new BASE64Encoder().encode(bt);
        return strs;
    }

    /**
     * Description 根據鍵值進行解密
     *
     * @param data
     * @param key  加密鍵byte數組
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String key) throws Exception,
            Exception {
        if (data == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        byte[] buf = decoder.decodeBuffer(data);
        byte[] bt = decrypt(buf, key.getBytes());
        return new String(bt);
    }

    /**
     * Description 根據鍵值進行加密
     *
     * @param data
     * @param key  加密鍵byte數組
     * @return
     * @throws Exception
     */
    private static byte[] encrypt(byte[] data, byte[] key) throws Exception {
        // 生成一個可信任的隨機數源
        SecureRandom sr = new SecureRandom();

        // 從原始密鑰數據創建DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);

        // 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher對象實際完成加密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密鑰初始化Cipher對象
        cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }


    /**
     * Description 根據鍵值進行解密
     *
     * @param data
     * @param key  加密鍵byte數組
     * @return
     * @throws Exception
     */
    private static byte[] decrypt(byte[] data, byte[] key) throws Exception {
        // 生成一個可信任的隨機數源
        SecureRandom sr = new SecureRandom();

        // 從原始密鑰數據創建DESKeySpec對象
        DESKeySpec dks = new DESKeySpec(key);

        // 創建一個密鑰工廠,然後用它把DESKeySpec轉換成SecretKey對象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
        SecretKey securekey = keyFactory.generateSecret(dks);

        // Cipher對象實際完成解密操作
        Cipher cipher = Cipher.getInstance(DES);

        // 用密鑰初始化Cipher對象
        cipher.init(Cipher.DECRYPT_MODE, securekey, sr);

        return cipher.doFinal(data);
    }

    public static void main(String[]args)throws Exception{
       String  sStr=encrypt("122222112222:12343232323:jajwwwwslwskwkkwksk","wew2323w233321ws233w");
       System.out.println(sStr);
       String mStr=decrypt(sStr,"wew2323w233321ws233w");
       System.out.println(mStr);
    }
}

2. AES

AES的全稱是Advanced Encryption Standard,即高級加密標準,該算法由比利時密碼學家Joan Daemen和Vincent Rijmen所設計,結合兩位作者的名字,又稱Rijndael加密算法,是美國聯邦政府採用的一種對稱加密標準,這個標準用來替代原先的DES算法,已經廣爲全世界所使用,已然成爲對稱加密算法中最流行的算法之一。AES算法作爲新一代的數據加密標準匯聚了強安全性、高性能、高效率、易用和靈活等優點,設計有三個密鑰長度:128,192,256位,比DES算法的加密強度更高,更爲安全。


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Created by fangzhipeng on 2017/3/21.
 */
public class AESUtil {

    static  byte[]  key = "w@#$4@#$s^&3*&^4".getBytes();
    final static String algorithm="AES";

    public static String encrypt(String data){

        byte[] dataToSend = data.getBytes();
        Cipher c = null;
        try {
            c = Cipher.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SecretKeySpec k =  new SecretKeySpec(key, algorithm);
        try {
            c.init(Cipher.ENCRYPT_MODE, k);
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] encryptedData = "".getBytes();
        try {
            encryptedData = c.doFinal(dataToSend);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] encryptedByteValue =     Base64.getEncoder().encode(encryptedData);
        return  new String(encryptedByteValue);//.toString();
    }

    public static String decrypt(String data){

        byte[] encryptedData  =  Base64.getDecoder().decode(data);
        Cipher c = null;
        try {
            c = Cipher.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        SecretKeySpec k =
                new SecretKeySpec(key, algorithm);
        try {
            c.init(Cipher.DECRYPT_MODE, k);
        } catch (InvalidKeyException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        byte[] decrypted = null;
        try {
            decrypted = c.doFinal(encryptedData);
        } catch (IllegalBlockSizeException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (BadPaddingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new String(decrypted);
    }

    public static void main(String[] args){
        String password=encrypt("12233440988:1239874389888:dd333");
        System.out.println(password);
        System.out.println(decrypt(password));
    }
}

三、非對稱加密

非對稱加密算法又稱爲公開密鑰加密算法,它需要兩個密鑰,一個稱爲公開密鑰(public key),即公鑰,另一個稱爲私有密鑰(private key),即私鑰。公鑰與私鑰需要配對使用,如果用公鑰對數據進行加密,只有用對應的私鑰才能進行解密,而如果使用私鑰對數據進行加密,那麼只有用對應的公鑰才能進行解密。因爲加密和解密使用的是兩個不同的密鑰,所以這種算法稱爲非對稱加密算法。非對稱加密算法實現機密信息交換的基本過程是:甲方生成一對密鑰並將其中的一把作爲公鑰向其它人公開,得到該公鑰的乙方使用該密鑰對機密信息進行加密後再發送給甲方,甲方再使用自己保存的另一把專用密鑰,即私鑰,對加密後的信息進行解密。

1.RSA

RSA非對稱加密算法是1977年由Ron Rivest、 Adi Shamirh和LenAdleman開發的, RSA取名來自開發他們三者的名字。 RSA是目前最有影響力的非對稱加密算法,它能夠抵抗到目前爲止已知的所有密碼攻擊,已被ISO推薦爲公鑰數據加密標準。 RSA算法基於一個十分簡單的數論事實:將兩個大素數相乘十分容易,但反過來想要對其乘積進行因式分解卻極其困難,因此可以將乘積公開作爲加密密鑰。


/**
 * Created by fangzhipeng on 2017/3/21.
 * RSA :RSA非對稱加密算法是1977年由Ron Rivest、 Adi Shamirh和LenAdleman開發   *  的, RSA取名來
 *  自開發他們三者的名字。
 * 參考:http://blog.csdn.net/wangqiuyun/article/details/42143957
 */

import java.io.*;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSAUtil {


    /**
     * 字節數據轉字符串專用集合
     */
    private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * 隨機生成密鑰對
     */
    public static void genKeyPair(String filePath) {
        // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
        KeyPairGenerator keyPairGen = null;
        try {
            keyPairGen = KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // 初始化密鑰對生成器,密鑰大小爲96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一個密鑰對,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        // 得到私鑰
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        // 得到公鑰
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        try {
            // 得到公鑰字符串
            // 得到私鑰字符串
            String privateKeyString =new String( Base64.getEncoder().encode(privateKey.getEncoded()));
            String publicKeyString =new String( Base64.getEncoder().encode(publicKey.getEncoded()));
            // 將密鑰對寫入到文件

            File file1=new File(filePath + "publicKey.keystore");
            File file2=new File(filePath + "privateKey.keystore");
            if(!file1.exists()) {
                file1.createNewFile();
            }
            if(!file2.exists()) {
                file2.createNewFile();
            }
            FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore");
            FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore");
            BufferedWriter pubbw = new BufferedWriter(pubfw);
            BufferedWriter pribw = new BufferedWriter(prifw);
            pubbw.write(publicKeyString);
            pribw.write(privateKeyString);
            pubbw.flush();
            pubbw.close();
            pubfw.close();
            pribw.flush();
            pribw.close();
            prifw.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 從文件中輸入流中加載公鑰
     *
     * @param
     *
     * @throws Exception
     *             加載公鑰時產生的異常
     */
    public static String loadPublicKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/publicKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("公鑰數據流讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("公鑰輸入流爲空");
        }
    }

    /**
     * 從字符串中加載公鑰
     *
     * @param publicKeyStr
     *            公鑰數據字符串
     * @throws Exception
     *             加載公鑰時產生的異常
     */
    public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.getDecoder().decode(publicKeyStr);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公鑰非法");
        } catch (NullPointerException e) {
            throw new Exception("公鑰數據爲空");
        }
    }

    /**
     * 從文件中加載私鑰
     *
     * @param
     *
     * @return 是否成功
     * @throws Exception
     */
    public static String loadPrivateKeyByFile(String path) throws Exception {
        try {
            BufferedReader br = new BufferedReader(new FileReader(path
                    + "/privateKey.keystore"));
            String readLine = null;
            StringBuilder sb = new StringBuilder();
            while ((readLine = br.readLine()) != null) {
                sb.append(readLine);
            }
            br.close();
            return sb.toString();
        } catch (IOException e) {
            throw new Exception("私鑰數據讀取錯誤");
        } catch (NullPointerException e) {
            throw new Exception("私鑰輸入流爲空");
        }
    }

    public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
            throws Exception {
        try {
            byte[] buffer = Base64.getDecoder().decode(privateKeyStr);
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私鑰非法");
        } catch (NullPointerException e) {
            throw new Exception("私鑰數據爲空");
        }
    }

    /**
     * 公鑰加密過程
     *
     * @param publicKey
     *            公鑰
     * @param plainTextData
     *            明文數據
     * @return
     * @throws Exception
     *             加密過程中的異常信息
     */
    public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("加密公鑰爲空, 請設置");
        }
        Cipher cipher = null;
        try {
            // 使用默認RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密公鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文數據已損壞");
        }
    }

    /**
     * 私鑰加密過程
     *
     * @param privateKey
     *            私鑰
     * @param plainTextData
     *            明文數據
     * @return
     * @throws Exception
     *             加密過程中的異常信息
     */
    public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私鑰爲空, 請設置");
        }
        Cipher cipher = null;
        try {
            // 使用默認RSA
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(plainTextData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("加密私鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文數據已損壞");
        }
    }

    /**
     * 私鑰解密過程
     *
     * @param privateKey
     *            私鑰
     * @param cipherData
     *            密文數據
     * @return 明文
     * @throws Exception
     *             解密過程中的異常信息
     */
    public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
            throws Exception {
        if (privateKey == null) {
            throw new Exception("解密私鑰爲空, 請設置");
        }
        Cipher cipher = null;
        try {
            // 使用默認RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密私鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文數據已損壞");
        }
    }

    /**
     * 公鑰解密過程
     *
     * @param publicKey
     *            公鑰
     * @param cipherData
     *            密文數據
     * @return 明文
     * @throws Exception
     *             解密過程中的異常信息
     */
    public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
            throws Exception {
        if (publicKey == null) {
            throw new Exception("解密公鑰爲空, 請設置");
        }
        Cipher cipher = null;
        try {
            // 使用默認RSA
            cipher = Cipher.getInstance("RSA");
            // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, publicKey);
            byte[] output = cipher.doFinal(cipherData);
            return output;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("無此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        } catch (InvalidKeyException e) {
            throw new Exception("解密公鑰非法,請檢查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文長度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文數據已損壞");
        }
    }

    /**
     * 字節數據轉十六進制字符串
     *
     * @param data
     *            輸入數據
     * @return 十六進制內容
     */
    public static String byteArrayToString(byte[] data) {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < data.length; i++) {
            // 取出字節的高四位 作爲索引得到相應的十六進制標識符 注意無符號右移
            stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
            // 取出字節的低四位 作爲索引得到相應的十六進制標識符
            stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
            if (i < data.length - 1) {
                stringBuilder.append(' ');
            }
        }
        return stringBuilder.toString();
    }



    public static void main(String[] args) throws Exception {
        String filepath="F:/temp/";
        File file=new File(filepath);
        if(!file.exists()){
            file.mkdir();
        }
        genKeyPair(filepath);
        System.out.println("--------------公鑰加密私鑰解密過程-------------------");
        String plainText="1223333323:8783737321232:dewejj28i33e92hhsxxxx";
        //公鑰加密過程
        byte[] cipherData=encrypt(loadPublicKeyByStr(loadPublicKeyByFile(filepath)),plainText.getBytes());
        String cipher=new String(Base64.getEncoder().encode(cipherData));
        //私鑰解密過程
        byte[] res=decrypt(loadPrivateKeyByStr(loadPrivateKeyByFile(filepath)), Base64.getDecoder().decode(cipher));
        String restr=new String(res);
        System.out.println("原文:"+plainText);
        System.out.println("加密密文:"+cipher);
        System.out.println("解密:"+restr);
        System.out.println();
    }
}

轉載聲明:本文轉自方誌朋,常見的安全算法

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