Java与C++之RSA签名与验签及加解密操作

一、使用OpenSSL来生成私钥和公钥

1、执行命令openssl version -a 验证机器上已经安装openssl 

2、使用openssl命令生成公私钥

openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout
openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

所有RSA流程总规则:(私钥签名,公钥验签),(公钥加密,私钥解密)

二、java 实现过程

1、java签名/验证签名,加解密实现

    /**
     * 公钥
     */
    private static final String DEFAULT_PUBLIC_KEY="公钥\r";

    /**
     * 私钥
     */
    private static final String DEFAULT_PRIVATE_KEY="私钥\r";

    /**
     * 生成签名或密文
     */
    public String password(String data) {
        String pw = "";
        try {
            //System.out.println("---------------私钥签名过程------------------");
            //signstr = RSASignatureCommon.sign(data, DEFAULT_PRIVATE_KEY);
            //System.out.println("签名原串:" + data);
            //System.out.println("签名串:" + signstr);
            //System.out.println();

            //加密
            Base64 base64 = new Base64();
            RSAEncryptCommon rsaEncrypt= new RSAEncryptCommon();
            rsaEncrypt.loadPublicKey(DEFAULT_PUBLIC_KEY);//加载公钥
            byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), data.getBytes());
            pw = new String(base64.encode(cipher));
        } catch (Exception e) {
            System.err.println("错误:" + e.getMessage());
        }

        return pw;
    }

    /**
     * 解密或者验签
     */
    public String decryption(String password) {
        try {
            //RSA解密
            Base64 base64 = new Base64();
            RSAEncryptCommon rsaEncrypt= new RSAEncryptCommon();
            //加载私钥
            rsaEncrypt.loadPrivateKey(DEFAULT_PRIVATE_KEY);

            System.out.println("密文长度:"+ base64.decode(password).length);
            byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), base64.decode(password));
            password = new String(plainText, "UTF-8");
            System.out.println("明文:"+ password);

            //System.out.println("---------------公钥校验签名------------------");
            //System.out.println("验签结果:" + RSASignatureCommon.doCheck(password, signature, DEFAULT_PUBLIC_KEY));
            //!RSASignatureCommon.doCheck(password, signature, DEFAULT_PUBLIC_KEY) ||
            //System.out.println();

        } catch (Exception e) {
            System.err.println(e.getMessage());
        }

        return password;
    }

2、JAVA rsa签名和验签方法

注意:
    public static final String SIGN_ALGORITHMS = "MD5WithRSA"; //根据c++端算法选择对应算法

package com.gks.auth.common;

import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * RSA签名验签类
 */
public class RSASignatureCommon {

    /**
     * 签名算法
     * C++ EVP_md5 对应 MD5withRSA   实现Java语言MD5withRSA/SHA256withRSA/SHA384withRSA/SHA512withRSA
     */
    public static final String SIGN_ALGORITHMS = "MD5WithRSA"; //根据c++端算法选择对应算法

    /**
     * RSA签名
     * @param content 待签名数据
     * @param privateKey 商户私钥
     * @param encode 字符集编码
     * @return 签名值
     */
    public static String sign(String content, String privateKey, String encode) {
        try {
            Base64 base64 = new Base64();
            PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey));

            KeyFactory keyf = KeyFactory.getInstance("RSA");
            PrivateKey priKey = keyf.generatePrivate(priPKCS8);

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initSign(priKey);
            signature.update(content.getBytes(encode));

            byte[] signed = signature.sign();

            return new String(base64.encode(signed));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * RSA验签名检查
     * @param content 待签名数据
     * @param sign 签名值
     * @param publicKey 分配给开发商公钥
     * @param encode 字符集编码
     * @return 布尔值
     */
    public static boolean doCheck(String content, String sign, String publicKey, String encode) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            Base64 base64 = new Base64();
            byte[] encodedKey = base64.decode(publicKey);
            PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

            java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);

            signature.initVerify(pubKey);
            signature.update(content.getBytes(encode));

            boolean bverify = signature.verify(base64.decode(sign));
            return bverify;

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

        return false;
    }

}

3、JAVA rsa加解密代码

注意:cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());

根据C++端的加密算法调整对应的内容RSA/ECB/PKCS1Padding

package com.gks.auth.common;

import java.io.*;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import sun.misc.BASE64Decoder;

public class RSAEncryptCommon {

    /**
     * 私钥
     */
    private RSAPrivateKey privateKey;

    /**
     * 公钥
     */
    private RSAPublicKey publicKey;

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

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

    /**
     * 字节数据转字符串专用集合
     */
    private static final char[] HEX_CHAR= {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 获取私钥
     * @return 当前的私钥对象
     */
    public RSAPrivateKey getPrivateKey() {
        return privateKey;
    }

    /**
     * 获取公钥
     * @return 当前的公钥对象
     */
    public RSAPublicKey getPublicKey() {
        return publicKey;
    }

    /**
     * 随机生成密钥对
     */
    public void genKeyPair(){
        KeyPairGenerator keyPairGen= null;
        try {
            keyPairGen= KeyPairGenerator.getInstance("RSA");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        keyPairGen.initialize(1024, new SecureRandom());
        KeyPair keyPair= keyPairGen.generateKeyPair();
        this.privateKey= (RSAPrivateKey) keyPair.getPrivate();
        this.publicKey= (RSAPublicKey) keyPair.getPublic();
    }

    /**
     * 从文件中输入流中加载公钥
     * @param in 公钥输入流
     * @throws Exception 加载公钥时产生的异常
     */
    public void loadPublicKey(InputStream in) throws Exception{
        try {
            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');
                }
            }
            loadPublicKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("公钥数据流读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥输入流为空");
        }
    }

    /**
     * 从字符串中加载公钥
     * @param publicKeyStr 公钥数据字符串
     * @throws Exception 加载公钥时产生的异常
     */
    public void loadPublicKey(String publicKeyStr) throws Exception{
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(publicKeyStr);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            X509EncodedKeySpec keySpec= new X509EncodedKeySpec(buffer);
            this.publicKey= (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("公钥非法");
        } catch (IOException e) {
            throw new Exception("公钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("公钥数据为空");
        }
    }

    /**
     * 从文件中加载私钥
     * @param in 私钥文件名
     * @return 是否成功
     * @throws Exception
     */
    public void loadPrivateKey(InputStream in) throws Exception{
        try {
            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');
                }
            }
            loadPrivateKey(sb.toString());
        } catch (IOException e) {
            throw new Exception("私钥数据读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥输入流为空");
        }
    }

    /**
     * 从字符串中加载私钥
     * @param privateKeyStr 私钥数据字符串
     * @throws Exception 加载私钥时产生的异常
     */
    public void loadPrivateKey(String privateKeyStr) throws Exception{
        try {
            BASE64Decoder base64Decoder= new BASE64Decoder();
            byte[] buffer= base64Decoder.decodeBuffer(privateKeyStr);
            PKCS8EncodedKeySpec keySpec= new PKCS8EncodedKeySpec(buffer);
            KeyFactory keyFactory= KeyFactory.getInstance("RSA");
            this.privateKey= (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此算法");
        } catch (InvalidKeySpecException e) {
            throw new Exception("私钥非法");
        } catch (IOException e) {
            throw new Exception("私钥数据内容读取错误");
        } catch (NullPointerException e) {
            throw new Exception("私钥数据为空");
        }
    }

    /**
     * 加密过程
     * @param publicKey 公钥
     * @param plainTextData 明文数据
     * @return
     * @throws Exception 加密过程中的异常信息
     */
    public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception{
        if(publicKey== null){
            throw new Exception("加密公钥为空, 请设置");
        }
        Cipher cipher= null;
        try {
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            int inputLen = plainTextData.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(plainTextData, offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(plainTextData, offset, inputLen - offset);
                }
                out.write(cache, 0, cache.length);
                i++;
                offset = i * MAX_ENCRYPT_BLOCK;
            }
            byte[] encryptedData = out.toByteArray();
            out.close();

            return encryptedData;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此加密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("加密公钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("明文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("明文数据已损坏");
        }
    }

    /**
     * 解密过程
     * @param privateKey 私钥
     * @param cipherData 密文数据
     * @return 明文
     * @throws Exception 解密过程中的异常信息
     */
    public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception{
        if (privateKey== null){
            throw new Exception("解密私钥为空, 请设置");
        }
        Cipher cipher= null;
        try {
            cipher= Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);

            int inputLen = cipherData.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(cipherData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(cipherData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            byte[] decryptedData = out.toByteArray();
            out.close();

            return decryptedData;
        } catch (NoSuchAlgorithmException e) {
            throw new Exception("无此解密算法");
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
            return null;
        }catch (InvalidKeyException e) {
            throw new Exception("解密私钥非法,请检查");
        } catch (IllegalBlockSizeException e) {
            throw new Exception("密文长度非法");
        } catch (BadPaddingException e) {
            throw new Exception("密文数据已损坏");
        }
    }

}

三、  C++实现代码

1、C++实现代码部分

std::string common_tool::url_encode(const std::string& szToEncode)
{
    std::string src = szToEncode;
    char hex[] = "0123456789ABCDEF";
    std::string dst;
 
    for (size_t i = 0; i < src.size(); ++i)
    {
        unsigned char cc = src[i];
        if (isascii(cc))
        {
            if (cc == ' ')
            {
                dst += "%20";
            }
            else
                dst += cc;
        }
        else
        {
            unsigned char c = static_cast<unsigned char>(src[i]);
            dst += '%';
            dst += hex[c / 16];
            dst += hex[c % 16];
        }
    }
    return dst;
}
 
std::string common_tool::url_decode(const std::string &SRC) {
	std::string ret;
	char ch;
	int i, ii;
	for (i=0; i<SRC.length(); i++) {
			if (int(SRC[i])==37) {
					sscanf(SRC.substr(i+1,2).c_str(), "%x", &ii);
					ch=static_cast<char>(ii);
					ret+=ch;
					i=i+2;
			} else {
					ret+=SRC[i];
			}
	}
	return (ret);
}
bool common_tool::verify_rsa(/*const char *public_key*/RSA *rsa ,
                        const std::string &content, const std::string &sign) {
	BIO *bufio = NULL;
	EVP_PKEY *evpKey = NULL;
	bool verify = false;
	EVP_MD_CTX ctx;
	int result = 0;
	std::string decodedSign = common_tool::base64_decode(sign);
	char *chDecodedSign = const_cast<char*>(decodedSign.c_str());
 
	if (rsa == NULL) {
			printf("PEM_read_bio_RSA_PUBKEY failed");
			goto safe_exit;
	}
 
	evpKey = EVP_PKEY_new();
	if (evpKey == NULL) {
			printf("EVP_PKEY_new failed");
			goto safe_exit;
	}
 
	if ((result = EVP_PKEY_set1_RSA(evpKey, rsa)) != 1) {
			printf("EVP_PKEY_set1_RSA failed");
			goto safe_exit;
	}
 
	EVP_MD_CTX_init(&ctx);
 
	if (result == 1 && (result = EVP_VerifyInit_ex(&ctx,
									EVP_md5(), NULL)) != 1) {
			printf("EVP_VerifyInit_ex failed");
	}
 
	if (result == 1 && (result = EVP_VerifyUpdate(&ctx,
									content.c_str(), content.size())) != 1) {
			printf("EVP_VerifyUpdate failed");
	}
 
	if (result == 1 && (result = EVP_VerifyFinal(&ctx,
									(unsigned char*)chDecodedSign,
									decodedSign.size(), evpKey)) != 1) {
			printf("EVP_VerifyFinal failed");
	}
	if (result == 1) {
			verify = true;
	} else {
			printf("verify failed");
	}
 
	EVP_MD_CTX_cleanup(&ctx);
 
	safe_exit:
	if (rsa != NULL) {
			RSA_free(rsa);
			rsa = NULL;
	}
 
	if (evpKey != NULL) {
			EVP_PKEY_free(evpKey);
			evpKey = NULL;
	}
 
	if (bufio != NULL) {
			BIO_free_all(bufio);
			bufio = NULL;
	}
 
	return verify;
}

2、C++签名过程:

static std::string sign(const char *private_key, 
			const std::string &content) {
		BIO *bufio = NULL;
		RSA *rsa = NULL;
		EVP_PKEY *evpKey = NULL;
		bool verify = false;
		EVP_MD_CTX ctx;
		int result = 0;
		unsigned int size = 0;
		char *sign = NULL;
		std::string signStr = "";
 
		//bufio = BIO_new_mem_buf((void*)private_key, -1);
		//if (bufio == NULL) {
		//	ERR("BIO_new_mem_buf failed");
		//	goto safe_exit;
		//}
		bufio = BIO_new(BIO_s_file());
                BIO_read_filename(bufio, "rsa_private_key_pkcs8.pem");
                //BIO_read_filename(bufio, "rsa_private_key.pem");
 
		rsa = PEM_read_bio_RSAPrivateKey(bufio, NULL, NULL, NULL);
		if (rsa == NULL) {
			ERR("PEM_read_bio_RSAPrivateKey failed");
			goto safe_exit;
		}
 
		evpKey = EVP_PKEY_new();
		if (evpKey == NULL) {
			ERR("EVP_PKEY_new failed");
			goto safe_exit;
		}
 
		if ((result = EVP_PKEY_set1_RSA(evpKey, rsa)) != 1) {
			ERR("EVP_PKEY_set1_RSA failed");
			goto safe_exit;
		}
 
		EVP_MD_CTX_init(&ctx);
 
		if (result == 1 && (result = EVP_SignInit_ex(&ctx, 
						EVP_md5(), NULL)) != 1) {
			ERR("EVP_SignInit_ex failed");
		}
 
		if (result == 1 && (result = EVP_SignUpdate(&ctx, 
						content.c_str(), content.size())) != 1) {
			ERR("EVP_SignUpdate failed");
		}
 
		size = EVP_PKEY_size(evpKey);
		sign = (char*)malloc(size+1);
		memset(sign, 0, size+1);
		
		if (result == 1 && (result = EVP_SignFinal(&ctx, 
						(unsigned char*)sign,
						&size, evpKey)) != 1) {
			ERR("EVP_SignFinal failed");
		}
 
		if (result == 1) {
			verify = true;
		} else {
			ERR("verify failed");
		}
 
		signStr = common_tool::base64_encode((const unsigned char*)sign, size);
		EVP_MD_CTX_cleanup(&ctx);
		free(sign);
 
safe_exit:
		if (rsa != NULL) {
			RSA_free(rsa);
			rsa = NULL;
		}
 
		if (evpKey != NULL) {
			EVP_PKEY_free(evpKey);
			evpKey = NULL;
		}
 
		if (bufio != NULL) {
			BIO_free_all(bufio);
			bufio = NULL;
		}
 
		return signStr;
		//return sign;
	}

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值