首页 > 编程语言 >java rsa加解密

java rsa加解密

时间:2023-12-18 16:58:03浏览次数:34  
标签:return String 加解密 rsa param static java byte throws

坑点:

  用其他语言的一定注意,Java秘钥和php秘钥不同,不用混用。

 

 

package cn.muyan.monitoragent.utils.encrypt;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.IOException;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/***
 * RSA加解密操作
 */
public class RSAUtils {
    
    // 加密算法
    private static String ALGORITHM = "RSA";
    // 加签算法
    private static String SIGN_ALGORITHM = "MD5withRSA";
    private static String CHARSET = "utf8";


    /***
     * 生成秘钥对
     * @return
     * @throws Exception
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        keyPairGenerator.initialize(2048);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        return keyPair;
    }

    /***
     * 获取公钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPublicKey(KeyPair keyPair) {
        PublicKey publicKey = keyPair.getPublic();
        byte[] bytes = publicKey.getEncoded();
        return byte2Base64(bytes);
    }

    /***
     * 获取私钥(Base64编码)
     * @param keyPair
     * @return
     */
    public static String getPrivateKey(KeyPair keyPair) {
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] bytes = privateKey.getEncoded();
        return byte2Base64(bytes);
    }

    /***
     * 将Base64编码后的公钥转换成PublicKey对象
     * @param pubStr
     * @return
     * @throws Exception
     */
    public static PublicKey string2PublicKey(String pubStr) throws Exception {
        byte[] keyBytes = base642Byte(pubStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }

    /***
     * 将Base64编码后的私钥转换成PrivateKey对象
     *
     * @param priStr
     * @return
     * @throws Exception
     */
    public static PrivateKey string2PrivateKey(String priStr) throws Exception {
        byte[] keyBytes = base642Byte(priStr);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    /***
     * 公钥加密
     * @param base64Key
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String publicEncrypt(String base64Key, PublicKey publicKey) throws Exception {
        byte[] content = base64Key.getBytes();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return byte2Base64(bytes);
    }

    /***
     * 公钥解密
     * @param base64Key
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String publicDecrypt(String base64Key, PublicKey publicKey) throws Exception {
        byte[] content = base642Byte(base64Key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] bytes = cipher.doFinal(content);
        return new String(bytes, CHARSET);
    }

    /***
     * 私钥解密
     * @param base64Key
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String privateDecrypt(String base64Key, PrivateKey privateKey) throws Exception {
        byte[] content = base642Byte(base64Key);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return new String(bytes, CHARSET);
    }

    /***
     * 私钥加密
     * @param base64Key
     * @param privateKey
     * @return
     * @throws Exception
     */
    public static String privateEncrypt(String base64Key, PrivateKey privateKey) throws Exception {
        byte[] content = base64Key.getBytes();
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] bytes = cipher.doFinal(content);
        return byte2Base64(bytes);
    }

    /**
     * 私钥签名
     *
     * @param data       待签名数据
     * @param privateKey 私钥
     * @return 签名
     */
    public static String sign(String data, PrivateKey privateKey) throws Exception {
        byte[] keyBytes = privateKey.getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PrivateKey key = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initSign(key);
        signature.update(data.getBytes());
        return byte2Base64(signature.sign());
    }

    /**
     * 公钥验签
     *
     * @param srcData   原始字符串
     * @param publicKey 公钥
     * @param sign      签名
     * @return 是否验签通过
     */
    public static boolean verify(String srcData, PublicKey publicKey, String sign) throws Exception {
        byte[] keyBytes = publicKey.getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGN_ALGORITHM);
        signature.initVerify(key);
        signature.update(srcData.getBytes());
        return signature.verify(base642Byte(sign));
    }

    /***
     * 字节数组转Base64编码
     *
     * @param bytes
     * @return
     */
    public static String byte2Base64(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(bytes);
    }

    /***
     * Base64编码转字节数组
     * @param base64Key
     * @return
     * @throws IOException
     */
    public static byte[] base642Byte(String base64Key) throws IOException {
        BASE64Decoder decoder = new BASE64Decoder();
        return decoder.decodeBuffer(base64Key);
    }

    public static void main(String[] args) {
        String publicKeyStr = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAkm6NbElYw8dJTjK9e7i+urYfBa5mj5PGkMvlfS3nrGROVfA4kenfVGbrKrTmbJBOaCHwrzpHWC16g4dRUKTyGwPMEGZp1wRfqbCXLQcy7Q8H1YlpC0eUxlg7a9GCMIAPDYil+ANmpcueGi0dHmd/4jNMPpVrjA/T/8vnb+QIeXf2GkWp/5F1zD6D6kstNJIpz9wfLenWHV29eMHO+FZa4fYSPWB04sn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7MVzEFJQl1ZNXWfk3OQx7dUj5+4EahipHBtuSyuzTdhW7dx4ooAEHsv9JWQpJJ439GzANDcAKdZC+AoTFePE0kilXSBgebjUEgDPbN8vipp6uqDuZX4lAyvmPYaQVMz0AoYQqYMLyFsFUCZhmcgjT1H+K4yWH203OwKBgQDSNG2h+bhtKJzmDuQ1bZ9Q6VhL45C8VZoMiGKCtwC3o3cP+4eYe5AaxNGujSfkntAlzNkpRqAhldejJDv2Atnm8noxPcWLg4tImVW46wzmxfF5Pxisih+vye9n+3Gs567uoiO2OagZJhmaAAJv+ROf3A2uql0vDoCKWTD56WGLXwKBgFmMX5VZ56qd1Dip++20aiYVbBiiG2av79PCFaNt+8aKH5Nu2xhB5VLrDHka7fm/0332JQaA386VSmFF+4Pxm+XkR2eaXs25qkMQgUujcvNq5dTLLSd184VNZkdLkq6+A5wJEz0GKzAqmXz8N1mmxUOFBBb+/NB3ZNO1ce39hoL7AoGAevZ5deD/yz/dguxd5tB58MUorFwqM/VLmxQAggXRvR8UusSNdrsa8Zjwzn/WyXJ7wWJ3rFdar6Ml3QMS6d31fxOd3QD01cssYFqL7HqsOcityfuIgsJZl7t7GvUt1YHpn3SuEkbDHvtoWlYwMhtnBeVQmy+RX261c8Rvbu6zXa4=";
        String byte2Base64 = "ggam2MkjuDZ75jOWGuD+WV5EA+VYVk5kFtlAUxfze2kZ0OlNEaK2c9CgovfTKyhRhKCGQRcFNY+ihvIfHP9wUjOvnM3jqDteIs8Thz1S3aTPGQT8zji8Ze2CObELPuZ9xPnbo+wL9cTIMkA4t9d7xMLfMnmV6irIXVOQ5anYCC+U8NLQtEsshqnzzyOMuRojqG+MBWEpe0X9LqFSIzdxVegtwZh9eJ1Zmw9VkvotBs1YnQqF/ivRiX2y6ZB8L7nZwCcS65GQq4ZARcVr5I3PN36p9dznjQguFKGxd3pftmupqoB7w51KzzYpZNfOzGYHM/sHDagUjYQWZL1fsBMnIg==";

        try {
//            KeyPair keyPair = getKeyPair();
//            String publicKeyStr = getPublicKey(keyPair);
//            String privateKeyStr = getPrivateKey(keyPair);
//            System.out.println("RSA公钥Base64编码:" + publicKeyStr);
//            System.out.println("RSA私钥Base64编码:" + privateKeyStr);
            String message = "123456";
//////            //将Base64编码后的公钥转换成PublicKey对象
            PublicKey publicKey = string2PublicKey(publicKeyStr);
            //用公钥加密
            String publicEncrypt = publicEncrypt(message, publicKey);
            //加密后的内容Base64编码
            //byte2Base64 = byte2Base64(publicEncrypt);
            System.out.println("公钥加密并Base64编码的结果:" + publicEncrypt);
            //将Base64编码后的私钥转换成PrivateKey对象
            PrivateKey privateKey = string2PrivateKey(privateKeyStr);

            //加密后的内容Base64解码
//            byte[] base642Byte = base642Byte(byte2Base64);


            //用私钥解密
            String privateDecrypt = privateDecrypt(publicEncrypt, privateKey);
            //解密后的明文
            System.out.println("解密后的明文: " + privateDecrypt);
            // 签名
//            String signStr = sign("11111111", privateKey);
//            System.out.println("签名: " + signStr);

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e);
        }

    }
}

 

标签:return,String,加解密,rsa,param,static,java,byte,throws
From: https://www.cnblogs.com/yangzailu/p/16865968.html

相关文章

  • jenkins发布Java项目
    1.java项目是什么(springboot)由java语言开发的后端,就是java项目前面于超老师教了大家学习了wordpress---php项目部署,提供LNMP,交给php-fpm进程去解释执行该源码jumpserver的core后端---python项目,提供python3环境,即可运行golang程序,需要安装golan编译器,编译二进制命令......
  • 无涯教程-Java - Vector 类函数
    Vector实现了动态数组。它类似于ArrayList,线程同步sychronized。以下是vector类提供的构造函数的列表。Sr.No.Constructor&Remark1Vector()此构造函数创建一个默认向量,其初始大小为10。2Vector(intsize)此构造函数接受等于所需大小的参数,并创建一个向量,其初始容......
  • 《Java编程思想第四版》学习笔记49--关于第十三章习题
    (9)增加Frog.class到本章出现的清单文件中并运行jar以创建一个包括Frog和BangBean的JAR文件。现在从SUN公司处下载并安装BDK或者使用我们自己的可激活Bean的程序构建工具并增加JAR文件到我们的环境中,因此我们可以测试两个Bean。(10)创建我们自己的包括两个属性......
  • Java里Integer怎么转成Long
    在Java中,你可以使用装箱(Boxing)和拆箱(Unboxing)的概念来进行Integer到Long的转换。具体方法如下:IntegerintValue=42;//你的整数值LonglongValue=intValue.longValue();这里的longValue()方法将Integer对象转换为对应的long型值,因为Long是整数的64位表示,而Integer是32位表示......
  • 《Effective Java》阅读笔记-第六章
    EffectiveJava阅读笔记第六章枚举和注解第34条用enum代替int常量int类型常量或者String类型常量作为参数的可读性和可维护性都比较差,甚至IDE都不好提示。Java中的枚举是完全单例,并且可以有字段、方法,以及实现接口(因为编译之后就是个类,并且自动继承了java.lang......
  • java常考面试题1-20
    Java程序员面试题集(1-70)一、Java基础部分1、面向对象的特征有哪些方面?答:面向对象的特征主要有以下几个方面:1)抽象:抽象是将一类对象的共同特征总结出来构造类的过程,包括数据抽象和行为抽象两方面。抽象只关注对象有哪些属性和行为,并不关注这些行为的细节是什么。2)继承:继承是......
  • Java 数组和ArrayList排序
    数组排序1.数组排序(从小到大排序)importjava.util.Arrays;publicclassTest01{publicstaticvoidmain(String[]args){//数组(从小到大排序)//1.第一种方法Integer[]arr1={21,11,41,31,51};Arrays.sort(arr1);Sy......
  • Java五种设计模式实现奶茶订单生成系统小DEMO
    前言这是大学时候上设计模式这门课写的程序,当时课程任务是要求结合五个设计模式写一个系统,最近偶然翻到,把系统分享一下。成品预览主界面​功能介绍订单管理系统,实现了对订单的增删改查。且实现了将订单内容写入文件,每次增删改查都会做保存,下次重启程序时......
  • JavaWeb - Day09 - Mybatis - 基础操作、XML映射文件、动态SQL
    01.Mybatis-基础操作-环境准备需求需求说明:根据资料中提供的《tlias智能学习辅助系统》页面原型及需求,完成员工管理的需求开发。通过分析以上的页面原型和需求,我们确定了功能列表:查询根据主键ID查询条件查询新增更新删除根据主键ID删除根据......
  • Java Spring Boot 集成 Swagger 生成 API文档(SpringDoc)
    在我们进行项目开发的时候,有些文档是必不可少的,或者也有利于自己查阅,比如API接口文档。在SpringBoot中通常有有个选择:springfoxspringdoc因为springfox和SpringBoot版本适配问题是个坑,这里我们选用更加友好的springDoc,而且用起来更顺手,很丝滑。以下是环境:Spring......