RSA签名和验签

本文介绍了两种RSA签名和验签的方法。第一种方法依赖于bcprov-jdk5on-1.53.jar库,提供了签名和验签的代码示例,并使用了Base64工具类。第二种方法详细说明了如何使用支持pkcs#1和pkcs8的签名类,提供了jar下载链接,以及调用测试的代码,特别指出加载私钥时关于pkcs标准的注意事项。
摘要由CSDN通过智能技术生成

=========================签名验签方法一=========================
首先,需要有bcprov-jdk5on-1.53.jar

然后代码如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Enumeration;

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

public class RSAUtil {
   

    public static final String SIGN_ALGORITHMS = "SHA1WithRSA";

    public static String sign(String content, String input_charset, Key key)
            throws UnsupportedEncodingException, Exception {
        Cipher cipher;
        try {
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] output = cipher.doFinal(content.getBytes(input_charset));
            return Base64.encode(output);
        } 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("明文数据已损坏");
        }
    }

    public static String readFile(String filePath, String charSet) throws Exception {
        FileInputStream fileInputStream = new FileInputStream(filePath);
        try {
            FileChannel fileChannel = fileInputStream.getChannel();
            ByteBuffer byteBuffer = ByteBuffer.allocate((int) fileChannel.size());
            fileChannel.read(byteBuffer);
            byteBuffer.flip();
            return new String(byteBuffer.array(), charSet);
        } finally {
            fileInputStream.close();
        }

    }

    public static String getKey(String string) throws Exception {
        String content = readFile(string, "UTF8");
        return content.replaceAll("\\-{5}[\\w\\s]+\\-{5}[\\r\\n|\\n]", "");
    }

    public static String signByPrivate(String content, PrivateKey privateKey,
                                       String input_charset) throws Exception {
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        java.security.Signature signature = java.security.Signature
                .getInstance(SIGN_ALGORITHMS);
        signature.initSign(privateKey);
        signature.update(content.getBytes(input_charset));
        return Base64.encode(signature.sign());
    }

    public static String signByPrivate(String content, String privateKey, String input_charset) throws Exception {
//      System.out.println("privateKey:"+privateKey);
        if (privateKey == null) {
            throw new Exception("加密私钥为空, 请设置");
        }
        PrivateKey privateKeyInfo = getPrivateKey(privateKey);
        return signByPrivate(content, privateKeyInfo, input_charset);
    }

    public static boolean verifyByKeyPath(String content, String sign, String publicKeyPath, String input_charset) {
//      System.out.println("publicKeyPath:"+publicKeyPath);
        try {
            return verify(content, sign, getKey(publicKeyPath), input_charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * RSA验签名检查
     * 
     * @param content
     *            待签名数据
     * @param sign
     *            签名值
     * @param publicKey
     *            支付宝公钥
     * @param input_charset
     *            编码格式
     * @return 布尔值
     */
    public static boolean verify(String content, String sign,
                                 String publicKey, String input_charset) {
        try {
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            byte[] encodedKey = Base64.decode(publicKey);
            PublicKey pubKey = keyFactory
                    .generatePublic(new X509EncodedKeySpec(encodedKey));
            return verify(content, sign, pubKey, input_charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    public static boolean verify(String content,String sign,PublicKey publicKey,String inputCharset){
        try {
            java.security.Signature signature = java.security.Signature
                    .getInstance(SIGN_ALGORITHMS);
            signature.initVerify(publicKey);
            signature.update(content.getBytes(inputCharset));
            boolean bverify = signature.verify(Base64.decode(sign));
            return bverify;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 得到私钥
     * 
     * @param key
     *            密钥字符串(经过base64编码)
     * @throws Exception
     */
    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = buildPKCS8Key(key);

        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);

        return privateKey;        
    }

    private static byte[] buildPKCS8Key(String privateKey) throws IOException {
        if (privateKey.contains("-----BEGIN PRIVATE KEY-----")) {
            return Base64.decode(privateKey.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
        } else if (privateKey.contains("-----BEGIN RSA PRIVATE KEY-----")) {
            final byte[] innerKey = Base64.decode(privateKey.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
            final byte[] result = 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
RSA数字签名的大致流程如下: 1. 首先需要生成RSA密钥对,包括公钥和私钥。 2. 对要签名的数据进行哈希处理。 3. 用私钥对哈希值进行加密,得到签名值。 4. 将签名值和原始数据一起发送给接收方。 5. 接收方用公钥对签名值进行解密,得到哈希值。 6. 对接收到的原始数据进行哈希处理,得到接收方计算出的哈希值。 7. 比较接收方计算出的哈希值和接收到的哈希值是否一致,如果一致,则表示签名验证成功。 下面是一个简单的RSA数字签名和验的C++代码示例: ```c++ #include <iostream> #include <openssl/rsa.h> #include <openssl/pem.h> #include <openssl/err.h> #include <openssl/md5.h> using namespace std; // 生成RSA密钥对 RSA* generateRSAKey() { RSA* rsa = RSA_new(); BIGNUM* bne = BN_new(); BN_set_word(bne, RSA_F4); RSA_generate_key_ex(rsa, 2048, bne, NULL); return rsa; } // RSA数字签名 bool rsaSign(const char* data, size_t dataLen, RSA* rsa, unsigned char* sig, unsigned int* sigLen) { unsigned char md[MD5_DIGEST_LENGTH]; MD5((unsigned char*)data, dataLen, md); int ret = RSA_sign(NID_md5, md, MD5_DIGEST_LENGTH, sig, sigLen, rsa); return (ret == 1); } // RSA bool rsaVerify(const char* data, size_t dataLen, RSA* rsa, unsigned char* sig, unsigned int sigLen) { unsigned char md[MD5_DIGEST_LENGTH]; MD5((unsigned char*)data, dataLen, md); int ret = RSA_verify(NID_md5, md, MD5_DIGEST_LENGTH, sig, sigLen, rsa); return (ret == 1); } int main() { // 生成RSA密钥对 RSA* rsa = generateRSAKey(); // 要签名的数据 char data[] = "Hello World!"; // RSA数字签名 unsigned char sig[1024]; unsigned int sigLen = 0; rsaSign(data, sizeof(data), rsa, sig, &sigLen); // RSA bool result = rsaVerify(data, sizeof(data), rsa, sig, sigLen); if (result) { cout << "RSA verify success!" << endl; } else { cout << "RSA verify failed!" << endl; } RSA_free(rsa); return 0; } ``` 需要注意的是,本示例使用了OpenSSL库来实现RSA签名和验,使用前需要先安装OpenSSL库并链接到项目中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值