1. 程式人生 > >RSA加密工具類(Java)

RSA加密工具類(Java)

乾貨

package com.hht.exchange.utils;

import javax.crypto.Cipher;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

public class RSAUtils {

     /**
      * 預設的2048位金鑰對,可處理245個位元組(81個漢字)的資料
      */
     public static
String PRIVATE_KEY = "MIIEv***XFu4="; public static String PUBLIC_KEY = "MIIB***DAQAB"; /** * 字符集 */ public static String CHARSET = "utf-8"; /** * 簽名演算法 */ public static final String SIGNATURE_INSTANCE = "SHA1WithRSA"; /** * 生成金鑰對 * @param keyLength * @return * @throws Exception */
public static KeyPair getKeyPair(int keyLength) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(keyLength); return keyPairGenerator.generateKeyPair(); } /** * 公鑰字串轉PublicKey例項 * @param publicKey * @return * @throws Exception */
public static PublicKey getPublicKey(String publicKey) throws Exception { byte[] publicKeyBytes = Base64.getDecoder().decode(publicKey.getBytes()); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(keySpec); } /** * 私鑰字串轉PrivateKey例項 * @param privateKey * @return * @throws Exception */ public static PrivateKey getPrivateKey(String privateKey) throws Exception { byte[] privateKeyBytes = Base64.getDecoder().decode(privateKey.getBytes()); PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePrivate(keySpec); } /** * 公鑰加密 * @param content * @param publicKey * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(content); } public static byte[] encryptByPublicKey(byte[] content) throws Exception { return encryptByPublicKey(content, getPublicKey(PUBLIC_KEY)); } public static String encryptByPublicKey(String content, String publicKey) throws Exception { return new String(Base64.getEncoder().encode(encryptByPublicKey(content.getBytes(CHARSET), getPublicKey(publicKey)))); } public static String encryptByPublicKey(String content) throws Exception { return new String(Base64.getEncoder().encode(encryptByPublicKey(content.getBytes(CHARSET)))); } /** * 私鑰解密 * @param content * @param privateKey * @return * @throws Exception */ public static byte[] decryptByPrivateKey(byte[] content, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(content); } public static byte[] decryptByPrivateKey(byte[] content) throws Exception { return decryptByPrivateKey(content, getPrivateKey(PRIVATE_KEY)); } public static String decryptByPrivateKey(String content, String privateKey) throws Exception { return new String(decryptByPrivateKey(Base64.getDecoder().decode(content), getPrivateKey(privateKey)), CHARSET); } public static String decryptByPrivateKey(String content) throws Exception { return new String(decryptByPrivateKey(Base64.getDecoder().decode(content)), CHARSET); } /** * 私鑰加密 * @param content * @param privateKey * @return * @throws Exception */ public static byte[] encryptByPrivateKey(byte[] content, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, privateKey); return cipher.doFinal(content); } public static byte[] encryptByPrivateKey(byte[] content) throws Exception { return encryptByPrivateKey(content, getPrivateKey(PRIVATE_KEY)); } public static String encryptByPrivateKey(String content, String privateKey) throws Exception { return new String(encryptByPrivateKey(content.getBytes(CHARSET), getPrivateKey(privateKey)), CHARSET); } public static String encryptByPrivateKey(String content) throws Exception { return new String(encryptByPrivateKey(content.getBytes(CHARSET)), CHARSET); } /** * 公鑰解密 * @param content * @param publicKey * @return * @throws Exception */ public static byte[] decrypByPublicKey(byte[] content, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, publicKey); return cipher.doFinal(content); } public static byte[] decrypByPublicKey(byte[] content) throws Exception { return decrypByPublicKey(content, getPublicKey(PUBLIC_KEY)); } public static String decrypByPublicKey(String content, String publicKey) throws Exception { return new String(decrypByPublicKey(Base64.getDecoder().decode(content), getPublicKey(publicKey)), CHARSET); } public static String decrypByPublicKey(String content) throws Exception { return new String(decrypByPublicKey(Base64.getDecoder().decode(content)), CHARSET); } /** * 簽名 * @param content * @param privateKey * @return * @throws Exception */ public static byte[] sign(byte[] content, PrivateKey privateKey) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_INSTANCE); signature.initSign(privateKey); signature.update(content); return signature.sign(); } public static byte[] sign(byte[] content) throws Exception { return sign(content, getPrivateKey(PRIVATE_KEY)); } public static String sign(String content, String privateKey) throws Exception { return new String(Base64.getEncoder().encode(sign(content.getBytes(CHARSET), getPrivateKey(privateKey))), CHARSET); } public static String sign(String content) throws Exception { return new String(Base64.getEncoder().encode(sign(content.getBytes(CHARSET))), CHARSET); } /** * 驗籤 * @param content * @param sign * @param publicKey * @return * @throws Exception */ public static boolean verify(byte[] content, byte[] sign, PublicKey publicKey) throws Exception { Signature signature = Signature.getInstance(SIGNATURE_INSTANCE); signature.initVerify(publicKey); signature.update(content); return signature.verify(sign); } public static boolean verify(byte[] content, byte[] sign) throws Exception { return verify(content, sign, getPublicKey(PUBLIC_KEY)); } public static boolean verify(String content, String sign, String publicKey) throws Exception { return verify(content.getBytes(CHARSET), Base64.getDecoder().decode(sign), getPublicKey(publicKey)); } public static boolean verify(String content, String sign) throws Exception { return verify(content.getBytes(CHARSET), Base64.getDecoder().decode(sign), getPublicKey(PUBLIC_KEY)); } }

預設的金鑰對可以用這段程式碼計算:

    @Test
    public void testGetKeyPair() {
        try {
            KeyPair keyPair = RSAUtils.getKeyPair(1024);
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();
            System.out.println(new String(Base64.getEncoder().encode(publicKey.getEncoded())));
            // MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDffzKfmLgZWc1cp0kMwky0Yd4upchGbKRS5a9L2Imw1m0BVpE1Vcg0i9tnBCYzRmuToeq+m30SQhMK+FvICMMvRX9zMyvvf50jMIV78xB6UBWJd5EIFwwPP900I/sSWE3fT09BwVDNP1ILPAAN2ZfjbUkDrIFPra8WKjVc5bTlWwIDAQAB
            System.out.println(new String(Base64.getEncoder().encode(privateKey.getEncoded())));
            // MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAN9/Mp+YuBlZzVynSQzCTLRh3i6lyEZspFLlr0vYibDWbQFWkTVVyDSL22cEJjNGa5Oh6r6bfRJCEwr4W8gIwy9Ff3MzK+9/nSMwhXvzEHpQFYl3kQgXDA8/3TQj+xJYTd9PT0HBUM0/Ugs8AA3Zl+NtSQOsgU+trxYqNVzltOVbAgMBAAECgYEA2Jgz3lmp6N+P10BD2jqfDZ1fLoP5sM5u/eucU/vZjOhxoX9coHyu1sXHbnGl98FCVkPv9KNJtZ0VSWdhw11CkciVPJLaDXhLQYuaXjUZy9HxtRroGU3h+SYvNzBYmuvSKqEbUAxa2A+ca5VemKHs0mjyuUg7LNDC3cty+ejHR0kCQQD1oYNVRLPQrr1rEMCWI4+N7j1dnhZ7cwmjT9HqxKLQBO+gXmwYGS/sUHiS85Col0mP/GIUzRvCRzPulEAWXhctAkEA6O58fQ5I9oZuWmnvOk9e2dDBKWK5vBZ+F3hbsxjQLZYeJdiFXxLQFrWbJlhyb3vl3RnuuUP15VY+RquXQS9DpwJASN8w6nQmcKvWsFPY/vHv3einNgX3n4pCervsiBzsPJCqUsaQhRm72P0KuHYgHZQ8k8YJhyhOqvWa15YN6VTixQJBAJBBGhGsph0etfsCfihjfT9x3B6QSKymVWKdpFSvOkXxISyZAkgV848M21ANGJnYZkvewowz/XYRSjIkFGFHLyMCQQCMvrDZg0A9xkL7KIpbo2/i5OdYfbEyFtCwnIbqkUMEyZlAZy+Se3K79nsRA3917jS4W1JH0Ms8ponkHYzY3Fq3
        } catch (Exception e) {
            e.printStackTrace();
        }
    }