美文网首页
RSA加密工具

RSA加密工具

作者: brightranger | 来源:发表于2020-01-16 15:55 被阅读0次
BASE64工具类
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * BASE64 工具类
 */
public class Base64Util {
  /**
   * 解密
   */
  public static byte[] decryptBASE64(String key) throws Exception {
      return (new BASE64Decoder()).decodeBuffer(key);
  }

  /**
   * BASE64加密
   */
  public static String encryptBASE64(byte[] key) throws Exception {
      return (new BASE64Encoder()).encodeBuffer(key);
  }
}
RSA密钥对生成工具
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Map;

public class KeyGenerator {
  private static final String key_algorithm = "RSA";
  private static Map<String, String> keyPairMap = new HashMap<>();

  /**
   * 生成密钥对
   *
   * @return 密钥对
   * @throws Exception
   */
  private static KeyPair generatePublicKey() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(key_algorithm);
    keyPairGen.initialize(1024);
    return keyPairGen.generateKeyPair();
  }

  private static void initKeyPair() throws Exception {
    KeyPair keyPair = generatePublicKey();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();
    keyPairMap.put("privateKey", Base64Util.encryptBASE64(privateKey.getEncoded()));
    keyPairMap.put("publicKey", Base64Util.encryptBASE64(publicKey.getEncoded()));
  }
  /**
   * 获取公钥
   *
   * @return 公钥
   * @throws Exception
   */
  public static String getPublicKey() throws Exception {
    if (keyPairMap.size() == 0) {
        initKeyPair();
    }
    return keyPairMap.get("publicKey");
  }

  /**
   * 获取私钥
   *
   * @return 私钥
   * @throws Exception
   */
  public static String getPrivateKey() throws Exception {
     if (keyPairMap.size() == 0) {
        initKeyPair();
    }
    return keyPairMap.get("privateKey");
  }
}
RSA加解密
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

public class RsaHelper {
    private static final String key_algorithm = "RSA";
    private static final String signature_algorithm = "MD5withRSA";
    
    
    /**
     * 使用私钥对信息 生成数字签名
     *
     * @param data        待加密数据
     * @param private_key 私钥
     * @return 数据签名
      * @throws Exception 异常
     */
    public static String sign(byte[] data, String private_key) throws Exception {
        //私钥base64
        byte[] keyBytes = Base64Util.decryptBASE64(private_key);
        //构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
        //指定加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        //获取私钥
        PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        //使用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(signature_algorithm);
        signature.initSign(privateKey);
        signature.update(data);
        //对数字签名做BASE64
        return Base64Util.encryptBASE64(signature.sign());
    }
    
    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
        throws Exception {
        // 解密由base64编码的公钥
        byte[] keyBytes = Base64Util.decryptBASE64(publicKey);
        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(signature_algorithm);
    signature.initVerify(pubKey);
        signature.update(data);
        // 验证签名是否正常
        return signature.verify(Base64Util.decryptBASE64(sign));
    }
    
    /**
     * 解密 用私钥解密
     *
     * @param data 加密数据
     * @param key  私钥
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] data, String key)
        throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64Util.decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
  
    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data 加密的数据
     * @param key  公钥
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
        throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64Util.decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }


    /**
     * 加密
     * 用公钥加密
     *
     * @param data 待加密数据
     * @param key  公钥
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String key) throws Exception {
        // 对公钥解密
        byte[] keyBytes = Base64Util.decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }
  
    /**
     * 加密
     * 用私钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
        throws Exception {
        // 对密钥解密
        byte[] keyBytes = Base64Util.decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(key_algorithm);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }

    /**
     * 加密
     *
     * @param plainText  明文
     * @param privateKey 私钥
     * @return 密文
     */
    public static String encodeStr(String plainText, String privateKey) throws Exception {
        byte[] cipherByte = RsaHelper.encryptByPrivateKey(plainText.getBytes(), privateKey);
        return Base64Util.encryptBASE64(cipherByte);
    }

    /**
     * 解密
     *
     * @param cipherText 密文
     * @param publicKey  公钥
     * @return 明文
     */
    public static String decodeStr(String cipherText, String publicKey) throws Exception {
        byte[] cipherByte = Base64Util.decryptBASE64(cipherText);
        byte[] plainByte = RsaHelper.decryptByPublicKey(cipherByte, publicKey);
        return new String(plainByte, StandardCharsets.UTF_8);
    }

    /**
     * 加密
     *
     * @param plainText  明文
     * @param privateKey 私钥
     * @return 密文
     */
    public static byte[] encodeByte(String plainText, String privateKey) throws Exception {
        return RsaHelper.encryptByPrivateKey(plainText.getBytes(StandardCharsets.UTF_8), privateKey);
    }


    /**
     * 解密
     *
     * @param cipherByte 密文
     * @param publicKey  公钥
     * @return 明文
     */
    public static String decodeByte(byte[] cipherByte, String publicKey) throws Exception {
        byte[] plainByte = RsaHelper.decryptByPublicKey(cipherByte, publicKey);
        return new String(plainByte, StandardCharsets.UTF_8);
    }
}
RSA测试类
import java.nio.charset.StandardCharsets;

public class RsaTest {

    public static void main(String[] args) throws Exception {
        //明文
        String plainText = "粗枝大叶sdosodf";

        //加密过程
        String privateKey = KeyGenerator.getPrivateKey();
        //密文
        byte[] cipherByte = RsaHelper.encryptByPrivateKey(plainText.getBytes(), privateKey);
        //生成数字签名
        String sign = RsaHelper.sign(cipherByte, privateKey);
        //BASE64 encode
        String cipherText = Base64Util.encryptBASE64(cipherByte);

        //解密过程
        String publicKey = KeyGenerator.getPublicKey();
        //BASE64 decode
        byte[] _cipherByte = Base64Util.decryptBASE64(cipherText);

        //验证数字签名
        boolean flag = RsaHelper.verify(_cipherByte, publicKey, sign);
        if (flag) {
            //解密
            byte[] plainByte = RsaHelper.decryptByPublicKey(_cipherByte, publicKey);
            System.out.println(new String(plainByte, StandardCharsets.UTF_8));
        } else {
            System.out.println("密文已经被破坏");
        }
    }
}

相关文章

网友评论

      本文标题:RSA加密工具

      本文链接:https://www.haomeiwen.com/subject/eaifzctx.html