JAVA加密解密之RSA算法

时间:2021-12-13 03:59:34

RSA算法简介

RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。1987年首次公布,当时他们三人都在麻省理工学院工作。RSA就是他们三人姓氏开头字母拼在一起组成的。RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,已被ISO推荐为公钥数据加密标准。今天只有短的RSA钥匙才可能被强力方式解破。到2008年为止,世界上还没有任何可靠的攻击RSA算法的方式。只要其钥匙的长度足够长,用RSA加密的信息实际上是不能被解破的。但在分布式计算和量子计算机理论日趋成熟的今天,RSA加密安全性受到了挑战。RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

  1. 甲方构建密钥对儿,将公钥公布给乙方,将私钥保留。
  2. 甲方使用私钥加密数据,然后用私钥对加密后的数据签名,发送给乙方签名以及加密后的数据;乙方使用公钥、签名来验证待解密数据是否有效。
  3. 如果有效使用公钥对数据解密。 乙方使用公钥加密数据,向甲方发送经过加密后的数据;甲方获得加密数据,通过私钥解密。

RSA算法实现

package com.jianggujin.codec;

import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

/** * RSA * * @author jianggujin * */
public class HQRSA {
   private static HQRSA rsa = new HQRSA();

   public static HQRSA getInstance()
   {
      return rsa;
   }

   private HQRSA()
   {
   }

   /** * RSA签名算法 * * @author jianggujin * */
   public static enum HQRSASignatureAlgorithm
   {

      MD2withRSA("MD2withRSA"), MD5withRSA("MD5withRSA"), SHA1withRSA("SHA1withRSA"), SHA224withRSA(
            "SHA224withRSA"), SHA256withRSA(
                  "SHA256withRSA"), SHA384withRSA("SHA384withRSA"), SHA512withRSA("SHA512withRSA");
      private String name;

      private HQRSASignatureAlgorithm(String name)
      {
         this.name = name;
      }

      public String getName()
      {
         return this.name;
      }
   }

   private static final String ALGORITHM = "RSA";

   public byte[] sign(byte[] data, byte[] privateKey, HQRSASignatureAlgorithm signatureAlgorithm) throws Exception
   {
      return sign(data, privateKey, signatureAlgorithm.getName());
   }

   public byte[] sign(byte[] data, byte[] privateKey, String signatureAlgorithm) throws Exception
   {
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);

      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

      PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);

      Signature signature = Signature.getInstance(signatureAlgorithm);
      signature.initSign(priKey);
      signature.update(data);
      return signature.sign();
   }

   public boolean verify(byte[] data, byte[] publicKey, byte[] sign, HQRSASignatureAlgorithm signatureAlgorithm)
         throws Exception
   {
      return verify(data, publicKey, sign, signatureAlgorithm.getName());
   }

   public boolean verify(byte[] data, byte[] publicKey, byte[] sign, String signatureAlgorithm) throws Exception
   {
      X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKey);

      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

      PublicKey pubKey = keyFactory.generatePublic(keySpec);

      Signature signature = Signature.getInstance(signatureAlgorithm);
      signature.initVerify(pubKey);
      signature.update(data);

      return signature.verify(sign);
   }

   public byte[] encrypt(HQKeyType keyType, byte[] data, byte[] key) throws Exception
   {
      switch (keyType)
      {
      case PRIVATE:
         return encryptByPrivateKey(data, key);
      case PUBLIC:
         return encryptByPublicKey(data, key);
      default:
         throw new IllegalArgumentException();
      }
   }

   /** * 公钥加密 * * @param data * @param publicKey * @return * @throws Exception */
   private byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception
   {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, publicK);

      return cipher.doFinal(data);
   }

   /** * 私钥加密 * * @param data * @param privateKey * @return * @throws Exception */
   private byte[] encryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception
   {
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.ENCRYPT_MODE, privateK);
      return cipher.doFinal(data);
   }

   public byte[] decrypt(HQKeyType keyType, byte[] data, byte[] key) throws Exception
   {
      switch (keyType)
      {
      case PRIVATE:
         return decryptByPrivateKey(data, key);
      case PUBLIC:
         return decryptByPublicKey(data, key);
      default:
         throw new IllegalArgumentException();
      }
   }

   /** * 公钥解密 * * @param data * @param publicKey * @return * @throws Exception */
   private byte[] decryptByPublicKey(byte[] data, byte[] publicKey) throws Exception
   {
      X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(publicKey);
      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
      Key publicK = keyFactory.generatePublic(x509KeySpec);

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, publicK);
      return cipher.doFinal(data);
   }

   /** * 私钥解密 * * @param data * @param privateKey * @return * @throws Exception */
   private byte[] decryptByPrivateKey(byte[] data, byte[] privateKey) throws Exception
   {
      PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKey);
      KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
      Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);

      Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
      cipher.init(Cipher.DECRYPT_MODE, privateK);
      return cipher.doFinal(data);
   }

   /** * 初始化密钥 * * @return */
   public HQKeyPair initKey() throws Exception
   {
      return initKey(1024);
   }

   /** * 初始化密钥 * * @param keySize * @return */
   public HQKeyPair initKey(int keySize) throws Exception
   {
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(ALGORITHM);
      keyPairGen.initialize(1024);
      KeyPair keyPair = keyPairGen.generateKeyPair();
      return new HQKeyPair(keyPair);
   }
}

测试代码:

import org.junit.Test;

import com.jianggujin.codec.HQBase64;
import com.jianggujin.codec.HQKeyPair;
import com.jianggujin.codec.HQKeyType;
import com.jianggujin.codec.HQRSA;
import com.jianggujin.codec.HQRSA.HQRSASignatureAlgorithm;

public class RSATest {
   HQRSA rsa = HQRSA.getInstance();
   HQBase64 base64 = HQBase64.getInstance();

   @Test
   public void encode() throws Exception
   {
      byte[] data = "jianggujin".getBytes();
      HQKeyPair keyPair = rsa.initKey();
      System.err.println("私钥:" + base64.encodeToString(keyPair.getPrivateKey()));
      System.err.println("公钥:" + base64.encodeToString(keyPair.getPublicKey()));
      HQRSASignatureAlgorithm[] algorithms = HQRSASignatureAlgorithm.values();
      for (HQRSASignatureAlgorithm algorithm : algorithms)
      {
         System.err.println("=========================================");
         System.err.println(algorithm);
         byte[] sign = rsa.sign(data, keyPair.getPrivateKey(), algorithm);
         System.err.println("签名:" + base64.encodeToString(sign));
         System.err.println("验签:" + rsa.verify(data, keyPair.getPublicKey(), sign, algorithm));
         byte[] prie = rsa.encrypt(HQKeyType.PRIVATE, data, keyPair.getPrivateKey());
         System.err.println("私钥加密:" + base64.encodeToString(prie));
         System.err.println("公钥解密:" + new String(rsa.decrypt(HQKeyType.PUBLIC, prie, keyPair.getPublicKey())));
         byte[] pube = rsa.encrypt(HQKeyType.PUBLIC, data, keyPair.getPublicKey());
         System.err.println("公钥加密:" + base64.encodeToString(pube));
         System.err.println("私钥解密:" + new String(rsa.decrypt(HQKeyType.PRIVATE, pube, keyPair.getPrivateKey())));
      }
   }
}

测试结果:
私钥:MIICd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SA
签名:cd6ZTjFByAEStmrdRvGYI1vdemC/BL1OMSZO5UuXTOmYs9W8gG1SKyq2vfmEG4XgY/jmocWb0lEuB+hMn9NTpWuo2b9azhueoLs8wqJ+Ryxgndudjv9x4XvlDMFrTZpne1hewxpnhHr1qaRtNeu0FHR0apGPwNxOA+gLH1aIRLA=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:g/K+fMxKWH4+Rh5cuunxLcFOi3N2q6XD38Oq2Qa5DN+t8BSXk0Akhwk4V054an945XXHu2fhBEBJ/Zy4UMfVJLQvjOjRR7rRgVbO1Cqs2XGLs07wL2gNV3wChoy33kNaz/mjq+FiQx4RLYQql4DS2MVzoFMb43h0BGUYL0SOCdg=
私钥解密:jianggujin
=========================================
MD5withRSA
签名:KXpqiNuMJjA6LkNCd+kZThrCJGpCVdB1EkE2mIHqjI6ji3Tu2le6ZHL76YFANR8yh0UO5CbO9+ZIYBduzZ43CRzJWWTr4mmEuNoDnBxS9ejqzGgjYep1MBLPzRql3ldWwh8s/wsIXgJ5Dp7peRufdZ8sriGLRDo84eZd9VjkirQ=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:PkFxsTREDTU5Bd/c9bQmgE1PIn7cSf80q+8PMJ0ZhsyNwMYivlKRFPQiymRU/hYV3DK37a6yC5z98/ZE6nykFbuDk2kWjQEGapRw7w565XvU3Cb7VMU3SgBXyWHvnbKhY8bAi86BVRItgzsXzqYiAiwIj6p/VVTBz8BFpvujJWc=
私钥解密:jianggujin
=========================================
SHA1withRSA
签名:jldqy5WTOfQw+bAdX4pt7bPeN0nZFel6vSPRzKvDOo5oXfGKwH+q2Kbft5LG68BKd6PgNR7p/SyTSkbJON/FP8OLZfBQQ5zFsrM2lk5aCX7FfOzkZDbTzSUJTp5OR602zCJRIM4bltrrQF+8P49LmjF1TrTDdhK0+vxTJ5970EM=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:K6tZzDEc6HcRLJvvnrGe2TXwu3d5nX7TERhCFoZ4OGrV2QuM7nrRN7QNYYaqK2r2iZR6R6Dk1i1yVJCBDyQfw7+Kz2EHVm7ioIiXJhy1XE7Gs9cRE5STB9MLtcfpsJSfaKIOJM5V16fuEBPBTwl/eZpYZKCRxXVztjUt4uJ87Gw=
私钥解密:jianggujin
=========================================
SHA224withRSA
签名:DVhYCFH3FLjoEeyV+oG6KLWzzvZBNVil938dmhRe4ipya0oX7TOINpFHR9wO+WoQwxJ6OvImKo8y3bqrlgD2MeGByz60TrprcYKBCWQ7aP8rnR6Jk77NOVpjeh2ENgx3i9TdjA0YCarKtZON4S0B2Yf0e/PT2yk0p6jO9aDhdDs=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:ZZLJ6OMPFInWgC+Z5v5gSN20DojnR3wdyaUDKVYO2rdWbnrSR2lPD8sml9mvnN1hSN+ZAg3M4MjBefCJPiylnNOFjKYVql1gwnNZ21/Oj51U3KUxLUSmxrODH2sovI1XGnAucEn/r7jX5vMfK5xLuvg2sOCFo7fRd2WDf8Oscaw=
私钥解密:jianggujin
=========================================
SHA256withRSA
签名:gE1w1oTYDoanut2Y3bib3mfSB4s35D/LuXjDW3Mvp2m1hNJB3n2ZSf0jbDwS8O9WGEwgHHrPYqEKsT3FR+qZZKB1zYqwyqCxaA1hpCrXYHOTGQMKUI5OfLh4oItTlSqc+Es9X/c6iHsyFbPz/auPaouJjfmgvMjp+zFKRFax8fU=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:AU4qRyytGEUhetmxVVocG2tGYCY1mPmU+m21Y4nuwMOEB9+g0X/UtBPfLBirGxwU5rjK0qC3h8l4EyI9PI/4AdC/Wa7Z46RJddMvyNui8qIXwMV4Kc+pgLylmehErZEULv1s0Ce1gQncwMyRHfebBMB/ZU7HOOPn3bpi4fcnG3w=
私钥解密:jianggujin
=========================================
SHA384withRSA
签名:crOpZmb0n6hciB28zpwk5nw/R2BaVMHVDqUrJnZCu6d9pqKJkUUb/etr/8HOs3D7nA8pSrtSq1yy7g8wwYlGtIGujbI3sJVc10DDL/2vNV58L4ufG9AvsG8vo0+5IHxwWT0V9ZtYmvxez9JSJ6S5L19+/nDas79c9TWfu3HNlTw=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:FuVJtG71Nn6IshJbXapt4wuZiFBRi95fxJg62vnde77U+VkOoCMsc+j4ktC3aWRWiBLDM3582/x186o+o/cJOiqYlNGU7GR3RgrrXnTsIIPEIhJoi7nXyeSBZD3ZiTFBAW2Jv88bgUf0dVteZNYA7h01VWhgxNbN/p+tlfwf77Y=
私钥解密:jianggujin
=========================================
SHA512withRSA
签名:QhUfuk8rxghcDyHOWUVh9wOBAXmW9KXwiAhNo3Hr+895eDmdv6xJFpJrsErAu56xtBz6eQ65G/4idZ3CMYu2flZmvMpgXmm0RlPB1bK9FIY1TpgH9A0/vgJu8UDMT0AsI8nKE0G4XG81gM5vrnjE7HObHWoIc4rW+YIUNZeaKyI=
验签:true
私钥加密:d8dkS+obAvhw3XOukxi5UVmqJwOqV2OTJqnnit7nGDHBs/kkply+wFP/tw6z9ACJyYMdmME+Lycj9xU0LahyGE6mKAnTNL1cD/ZT+kF0+A5peOB6/d3dD1CGgby+h3Ojuju4ytfwDkrMTLl0RoxlxdW9RbUF+BU3D30nbQvcuQE=
公钥解密:jianggujin
公钥加密:d8HT593xI2KnUeGGvQSRoSWmVXk9DdWHU3kMqSOONmj5Y0N8KZcA3Z7tz+MJX2Xgno9vCn5iXQXYEti5OkPfM53E/qf6MdFS6EhgiiNwhZu80ZtvVnjgfk0ZhxlFp9qYeY+HRwLjPyAG88yTZ3w31DbXW23TE0r6b4/piEy1/Gg=
私钥解密:jianggujin