如何用java RSA生成生成公钥私钥(非对称加密)

言简意赅,直接见代码:

在线加解密工具:https://hao.panziye.com/sites/331.html

package com;


import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


import javax.crypto.Cipher;


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


public class CreateSecretKey {
    public static final String KEY_ALGORITHM = "RSA";
    private static final String PUBLIC_KEY = "RSAPublicKey";
    private static final String PRIVATE_KEY = "RSAPrivateKey";
    public static final String SIGNATURE_ALGORITHM="MD5withRSA";
     /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    //获得公钥字符串
    public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
        //获得map中的公钥对象 转为key对象
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }


    //获得私钥字符串
    public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
        //获得map中的私钥对象 转为key对象
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        //编码返回字符串
        return encryptBASE64(key.getEncoded());
    }
    
    //获取公钥
    public static PublicKey getPublicKey(String key) throws Exception {  
        byte[] keyBytes;  
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);  
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
        PublicKey publicKey = keyFactory.generatePublic(keySpec);  
        return publicKey;  
    }  
    
    //获取私钥
    public static PrivateKey getPrivateKey(String key) throws Exception {  
        byte[] keyBytes;  
        keyBytes = (new BASE64Decoder()).decodeBuffer(key);  
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);  
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);  
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);  
        return privateKey;  
    }
    
    //解码返回byte
    public static byte[] decryptBASE64(String key) throws Exception {
        return (new BASE64Decoder()).decodeBuffer(key);
    }


    //编码返回字符串
    public static String encryptBASE64(byte[] key) throws Exception {
        return (new BASE64Encoder()).encodeBuffer(key);
    }
    
    //***************************签名和验证*******************************  
    public static byte[] sign(byte[] data,String privateKeyStr) throws Exception{  
      PrivateKey priK = getPrivateKey(privateKeyStr);  
      Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);       
      sig.initSign(priK);  
      sig.update(data);  
      return sig.sign();  
    }  
    
    public static boolean verify(byte[] data,byte[] sign,String publicKeyStr) throws Exception{  
      PublicKey pubK = getPublicKey(publicKeyStr);  
      Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);  
      sig.initVerify(pubK);  
      sig.update(data);  
      return sig.verify(sign);  
    }  
    
  //************************加密解密**************************  
    public static byte[] encrypt(byte[] plainText,String publicKeyStr)throws Exception{  
        PublicKey publicKey = getPublicKey(publicKeyStr);  
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
        int inputLen = plainText.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        int i = 0;
        byte[] cache;
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptText = out.toByteArray();
        out.close();  
        return encryptText;  
    }  
      
    public static byte[] decrypt(byte[] encryptText,String privateKeyStr)throws Exception{  
        PrivateKey privateKey = getPrivateKey(privateKeyStr);  
        Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, privateKey);  
        int inputLen = encryptText.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(encryptText, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] plainText = out.toByteArray();
        out.close();  
        return plainText;  
    }  


    public static void main(String[] args) {
        Map<String, Object> keyMap;
        byte[] cipherText;
        String input = "Hello World!";
        try {
            keyMap = initKey();
            String publicKey = getPublicKeyStr(keyMap);
            System.out.println("公钥------------------");
            System.out.println(publicKey);
            String privateKey = getPrivateKeyStr(keyMap);
            System.out.println("私钥------------------");
            System.out.println(privateKey);
            
            System.out.println("测试可行性-------------------");
            System.out.println("明文======="+input);
            
            cipherText = encrypt(input.getBytes(),publicKey); 
            //加密后的东西 
            System.out.println("密文======="+new String(cipherText));
            //开始解密 
            byte[] plainText = decrypt(cipherText,privateKey); 
            System.out.println("解密后明文===== " + new String(plainText));
            System.out.println("验证签名-----------");
            
            String str="被签名的内容";  
            System.out.println("\n原文:"+str);  
            byte[] signature=sign(str.getBytes(),privateKey);  
            boolean status=verify(str.getBytes(), signature,publicKey);  
            System.out.println("验证情况:"+status);  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

AES/DES等对称加密/解密 | 程序员导航网 

RSA是一种非对称加密算法,它使用公钥私钥来加密和解密数据。在Java生成RSA公钥私钥的步骤如下: 1. 导入相关的类库: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; ``` 2. 初始化密钥对生成器: ```java KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); ``` 其中,第一行代码创建了一个KeyPairGenerator对象,指定算法为RSA;第二行代码初始化了密钥对生成器,并指定密钥长度为2048位。 3. 生成密钥对: ```java KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); ``` 其中,第一行代码生成了密钥对;第二行代码获取了私钥;第三行代码获取了公钥。 完整代码示例如下: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; public class RSAGenerator { public static void main(String[] args) throws NoSuchAlgorithmException { // 初始化密钥对生成器 KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); // 生成密钥对 KeyPair keyPair = keyGen.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); // 输出公钥私钥 System.out.println("私钥:" + privateKey); System.out.println("公钥:" + publicKey); } } ```
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值