1. 程式人生 > >RSA加密解密實現

RSA加密解密實現

概述

RSA被稱為非對稱性加密演算法,意思就是加密和解密用的不是同一份金鑰。RSA演算法的金鑰分為公鑰和私鑰,兩者內容不同,用途也不同。公鑰用於加密,一般交給客戶端使用;私鑰用於解密,一般由伺服器管理。反過來,對稱性加密演算法,指的就是用同一份金鑰進行加密解密了,比如DES加密演算法。

RSA演算法實現

一、生成金鑰對

在使用RSA加密解密之前,首先要生成金鑰對。RSA演算法的金鑰可以通過兩個途徑生成,一是藉助openssl命令終端,二是使用程式碼生成。

1、Openssl生成金鑰對

首先你得安裝Openssl,這裡就不再敘述如何安裝Openssl了,正好給你個機會去撩一下度娘。

第一步,生成私鑰。現在我們找到openssl安裝目錄的bin資料夾,雙擊開啟openssl.exe,輸入命令

genrsa -out rsa_private_key.pem 1024



在openssl.exe的同級目錄下可以找到生成的私鑰檔案rsa_private_key.pem,開啟後看到的內容類似下面

-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQC7yil5BUsHf+PdPl9fzdr3FNyrXDPJwV8Vfk3hCsiqs3YzHYjE
YpHZiaF8dg9wB/aqmKRA0KFH2eTv++GNf0fAtdfbZUeq1Y79BDs23kSoS6g0Xe8m
D76A2oD+G0o/llsBjpmWViFaCre0uALyOwd412pU7yj+IJU+JlNlxLapNwIDAQAB
AoGAH0C+9DgwS3g6WQjXYJ9m8LYVH6PBrrMy+uXBWlGsIdSqOEmTCHQLJ/Qi3w7a
9N8uayfqNitCnC2kT1hRKnZjX2Miy0LCfLsH6REV1NUgSmC7lr/TKkq9Hnvp1Y0H
bi7u5ux6QUzY8Yb7f6go7rAk764EikV8QeuRKsQP0jaPIckCQQDg8yyWlsWL298C
sn15tQAqmNI8kWpmOmZuvNE0oTzodsMCfi0K3e5c3KtHUgso1hPWTxJguRpWw1jS
4NsoYWJTAkEA1bXlP1vHF4DW9XjoE/VSb3ReUXvqCx96IrdxcKXKOPrNsGOpKBkL
3x74jImXjIiSEe4ePvOHsQ5HgB9scPlJDQJATcrKuKkbV+qJjN09F0HI9PI0gk2n
hgLcOZ+CmbjI33typQINgZyOOf72HIv63/xoj8x4hop82VRk+0hXgfdrkQJABQFo
qC4/IIbNAhzd2rHRR3kDSIdNeQs4sh1307qeXO1K6gm7iYvkoko4ahpC6XC9cxwP
q0vK7tO1ywNxZ8f+9QJAO2sXpLl4G/I0xrizv9Yoe7MON+8CsMXIUb0Swf3Q4Bbj
YNWXYD1BBa1qkIQU48dLgbJU24Abzl57nkSN/nns4A==
-----END RSA PRIVATE KEY-----

請忽略帶有虛線的第一行和最後一行,中間的內容就是我們的私鑰了。

第二步,生成公鑰。繼續在openssl終端視窗輸入命令:

rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout  


這裡根據私鑰資料,生成了公鑰,同樣也是儲存在openssl.exe同級目錄下,開啟看裡面的內容:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC7yil5BUsHf+PdPl9fzdr3FNyr
XDPJwV8Vfk3hCsiqs3YzHYjEYpHZiaF8dg9wB/aqmKRA0KFH2eTv++GNf0fAtdfb
ZUeq1Y79BDs23kSoS6g0Xe8mD76A2oD+G0o/llsBjpmWViFaCre0uALyOwd412pU
7yj+IJU+JlNlxLapNwIDAQAB
-----END PUBLIC KEY-----

到這裡,金鑰對基本生成了,但是這個金鑰對的私鑰無法在程式碼中直接使用,需要對私鑰進行PKCS#8編碼,繼續敲命令:
pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt


同樣在openssl.exe同級目錄下找到檔案pkcs8_rsa_private_key.pem,這裡就是我們最終需要的私鑰了。

下面可以看到內容跟rsa_private_key.pem裡面的內容是不一樣的:

-----BEGIN PRIVATE KEY-----
MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALvKKXkFSwd/490+
X1/N2vcU3KtcM8nBXxV+TeEKyKqzdjMdiMRikdmJoXx2D3AH9qqYpEDQoUfZ5O/7
4Y1/R8C119tlR6rVjv0EOzbeRKhLqDRd7yYPvoDagP4bSj+WWwGOmZZWIVoKt7S4
AvI7B3jXalTvKP4glT4mU2XEtqk3AgMBAAECgYAfQL70ODBLeDpZCNdgn2bwthUf
o8GuszL65cFaUawh1Ko4SZMIdAsn9CLfDtr03y5rJ+o2K0KcLaRPWFEqdmNfYyLL
QsJ8uwfpERXU1SBKYLuWv9MqSr0ee+nVjQduLu7m7HpBTNjxhvt/qCjusCTvrgSK
RXxB65EqxA/SNo8hyQJBAODzLJaWxYvb3wKyfXm1ACqY0jyRamY6Zm680TShPOh2
wwJ+LQrd7lzcq0dSCyjWE9ZPEmC5GlbDWNLg2yhhYlMCQQDVteU/W8cXgNb1eOgT
9VJvdF5Re+oLH3oit3Fwpco4+s2wY6koGQvfHviMiZeMiJIR7h4+84exDkeAH2xw
+UkNAkBNysq4qRtX6omM3T0XQcj08jSCTaeGAtw5n4KZuMjfe3KlAg2BnI45/vYc
i/rf/GiPzHiGinzZVGT7SFeB92uRAkAFAWioLj8ghs0CHN3asdFHeQNIh015Cziy
HXfTup5c7UrqCbuJi+SiSjhqGkLpcL1zHA+rS8ru07XLA3Fnx/71AkA7axekuXgb
8jTGuLO/1ih7sw437wKwxchRvRLB/dDgFuNg1ZdgPUEFrWqQhBTjx0uBslTbgBvO
XnueRI3+eezg
-----END PRIVATE KEY-----


2、程式碼生成金鑰對

除了上面的openssl方法可以生成金鑰對外,使用程式碼也是可以生成的,具體的程式碼如下:

    public static KeyPair generateRSAKeyPair(int keyLength)
    {
        try
        {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            return null;
        }
    }

keyLength範圍512~2048,一般取1024,其他值本人沒嘗試過,有探索精神的可以自行更改。

通過keyPair.getPublic().getEncoded(),keyPair.getPrivate().getEncoded()分別獲取公鑰、私鑰的位元組碼。

為了更直觀一點,可以通過Base64編碼把位元組碼轉為可讀的字串儲存起來 Base64Utils.encode(rsaKeyPair.getPublic().getEncoded());

二、RSA加密解密程式碼實現

廢話少說,趕著回家吃飯,上程式碼:

package com.yspay.sdk.util;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/**
 * 
 */
public final class RSAUtils
{
    private static String RSA = "RSA";

    /**
     * 隨機生成RSA金鑰對(預設金鑰長度為1024)
     *
     * @return
     */
    public static KeyPair generateRSAKeyPair()
    {
        return generateRSAKeyPair(1024);
    }

    /**
     * 隨機生成RSA金鑰對
     *
     * @param keyLength
     *            金鑰長度,範圍:512~2048<br>
     *            一般1024
     * @return
     */
    public static KeyPair generateRSAKeyPair(int keyLength)
    {
        try
        {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance(RSA);
            kpg.initialize(keyLength);
            return kpg.genKeyPair();
        } catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 用公鑰加密 <br>
     * 每次加密的位元組數,不能超過金鑰的長度值除以 8 再減去 11,所以採取分段加密的方式規避
     *
     * @param data 需加密資料的byte資料
     * @param publicKey 公鑰
     * @return 加密後的byte型資料
     */
    public static byte[] encryptData(byte[] data, PublicKey publicKey)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(RSA);
            // 編碼前設定編碼方式及金鑰
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);

            RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
            // 模長
            int keyLen = rsaPublicKey.getModulus().bitLength() / 8;
            int maxEncryptBlock = keyLen - 11;

            //如果明文長度大於模長-11則要分組加密
            int inputLen = data.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] temp;
            int i = 0;
            // 對資料分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > maxEncryptBlock) {
                    temp = cipher.doFinal(data, offSet, maxEncryptBlock);
                } else {
                    temp = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(temp, 0, temp.length);
                i++;
                offSet = i * maxEncryptBlock;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();
            // 傳入編碼資料並返回編碼結果
            return encryptedData;
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 用私鑰解密
     *
     * @param encryptedData 經過encryptedData()加密返回的byte資料
     * @param privateKey 私鑰
     * @return
     */
    public static byte[] decryptData(byte[] encryptedData, PrivateKey privateKey)
    {
        try
        {
            Cipher cipher = Cipher.getInstance(RSA);
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) privateKey;
            // 模長
            int keyLen = rsaPrivateKey.getModulus().bitLength() / 8;
            int maxDecryptBlock = keyLen;//不用減11

            //如果密文長度大於模長則要分組解密
            int inputLen = encryptedData.length;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int offSet = 0;
            byte[] temp;
            int i = 0;
            // 對資料分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > maxDecryptBlock) {
                    temp = cipher.doFinal(encryptedData, offSet, maxDecryptBlock);
                } else {
                    temp = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(temp, 0, temp.length);
                i++;
                offSet = i * maxDecryptBlock;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();

            return decryptedData;
        } catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通過公鑰byte[](publicKey.getEncoded())將公鑰還原,適用於RSA演算法
     *
     * @param keyBytes
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PublicKey getPublicKey(byte[] keyBytes) throws NoSuchAlgorithmException,
            InvalidKeySpecException
    {
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 通過私鑰byte[]將公鑰還原,適用於RSA演算法
     *
     * @param keyBytes
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PrivateKey getPrivateKey(byte[] keyBytes) throws NoSuchAlgorithmException,
            InvalidKeySpecException
    {
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 使用N、e值還原公鑰
     *
     * @param modulus
     * @param publicExponent
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PublicKey getPublicKey(String modulus, String publicExponent)
            throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        BigInteger bigIntModulus = new BigInteger(modulus);
        BigInteger bigIntPrivateExponent = new BigInteger(publicExponent);
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /**
     * 使用N、d值還原私鑰
     *
     * @param modulus
     * @param privateExponent
     * @return
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeySpecException
     */
    public static PrivateKey getPrivateKey(String modulus, String privateExponent)
            throws NoSuchAlgorithmException, InvalidKeySpecException
    {
        BigInteger bigIntModulus = new BigInteger(modulus);
        BigInteger bigIntPrivateExponent = new BigInteger(privateExponent);
        RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
        KeyFactory keyFactory = KeyFactory.getInstance(RSA);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /**
     * 從字串中載入公鑰
     *
     * @param publicKeyStr
     *            公鑰資料字串
     * @throws Exception
     *             載入公鑰時產生的異常
     */
    public static PublicKey loadPublicKey(String publicKeyStr) throws Exception
    {
        try
        {
            byte[] buffer = Base64Utils.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("公鑰資料為空");
        }
    }

    /**
     * 從字串中載入私鑰<br>
     * 載入時使用的是PKCS8EncodedKeySpec(PKCS#8編碼的Key指令)。
     *
     * @param privateKeyStr
     * @return
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(String privateKeyStr) throws Exception
    {
        try
        {
            byte[] buffer = Base64Utils.decode(privateKeyStr);
            //X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
            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 in
     *            公鑰輸入流
     * @throws Exception
     *             載入公鑰時產生的異常
     */
    public static PublicKey loadPublicKey(InputStream in) throws Exception
    {
        try
        {
            return loadPublicKey(readKey(in));
        } catch (IOException e)
        {
            throw new Exception("公鑰資料流讀取錯誤");
        } catch (NullPointerException e)
        {
            throw new Exception("公鑰輸入流為空");
        }
    }

    /**
     * 從檔案中載入私鑰
     * @param in
     * @return 私鑰
     * @throws Exception
     */
    public static PrivateKey loadPrivateKey(InputStream in) throws Exception
    {
        try
        {
            return loadPrivateKey(readKey(in));
        } catch (IOException e)
        {
            throw new Exception("私鑰資料讀取錯誤");
        } catch (NullPointerException e)
        {
            throw new Exception("私鑰輸入流為空");
        }
    }

    /**
     * 讀取金鑰資訊
     *
     * @param in
     * @return
     * @throws IOException
     */
    private static String readKey(InputStream in) throws IOException
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String readLine = null;
        StringBuilder sb = new StringBuilder();
        while ((readLine = br.readLine()) != null)
        {
            if (readLine.charAt(0) == '-')
            {
                continue;
            } else
            {
                sb.append(readLine);
                sb.append('\r');
            }
        }

        return sb.toString();
    }

}

Base64編碼工具可以使用系統自帶的android.util.Base64,也可以自己實現,以下是 從別處扣來的程式碼:
package com.yspay.sdk.util;

import java.io.UnsupportedEncodingException;

/**
 * Created by MPC on 2017/5/24.
 */

public class Base64Utils {

    private static char[] base64EncodeChars = new char[]
            { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5',
                    '6', '7', '8', '9', '+', '/' };
    private static byte[] base64DecodeChars = new byte[]
            { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
                    -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53,
                    54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
                    12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29,
                    30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1,
                    -1, -1, -1 };

    /**
     * 加密
     *
     * @param data
     * @return
     */
    public static String encode(byte[] data)
    {
        StringBuffer sb = new StringBuffer();
        int len = data.length;
        int i = 0;
        int b1, b2, b3;
        while (i < len)
        {
            b1 = data[i++] & 0xff;
            if (i == len)
            {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
                sb.append("==");
                break;
            }
            b2 = data[i++] & 0xff;
            if (i == len)
            {
                sb.append(base64EncodeChars[b1 >>> 2]);
                sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
                sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
                sb.append("=");
                break;
            }
            b3 = data[i++] & 0xff;
            sb.append(base64EncodeChars[b1 >>> 2]);
            sb.append(base64EncodeChars[((b1 & 0x03) << 4) | ((b2 & 0xf0) >>> 4)]);
            sb.append(base64EncodeChars[((b2 & 0x0f) << 2) | ((b3 & 0xc0) >>> 6)]);
            sb.append(base64EncodeChars[b3 & 0x3f]);
        }
        return sb.toString();
    }

    /**
     * 解密
     *
     * @param str
     * @return
     */
    public static byte[] decode(String str)
    {
        try
        {
            return decodePrivate(str);
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return new byte[]
                {};
    }

    private static byte[] decodePrivate(String str) throws UnsupportedEncodingException
    {
        StringBuffer sb = new StringBuffer();
        byte[] data = null;
        data = str.getBytes("US-ASCII");
        int len = data.length;
        int i = 0;
        int b1, b2, b3, b4;
        while (i < len)
        {

            do
            {
                b1 = base64DecodeChars[data[i++]];
            } while (i < len && b1 == -1);
            if (b1 == -1)
                break;

            do
            {
                b2 = base64DecodeChars[data[i++]];
            } while (i < len && b2 == -1);
            if (b2 == -1)
                break;
            sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));

            do
            {
                b3 = data[i++];
                if (b3 == 61)
                    return sb.toString().getBytes("iso8859-1");
                b3 = base64DecodeChars[b3];
            } while (i < len && b3 == -1);
            if (b3 == -1)
                break;
            sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));

            do
            {
                b4 = data[i++];
                if (b4 == 61)
                    return sb.toString().getBytes("iso8859-1");
                b4 = base64DecodeChars[b4];
            } while (i < len && b4 == -1);
            if (b4 == -1)
                break;
            sb.append((char) (((b3 & 0x03) << 6) | b4));
        }
        return sb.toString().getBytes("iso8859-1");
    }
}

最後附上工程程式碼,此處傳送門:點選開啟連結

工程介面如下: