• RSA 工具类


    package com.box.common.core.rsa;

    import com.alibaba.fastjson.JSONObject;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    import lombok.extern.slf4j.Slf4j;
    import sun.misc.BASE64Decoder;

    import java.io.ByteArrayOutputStream;
    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.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;
    import java.util.HashMap;
    import java.util.Map;

    import javax.crypto.Cipher;


    /**
    * RSA签名验签类
    */
    @Slf4j
    public class RSASignatureUtil {

    /**
    * 加密算法RSA
    */
    public static final String KEY_ALGORITHM = "RSA";

    /**
    * 签名算法
    */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
    * 获取公钥的key
    */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
    * 获取私钥的key
    */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
    * RSA最大加密明文大小
    */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
    * RSA最大解密密文大小
    */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
    * <p>
    * 生成密钥对(公钥和私钥)
    * </p>
    *
    * @return
    * @throws Exception
    */
    public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
    }

    /**
    * <p>
    * 用私钥对信息生成数字签名
    * </p>
    *
    * @param data 已加密数据
    * @param privateKey 私钥(BASE64编码)
    * @return
    * @throws Exception
    */
    public static String sign(byte[] data, String privateKey) {
    try {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return Base64Utils.encode(signature.sign());
    }catch (Exception e){
    e.printStackTrace();
    }
    return "";
    }

    /**
    * <p>
    * 校验数字签名
    * </p>
    *
    * @param data 已加密数据
    * @param publicKey 公钥(BASE64编码)
    * @param sign 数字签名
    * @return
    * @throws Exception
    */
    public static boolean verify(byte[] data, String publicKey, String sign) {
    try {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PublicKey publicK = keyFactory.generatePublic(keySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initVerify(publicK);
    signature.update(data);
    return signature.verify(Base64Utils.decode(sign));
    } catch (Exception e) {
    log.error("验证签名错误",e);
    }
    return false;

    }

    /**
    * <P>
    * 私钥解密
    * </p>
    *
    * @param encryptedData 已加密数据
    * @param privateKey 私钥(BASE64编码)
    * @return
    * @throws Exception
    */
    public static String decryptByPrivateKey(String encryptedData, String privateKey)throws Exception{

    return new String(decryptByPrivateKey(Base64Utils.decode(encryptedData),privateKey));
    }
    private static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey)
    throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段解密
    while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
    } else {
    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
    }

    /**
    * <p>
    * 公钥解密
    * </p>
    *
    * @param encryptedData 已加密数据
    * @param publicKey 公钥(BASE64编码)
    * @return
    * @throws Exception
    */
    public static String decryptByPublicKey(String encryptedData, String publicKey) throws Exception{

    return new String(decryptByPublicKey(Base64Utils.decode(encryptedData),publicKey));
    }
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey)
    throws Exception {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段解密
    while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
    } else {
    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
    }

    /**
    * <p>
    * 公钥加密
    * </p>
    *
    * @param data 源数据
    * @param publicKey 公钥(BASE64编码)
    * @return
    * @throws Exception
    */

    public static String encryptByPublicKey(String data, String publicKey)throws Exception{
    return Base64Utils.encode(encryptByPublicKey(data.getBytes(),publicKey)).toString();
    }
    private static byte[] encryptByPublicKey(byte[] data, String publicKey)
    throws Exception {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    // 对数据加密
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, publicK);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段加密
    while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
    } else {
    cache = cipher.doFinal(data, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_ENCRYPT_BLOCK;
    }
    byte[] encryptedData = out.toByteArray();
    out.close();
    return encryptedData;
    }

    /**
    * <p>
    * 私钥加密
    * </p>
    *
    * @param data 源数据
    * @param privateKey 私钥(BASE64编码)
    * @return
    * @throws Exception
    */
    public static String encryptByPrivateKey(String data, String privateKey)
    throws Exception {
    return Base64Utils.encode(encryptByPrivateKey(data.getBytes(),privateKey)).toString();
    }
    private static byte[] encryptByPrivateKey(byte[] data, String privateKey)
    throws Exception {
    byte[] keyBytes = Base64Utils.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, privateK);
    int inputLen = data.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // 对数据分段加密
    while (inputLen - offSet > 0) {
    if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
    } else {
    cache = cipher.doFinal(data, offSet, inputLen - offSet);
    }
    out.write(cache, 0, cache.length);
    i++;
    offSet = i * MAX_ENCRYPT_BLOCK;
    }
    byte[] encryptedData = out.toByteArray();
    out.close();
    return encryptedData;
    }

    /**
    * <p>
    * 获取私钥
    * </p>
    *
    * @param keyMap 密钥对
    * @return
    * @throws Exception
    */
    public static String getPrivateKey(Map<String, Object> keyMap)
    throws Exception {
    Key key = (Key) keyMap.get(PRIVATE_KEY);
    return Base64Utils.encode(key.getEncoded());
    }

    /**
    * <p>
    * 获取公钥
    * </p>
    *
    * @param keyMap 密钥对
    * @return
    * @throws Exception
    */
    public static String getPublicKey(Map<String, Object> keyMap)
    throws Exception {
    Key key = (Key) keyMap.get(PUBLIC_KEY);
    return Base64Utils.encode(key.getEncoded());
    }

    public static void main(String[] args) {

    JSONObject param = new JSONObject();
    param.put("deviceId", "12312973");
    param.put("offsetPage", "1");
    param.put("pageSize", "10");
    param.put("merchant_no","123456");

    System.out.println(JSONObject.toJSONString(param, SerializerFeature.SortField.MapSortField));


    try {

    /*
    Map<String, Object> keyMap = RSASignatureUtil.genKeyPair();
    String publicKey = RSASignatureUtil.getPublicKey(keyMap);
    String privateKey = RSASignatureUtil.getPrivateKey(keyMap);
    System.err.println("公钥: " + publicKey);
    System.err.println("私钥: " + privateKey);


    System.err.println("公钥加密——私钥解密");
    String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";
    System.out.println(" 加密前文字: " + source);

    String encodedData = RSASignatureUtil.encryptByPublicKey(source, publicKey);
    System.out.println("加密后文字: " + encodedData);
    String decodedData = RSASignatureUtil.decryptByPrivateKey(encodedData, privateKey);
    System.out.println("解密后文字: " + decodedData);


    encodedData = RSASignatureUtil.encryptByPrivateKey(param.toJSONString(), privateKey);
    System.out.println("加密后:" + encodedData);
    decodedData = RSASignatureUtil.decryptByPublicKey(encodedData, publicKey);
    System.out.println("解密后:" + decodedData);
    */
    //公钥:
    String pu = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCseCw4mhuvsy1rdrf4NC2RdhFCiC/ngefjworjZnRTc83aD5bUH/H4ewYVvaTXT2/eIiN93+SL/UC9asLsRXxV9rG99TltWWtaVR3ATB7bYQkUw0O+7ogbP+nAbIPGiuWopOPoIlHuCdaJJ1argNd9Od88QQnM1gtdRFwP9YuXdQIDAQAB";

    // 私钥:
    String pr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKx4LDiaG6+zLWt2t/g0LZF2EUKIL+eB5+PCiuNmdFNzzdoPltQf8fh7BhW9pNdPb94iI33f5Iv9QL1qwuxFfFX2sb31OW1Za1pVHcBMHtthCRTDQ77uiBs/6cBsg8aK5aik4+giUe4J1oknVquA13053zxBCczWC11EXA/1i5d1AgMBAAECgYBCuPMSqrwPSxhFPNaLVVRTtAOVY650t9MIUBj/RIG4T1LSC7nkMr+fy6hc/NMq4PZ8T2S/q8B1T/Kd1RG36mHhFT+MbLdLowUL6kUmMrNpZ91V0TT/+3R5p4tlot8FVp23mwerxST+aOksbEZYU/HQ+x9wkp4wH8m1QIGNBB5IeQJBANdjIF1ivwzjQcpyjT+kNAWwiwYfY1d+SGzor6kSHZRhhUBLRboDSz2RxrPPr8aZfOh1CnN31koZVDkgCNxzptcCQQDM/WDTmHrH3rgKjAPbVKrrFGLmc2fNhG48ykmL4i3dGfSoCA6egBNR9RnLztPhuFkANdWd2AyUIDA9BmCAHEaTAkAnF8fNC1ovxaOwUgBPF8eVbMie8N2ACNyuX8FaR3506wpbdA4Qx/5FC4tsIXr+6ebg7jVaZdrQEi7WO3lAQgF7AkEAx9j6zi+o/DT5bmbk168q1vbQGOZIPAgxRRjeLP88QYOtjygTwJkSvONc2+LvlO8Z7eeONE3OrZbYEJan/B4U+wJBAISZapra3LMk0CnKHk5dRUyUanmKP+6RbH00Zmh9z15u5S6JGDGekwppySnqmeOQ1RfFr1a7sWH093kvjEOuVN8=";

    String aa ="";

    //System.out.println("aa:"+ RSASignatureUtil.decryptByPublicKey(aa, pr));
    String sign = RSASignatureUtil.sign(JSONObject.toJSONString(param, SerializerFeature.SortField.MapSortField).getBytes(), pr);
    System.err.println("签名:" + sign);
    boolean status = RSASignatureUtil.verify(JSONObject.toJSONString(param, SerializerFeature.SortField.MapSortField).getBytes(), pu, sign);
    System.err.println("签名验证结果:" + status);



    } catch (Exception e) {
    e.printStackTrace();
    }


    }
    }
    小蚊子大人
  • 相关阅读:
    Silverlight4 GDR3与Silverlight5 EAP1的变化
    使用微软WPF技术开发产品优势究竟在那里
    于娟——《活着就是王道》博客精华文摘
    Silverlight中开发和设计人员的合作
    ubuntu10.10编译内核步骤
    添加系统调用实验步骤
    SinaWeiboSdk c++test
    【转】windows7下硬盘安装linux,双系统共存
    cppunit在vs2008下使用的环境搭建(上)
    【转】RedHat Linux 5 安装 OpenOffice 3.2.0
  • 原文地址:https://www.cnblogs.com/ywsheng/p/14976088.html
Copyright © 2020-2023  润新知