首页 > 其他分享 >RSA签名验签

RSA签名验签

时间:2024-09-30 11:23:30浏览次数:7  
标签:String Base64 RSA static 签名 验签 import byte

maven引入

<dependency>
       <groupId>org.bouncycastle</groupId>
      <artifactId>bcpkix-jdk15on</artifactId>
       <version>1.68</version>
</dependency>
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk15on</artifactId>
    <version>1.68</version>
</dependency>

工具类

package com.inesa.common.utils;

import cn.hutool.json.JSONObject;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Arrays;
import java.util.Base64;
import java.util.Map;

import static java.nio.charset.StandardCharsets.UTF_8;

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

    private static final String SIGN_ALGORITHMS = "SHA256withRSA";
    private static final int MAX_ENCRYPT_BLOCK_SIZE = 117; // 对于2048位密钥
    private static final int MAX_DECRYPT_BLOCK_SIZE = 256; // 对于2048位密钥

    private static String sign(String content, String privateKey, Charset encode) throws Exception {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes(encode));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    //加签
    public static String sign(String content, String privateKey) throws Exception {
        return sign(content, privateKey, UTF_8);
    }

    private static boolean verify(String content, String sign, String publicKey, Charset encode) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.getDecoder().decode(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

        Signature signature = Signature.getInstance(SIGN_ALGORITHMS);
        signature.initVerify(pubKey);
        signature.update(content.getBytes(encode));
        return signature.verify(Base64.getDecoder().decode(sign));
    }


    //验签
    public static boolean verify(String content, String sign, String publicKey) throws Exception {
        return verify(content, sign, publicKey, UTF_8);
    }

    //加密
    public static String encrypt(String data, String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] encodedKey = Base64.getDecoder().decode(publicKey);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey));

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);

        // 处理大块数据加密
        byte[] plainBytes = data.getBytes(UTF_8);
        StringBuilder encryptedText = new StringBuilder();
        for (int i = 0; i < plainBytes.length; i += MAX_ENCRYPT_BLOCK_SIZE) {
            byte[] block = Arrays.copyOfRange(plainBytes, i, Math.min(i + MAX_ENCRYPT_BLOCK_SIZE, plainBytes.length));
            byte[] encryptedBlock = cipher.doFinal(block);
            encryptedText.append(Base64.getEncoder().encodeToString(encryptedBlock));
        }
        return encryptedText.toString();
    }


    //解密
    public static String decrypt(String data, String privateKey) throws Exception {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);

        Cipher decriptCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        decriptCipher.init(Cipher.DECRYPT_MODE, priKey);

        // 处理大块数据解密
        byte[] encryptedBytes = Base64.getDecoder().decode(data);
        StringBuilder decryptedText = new StringBuilder();
        for (int i = 0; i < encryptedBytes.length; i += MAX_DECRYPT_BLOCK_SIZE) {
            byte[] block = Arrays.copyOfRange(encryptedBytes, i, Math.min(i + MAX_DECRYPT_BLOCK_SIZE, encryptedBytes.length));
            byte[] decryptedBlock = decriptCipher.doFinal(block);
            decryptedText.append(new String(decryptedBlock, UTF_8));
        }
        return decryptedText.toString();
    }

    public static KeyPair generateRsaKeyPair() throws NoSuchAlgorithmException {
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); // 选择密钥长度
        return keyGen.generateKeyPair();
    }

    public static String getPublicKey( PublicKey publicKey)  {
        byte[] publicKeyBytes = publicKey.getEncoded();
        return Base64.getEncoder().encodeToString(publicKeyBytes);
    }

    public static String getPrivateKey(PrivateKey privateKey)  {
        byte[] privateKeyBytes = privateKey.getEncoded();
        return Base64.getEncoder().encodeToString(privateKeyBytes);
    }

    public static void main(String[] args) {
        try {
//            Security.addProvider(new BouncyCastleProvider());

            // 生成 RSA 密钥对
            KeyPair keyPair = generateRsaKeyPair();


            String publicKeyPem = getPublicKey(keyPair.getPublic());
            String privateKeyPem = getPrivateKey(keyPair.getPrivate());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", "1234");
            jsonObject.put("captchaExpiration", "5");
            String data = jsonObject.toString();
            String data1= encrypt(data, publicKeyPem);
            System.out.println("公钥加密结果:" +data1 );
            System.out.println("私钥解密结果:" + decrypt(data1, privateKeyPem));

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

标签:String,Base64,RSA,static,签名,验签,import,byte
From: https://blog.csdn.net/N0t_F0und_404/article/details/142650846

相关文章

  • [GAN][图片异常检测]Unsupervised Anomaly Detection withGenerative Adversarial Net
    论文背景与目标:    本文旨在将GAN运用到图片异常检测中,并取得了一定的效果,该模型不仅能够检测已知的异常,还能够发现未曾标注的新异常。提出了结合GAN的生成和判别功能的新型异常评分方法。在无监督的前提下实现了异常图像的分割。通过利用GAN的潜在空间,提出了新的......
  • The 2023 ICPC Asia Jinan Regional Contest (The 2nd Universal Cup. Stage 17: Jina
    赛时4题,策略重大失误,g题思路假了但是以为是代码问题硬调3.5h,m题本来是可以过的,e是网络流说不定也能过呢。xixike大力平衡树直接打过k题省去思考双优先队列算法的时间,太强A观察到同级同形状括号如果有四个就一定可以交换顺序,而且是充要的,经典括号匹配用栈存储就过了,我代码比较丑......
  • 【GAN】生成对抗网络Generative Adversarial Networks理解摘要
    【Pytorch】生成对抗网络实战_pytorch生成对抗网络-CSDN博客【损失函数】KL散度与交叉熵理解-CSDN博客  [1406.2661]GenerativeAdversarialNetworks(arxiv.org)GAN本质是对抗或者说竞争,通过生成器和鉴别器的竞争获取有效地结果,换句话说,GAN是在养蛊,大量数据和批次的......
  • 李宏毅机器学习2023-HW10-Adversarial Attack
    文章目录TaskBaselineFGSM(FastGradientSignMethod(FGSM)I-FGSM(IterativeFastGradientSignMethod)MI-FGSM(MomentumIterativeFastGradientSignMethod)M-DI2-FGSM(DiverseInputMomentumIterativeFastGradientSignMethod)ReportfgsmattackJepgCom......
  • 信息安全工程师(19)HASH函数与数字签名
    一、Hash函数1、定义    Hash函数,又称散列函数或哈希函数,是一种将任意长度的输入(称为预映射或消息)通过散列算法变换成固定长度输出(称为散列值或哈希值)的函数。这种转换是单向的,即不能从哈希值反向推导出原始输入。2、特性单向性:难以根据哈希值反向求出原始数据。......
  • 签名功能并且加水印
    找的插件,自己写要做一堆兼容麻烦死了使用的这个插件vue-signature-pad,看下载量很多npmi vue-signature-pad import{VueSignaturePad}from'vue-signature-pad';components:{VueSignaturePad,UseDetailDailog},<VueSignaturePad......
  • RSA算法模拟实验报告
    课程名称网络安全实验成绩实验RSA算法模拟学号姓名日期2024.9.24一、实验目的(1)学习RSA基本算法(2)学习指数求模运算(3)学习逆元的求法二、实验原理生成两个大素数 p和 q;计算这两个素数的乘积 n=p*q;计算小于n并且与n互质的整数的个数,即欧拉......
  • 遇到stdole.dll强签名无效?Windows用户必看:如何安全处理stdole.dll的强签名验证问题
    遇到stdole.dll强签名无效的问题时,Windows用户需要谨慎处理以确保系统的稳定性和安全性。以下是一些安全处理stdole.dll强签名验证问题的步骤和建议:一、了解stdole.dll首先,了解stdole.dll是一个关键的系统文件,它主要负责OLE(对象链接与嵌入)技术的一些基础功能。在Windows操作......
  • WPF Error XLS0108 Entity references or sequences beginning with an ampersand '&'
    //https://img1.baidu.com/it/u=3991277133,2041185316&fm=253 <ImageSource="https://img1.baidu.com/it/u=3991277133,2041185316&fm=253"/>SeverityCodeDescriptionProjectFileLineSuppressionStateDetailsErr......
  • 【解决了一个小问题】aws s3 sdk 中的自定义header设置哪些不参与aws v4 签名
    作者:张富春(ahfuzhang),转载时请注明作者和引用链接,谢谢!cnblogs博客zhihuGithub公众号:一本正经的瞎扯在通过代理访问s3服务端的时候,s3服务端返回类似的错误信息:<?xmlversion="1.0"encoding="UTF-8"standalone="yes"?><Error><Code>AuthorizationQueryParametersE......