RSA 非对称加解密 公私钥的生成

加密和签名使用不同的密钥对,签名密钥对的私钥用于签名,其对应的公钥用于验证签名。

加密密钥对的公钥用于加密,其对应的私钥用于解密。

1.生成密钥对

    /**
     *  生成RSA随机密钥对(公钥和私钥)
     * @return
     */
    public static Map<String, String> createKeyPair() throws Exception {
        Map<String,String> keyPairMap = new HashMap<>();
        // 密钥生成器,基于RSA算法
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥生成器,密钥大小为96-1024位
        keyPairGenerator.initialize(1024, SecureRandom.getInstance("SHA1PRNG"));
        // 生成一个密钥对,保存在KeyPair中
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        // 获取公钥及公钥字节数组
        PublicKey publicKey = keyPair.getPublic();
        byte[] publicKeyBytes = publicKey.getEncoded();
        // 获取私钥及私钥字节数组
        PrivateKey privateKey = keyPair.getPrivate();
        byte[] privateKeyBytes = privateKey.getEncoded();
        // 转换成16进制字符保存在map中
        keyPairMap.put(PUBLIC_KEY, byte2Hex(publicKeyBytes));
        keyPairMap.put(PRIVATE_KEY, byte2Hex(privateKeyBytes));
        return keyPairMap;
    }

2.RSA公钥加密

    /**
     *  RSA公钥加密。RSA加密算法对于加密数据长度是有要求的,一般来说,明文长度大小小于等于密钥长度(bytes)-11.
     *   解决这个问题要对较长的明文进行分段加解密(这里不做实现)
     * @param contents
     * @param publicKeyString
     * @return
     */
    public static String encryptWithPublicKey(String contents, String publicKeyString) throws Exception {
        // 判断入参非空
        // 获取公钥
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(hex2Byte(publicKeyString)));
        // RSA公钥加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptBytes = cipher.doFinal(contents.getBytes("UTF-8"));
        return byte2Hex(encryptBytes);
    }

3.RSA私钥解密

    /**
     * RSA私钥解密。同样这里不做分段实现
     * @param encryptContents
     * @param privateKeyString
     * @return
     */
    public static String decryptWithPrivateKey(String encryptContents, String privateKeyString) throws Exception {
        // 判断非空
        // 获取私钥
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(hex2Byte(privateKeyString)));
        // RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptBytes = cipher.doFinal(hex2Byte(encryptContents));
        return new String(decryptBytes, "UTF-8");
    }

4.RSA私钥加密(用于签名)

    /**
     *  RSA私钥加密(用于签名)
     * @param contents
     * @param privateKeyString
     * @return
     */
    public static String encryptWithPrivateKey(String contents, String privateKeyString) throws Exception {
        // 判断非空
        // 获取私钥
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(hex2Byte(privateKeyString)));
        // RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] encryptBytes = cipher.doFinal(contents.getBytes("UTF-8"));
        return byte2Hex(encryptBytes);
    }

5.RSA公钥解密(用于验签)

    /**
     *  RSA公钥解密,用于验证签名
     * @param encryptContents
     * @param publicKeyString
     * @return
     */
    public static String decryptWithPublicKey(String encryptContents, String publicKeyString) throws Exception {
        // 判断非空
        // 获取公钥
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(hex2Byte(publicKeyString)));
        // RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] decryptBytes = cipher.doFinal(hex2Byte(encryptContents));
        return new String(decryptBytes, "UTF-8");
    }

--------------------------------------

工具方法

    /**
     *  将byte[]数组转换成16进制字符。一个byte生成两个字符,长度对应1:2
     * @param bytes,输入byte[]数组
     * @return 16进制字符
     */
    public static String byte2Hex(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        StringBuilder builder = new StringBuilder();
        // 遍历byte[]数组,将每个byte数字转换成16进制字符,再拼接起来成字符串
        for (int i = 0; i < bytes.length; i++) {
            // 每个byte转换成16进制字符时,bytes[i] & 0xff如果高位是0,输出将会去掉,所以+0x100(在更高位加1),再截取后两位字符
            builder.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        return builder.toString();
    }

    /**
     *  将16进制字符转换成byte[]数组。与byte2Hex功能相反。
     * @param string 16进制字符串
     * @return byte[]数组
     */
    public static byte[] hex2Byte(String string) {
        if (string == null || string.length() < 1) {
            return null;
        }
        // 因为一个byte生成两个字符,长度对应1:2,所以byte[]数组长度是字符串长度一半
        byte[] bytes = new byte[string.length() / 2];
        // 遍历byte[]数组,遍历次数是字符串长度一半
        for (int i = 0; i < string.length() / 2; i++) {
            // 截取没两个字符的前一个,将其转为int数值
            int high = Integer.parseInt(string.substring(i * 2, i * 2 + 1), 16);
            // 截取没两个字符的后一个,将其转为int数值
            int low = Integer.parseInt(string.substring(i * 2 + 1, i * 2 + 2), 16);
            // 高位字符对应的int值*16+低位的int值,强转成byte数值即可
            // 如dd,高位13*16+低位13=221(强转成byte二进制11011101,对应十进制-35)
            bytes[i] = (byte) (high * 16 + low);
        }
        return bytes;
    }

原文地址:https://www.cnblogs.com/hello4world/p/12216112.html

时间: 2024-07-30 20:50:24

RSA 非对称加解密 公私钥的生成的相关文章

php rsa 非对称加解密类

<?php header("Content-Type: text/html;charset=utf-8"); /* 生成公钥.私钥对,私钥加密的内容能通过公钥解密(反过来亦可以) 下载开源RSA密钥生成工具openssl(通常Linux系统都自带该程序),解压缩至独立的文件夹,进入其中的bin目录,执行以下命令: openssl genrsa -out rsa_private_key.pem 1024 #生成原始 RSA私钥文件 rsa_private_key.pem opens

ios php RSA 非对称加密解密 der 和pem生成

ios 使用public_key.der加密 php 使用 private_key.pem解密 openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem phrase: countryName : CNStateName:ZhejiangCityName: organizationName: organizational Unit Name: CommonNam

网Js RSA加密,后端(Asp.Net)解码(非对称加解密)

前言 RSA加解密知识自行百度了解决一下 1.取得公钥与私钥方法 JSEncrypt Download 下载后将其发布成网站进入:http://127.0.0.1:3000/demo/index.html (各自服务器站口不一样自行) 这样就得到一公钥和私钥 另一种生成公钥与私钥的方法如下:引用 https://blog.csdn.net/qq_39081974/article/details/81059022 ======================================Begi

C#创建数字证书并导出为pfx,并使用pfx进行非对称加解密

本文源程序下载:http://download.csdn.net/source/2444494 我的项目当中,考虑到安全性,需要为每个客户端分发一个数字证书,同时使用数字证书中的公私钥来进行数据的加解密.为了完成这个安全模块,特写了如下一个DEMO程序,该DEMO程序包含的功能有: 1:调用.NET2.0的MAKECERT创建含有私钥的数字证书,并存储到个人证书区: 2:将该证书导出为pfx文件,并为其指定一个用来打开pfx文件的password: 3:读取pfx文件,导出pfx中公钥和私钥:

加解密算法二:非对称加解密

加密和解密使用不同的密钥的一类加密算法.这类加密算法通常有两个密钥A和B,使用密钥A加密数据得到的密文,只有密钥B可以进行解密操作(即使密钥A也无法解密):相反,使用密钥B加密数据得到的密文,只有密钥A可以解密.这两个密钥分别称为私钥和公钥.私钥就是你个人保留,不能公开的密钥,而公钥则是公开给加解密操作的另一方的.根据不同用途,对数据进行加密所使用的密钥也不相同(有时用公钥加密,私钥解密:有时相反用私钥加密,公钥解密).非对称加密的代表算法是RSA算法.   RSA算法是第一个既能用于数据加密也

(转)C#实现RSA非对称加密解密

转自:http://blog.csdn.net/u010678947/article/details/48652875 一.RSA简介 RSA公钥加密算法是1977年由Ron Rivest.Adi Shamirh和LenAdleman在(美国麻省理工学院)开发的.RSA取名来自开发他们三者的名字.RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的所有密码攻击,已被ISO推荐为公钥数据加密标准.RSA算法基于一个十分简单的数论事实:将两个大素数相乘十分容易,但那时想要对其乘积进行因式

RSA 分段加解密【解决“不正确的长度”的异常】

方法1: RSA 是常用的非对称加密算法.最近使用时却出现了“不正确的长度”的异常,研究发现是由于待加密的数据超长所致. .NET Framework 中提供的 RSA 算法规定: 待加密的字节数不能超过密钥的长度值除以 8 再减去 11(即:RSACryptoServiceProvider.KeySize / 8 - 11),而加密后得到密文的字节数,正好是密钥的长度值除以 8(即:RSACryptoServiceProvider.KeySize / 8). 所以,如果要加密较长的数据,则可以

openssl RSA非对称加密解密

需要先了解的openssl系列函数 openssl_pkey_get_private 从证书中解析获取私钥,以供使用.成功,返回真实的密钥资源标识符(Resource ID),否则返回false openssl_pkey_get_public 从证书中解析获取公钥,以供使用.成功,返回真实的密钥资源标识符(Resource ID),否则返回false openssl_private_encrypt($data, $encrypted, $privateKeyResourceID, OPENSSL

RSA非对称加密解密实例

String content = ""; for(int i=1;i<100;i++)content += i + ") Easy to say, hard to do.\n"; /*1.利用公钥加密至文件*/ {     /*1)根据公钥反向构造PublickKey对象,调用cipher的init方法时使用*/     String KEY_PUBLIC  = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAIv38xXk06A