RSA算法

299 阅读7分钟

package com.bestpay.bpbp.gateway.test; import lombok.extern.slf4j.Slf4j; import org.apache.commons.codec.binary.Base64; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.math.BigInteger; import java.security.; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException;

@Slf4j

public 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>
 * 每次加密的字节数,不能超过密钥的长度值减去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);
        // 传入编码数据并返回编码结果
        return cipher.doFinal(data);
    } 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);
        return cipher.doFinal(encryptedData);
    } catch (Exception e) {
        return null;
    }
}

/**
 * 通过公钥byte[](publicKey.getEncoded())将公钥还原,适用于RSA算法
 * @param keyBytes
 * @return
 * @throws NoSuchAlgorithmException

 */
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[](publicKey.getEncoded())将私钥还原,适用于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    N
 * @param publicExponent   e
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getPublicKey(String modulus, String publicExponent)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    BigInteger bigIntModulus = new BigInteger(modulus,16);
    BigInteger bigIntPrivateExponent = new BigInteger(publicExponent,16);
    RSAPublicKeySpec keySpec = new RSAPublicKeySpec(bigIntModulus, bigIntPrivateExponent);
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    PublicKey publicKey = keyFactory.generatePublic(keySpec);
    return publicKey;
}

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

/**
 * 从字符串中加载公钥
 * @param publicKeyStr 公钥数据字符串
 * @throws Exception 加载公钥时产生的异常
 */
public static RSAPublicKey loadPublicKey(String publicKeyStr) throws Exception {
    try {
        byte[] buffer = new Base64().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 RSAPrivateKey loadPrivateKey(String privateKeyStr) throws Exception {
    try {
        byte[] buffer = new Base64().decode(privateKeyStr);
        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 rsa私钥证书
 * @throws Exception
 */
public static RSAPrivateKey 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();
}


/**
 * 用私钥进行数字签名
 *签名 SHA1WithRSA
 * @param data 加密数据
 * @param key  私钥
 * @return 数字签名
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws Exception
 */
public static String sign(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // 构造PKCS8EncodedKeySpec对象
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
    // 指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    // 取私钥匙对象
    PrivateKey privKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    // RSA数字签名
    Signature signature = Signature.getInstance("SHA1WithRSA");
    // 初始化私钥
    signature.initSign(privKey);
    signature.update(data);
    // 获取数字签名
    String s = Base64.encodeBase64String(signature.sign());
    log.info(" 签名值:{}", s);
    return s;
}

/**
 * 校验数字签名
 *   验签SHA1WithRSA
 * @param data      加密数据
 * @param publicKey 公钥
 * @param sign      数字签名
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static boolean verify(byte[] data, byte[] publicKey, String sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {

    // 构造X509EncodedKeySpec对象
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
            publicKey);
    // 指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    // 取公钥匙对象
    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);
    Signature signature = Signature.getInstance("SHA1WithRSA");
    signature.initVerify(publicKey2);
    signature.update(data);
    // 验证签名是否正常
    return signature.verify(Base64.decodeBase64(sign));
}



/**
 * 用私钥进行数字签名
 *签名  SHA256WithRSA
 * @param data 加密数据
 * @param key  私钥
 * @return 数字签名
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 * @throws Exception
 */
public static String sign256(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // 构造PKCS8EncodedKeySpec对象
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(key);
    // 指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    // 取私钥匙对象
    PrivateKey privKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    // RSA数字签名
    Signature signature = Signature.getInstance("SHA256withRSA");
    // 初始化私钥
    signature.initSign(privKey);
    signature.update(data);
    // 获取数字签名
    String s = Base64.encodeBase64String(signature.sign());
    log.info(" 签名值:{}", s);
    return s;
}
/**
 * 校验数字签名
 *   验签SHA256WithRSA
 * @param data      加密数据
 * @param publicKey 公钥
 * @param sign      数字签名
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws InvalidKeyException
 * @throws SignatureException
 */
public static boolean verify256(byte[] data, byte[] publicKey, String sign) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {

    // 构造X509EncodedKeySpec对象
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
            publicKey);
    // 指定加密算法
    KeyFactory keyFactory = KeyFactory.getInstance(RSA);
    // 取公钥匙对象
    PublicKey publicKey2 = keyFactory.generatePublic(x509EncodedKeySpec);
    Signature signature = Signature.getInstance("SHA256WithRSA");
    signature.initVerify(publicKey2);
    signature.update(data);
    // 验证签名是否正常
    return signature.verify(Base64.decodeBase64(sign));
}


/**
 * RSA NoPadding加密
 * @param data
 * @param publicKey
 */
private static byte [] encryptRsaNoPadding(byte[] data, PublicKey publicKey) {
    byte[]  enBytes = null;
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        enBytes = cipher.doFinal(data);
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }catch (InvalidKeyException e) {
        e.printStackTrace();
    }catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    }
    return enBytes;
}
/**
 * RSA NoPadding解密
 * @param data
 * @param privateKey
 * @return
 */
private static byte [] decryptRsaNoPadding(byte[] data, PrivateKey privateKey){
    byte[]  enBytes = null;
    try {
        Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        enBytes = cipher.doFinal(data);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (NoSuchPaddingException e) {
        e.printStackTrace();
    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }
    return enBytes;
}

private static final String HEX_CHARS = "0123456789ABCDEF";
/**
 * 测试根据  公钥模数N ,指数E生成公钥,---私钥模数N ,指数D生成私钥,
 * @param args
 */
public static void main(String[] args) {
    byte[] b = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};
    System.out.println("原始值:"+toHexString(b));
    KeyPair keyPair = generateRSAKeyPair();
    byte[] encryptByte = encryptRsaNoPadding(b, keyPair.getPublic());
    System.out.println("加密后值:"+toHexString(encryptByte));
    byte[] decryptByte = decryptRsaNoPadding(encryptByte, keyPair.getPrivate());
    System.out.println("解密后值:"+toHexString(decryptByte));
    /**
     * N E生成公钥
     */
    String N="00A5A9C9C011E80E904DA4650A3069B9966D6AD18008D54489010F47C46281F65D583EB74003F5740785395B0C2EEA0262C8A8CE574846B922EEF3C15D43A9F0A1B0D36237B5DAA6C058BD63D3D7865B7A0506667A813FFE90E57715EE946EE669DC3807E4570E9C009F87B491DDBDBCA4627AE4DB8294CD20F5CCF344C3C7ABBD";
    String E="00010001";

    /**
     * N D生成私钥
     */
    String N1="BBBC49996CB668B80A83E6BD5DC98937334315E46AD46C09DAEBDF7E57FFAA30FB9C7D130E87CA06BED60E07648F0109D117A97F0D406DCC5D1F5FE63315151F2A5221B054474E16166F64E76053FF8C5C7A8C950109E3F820ED0505D7A4C7B4F24FD57EC09F8052E35A84255EEEF693A51BDC1819C29ECF2D439AE48CA08657";
    String D1="4DC9F5872CAC22950BCA5ECC1D75FA34D4B959F3652EB2BB9CAA3AD79BB7F4B9CA302C053EF2960C187C12A10E9250C05412E5691F41109DEB022A96F498AA3B0A91D686CDE8CD9A3CADF5D3CAAB59BE5BDD05B08FF25A70E900A64515F08FFFAC9900B2DE4F50691E39883A444DAC661DB248865B8E49F37FFFB0FD6C0A003D";
    try {
        RSAPublicKey  pub = (RSAPublicKey)RSAUtils.getPublicKey(N,E);
        //System.out.println("pub----N:"+ toHexString(pub.getModulus().toByteArray()));
        //System.out.println("pub----E:"+toHexString(pub.getPublicExponent().toByteArray()));
        RSAPrivateKey pri = (RSAPrivateKey)RSAUtils.getPrivateKey(N1,D1);
        //System.out.println("pri----N1:"+toHexString(pri.getModulus().toByteArray()));
        //System.out.println("pri----D1:"+toHexString(pri.getPrivateExponent().toByteArray()));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }
}
/**
 * byte[]转16进制HEXString
 * @param b
 * @return
 */
public static String toHexString(byte[] b) {
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < b.length; i++) {
        sb.append(RSAUtils.HEX_CHARS.charAt(b[i] >>> 4 & 0x0F));
        sb.append(RSAUtils.HEX_CHARS.charAt(b[i] & 0x0F));
    }
    return sb.toString();
}

}