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


最后附上工程代码,此处传送门:点击打开链接


工程界面如下:








展开阅读全文

没有更多推荐了,返回首页