java RSA加密解密工具类 RSAUtils

本文介绍了如何在Java中使用RSA算法进行加密和解密,包括生成密钥对、公钥加密、私钥解密的过程,以及Base64编码的运用。
摘要由CSDN通过智能技术生成
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

public class RSAUtils {
    private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
    public static void main(String[] args) throws Exception {

        String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANdkPW0Ca/7ejTPn" +
                "pjbBGt7nohzghph8XJ7j1esMIj8SxQIMIMDy+EJcxTkSDiXBCditRyMTq0KXaH9z" +
                "ZULT2flyCCMiZw84/BRAuAYekmj0C+/rQ4vhZVJTPxZNr1Sj+233DhJwm3mCm+Xf" +
                "HPe9EiMk5qjaFCd3hGqCRQIjSgYdAgMBAAECgYB0Mkx88VCHd1IfjTl60mQHmlg3" +
                "UdzqiDSDNxAhNDOJaTvEpfxJewn46wkuh5IARgpkzN3Si3rZesrR7tPS4Gz3Cdgi" +
                "AeMDG0Kl3n+SgTGgkm/zY3SKNUiks+H/hSI8JbPzOcUhqIkfy5BWn6JMl27Qb3jM" +
                "KqzblgEF1KNYg5/PIQJBAPu1aBm655/lQMipWmFyWIHN75KdDh7z4KyG7O89rM5B" +
                "ZqezbToDz3Z2y3z7IBDC7BmTIn0gvEh+38NKfylJUBkCQQDbEFNuh36NIuVF7P5h" +
                "VQaEwq8OwhEaz7v7X85QemhiQZlwgAT9g7Lnvocl8mYaNxqdV+pZNQiHN8tsdexn" +
                "SValAkEAvc/N4eFVO/m4gdlb47JD1hcC+6/d7y9/lPrmf38l6h/dlscyrhYjg7UP" +
                "vH7vblRfkOWok211LsImYXGzNOIpOQJAPZ/GGJ29F+7tGFKm7LKCdu5dWIV3UleF" +
                "xh0ZaMJGgv15MJCS1s4pkc+jLSWXW2CM+B43KokksQUdEJHLwvJ6kQJABlCePQW8" +
                "wbidak4jrEruiXswR+OXOiLiOTSC9xhjnxGZlncHEiq7BSuqvBlrp86q6ntEWngI" +
                "9bm3IP7R93/fjQ==";
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDXZD1tAmv+3o0z56Y2wRre56Ic" +
                "4IaYfFye49XrDCI/EsUCDCDA8vhCXMU5Eg4lwQnYrUcjE6tCl2h/c2VC09n5cggj" +
                "ImcPOPwUQLgGHpJo9Avv60OL4WVSUz8WTa9Uo/tt9w4ScJt5gpvl3xz3vRIjJOao" +
                "2hQnd4RqgkUCI0oGHQIDAQAB";

        //测试
        String str = "123456";
        String a = encrypt(str,publicKey);
        System.out.println(a);
        String b = decrypt(a,privateKey);
        System.out.println(b);
    }



    /**
     * 随机生成密钥对
     * @throws NoSuchAlgorithmException
     */
    public static void genKeyPair() throws NoSuchAlgorithmException {
        // KeyPairGenerator类用于生成公钥和私钥对,基于RSA算法生成对象
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        // 初始化密钥对生成器,密钥大小为96-1024位
        keyPairGen.initialize(1024,new SecureRandom());
        // 生成一个密钥对,保存在keyPair中
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();   // 得到私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();  // 得到公钥
        String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
        // 得到私钥字符串
        String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
        // 将公钥和私钥保存到Map
        keyMap.put(0,publicKeyString);  //0表示公钥
        keyMap.put(1,privateKeyString);  //1表示私钥
    }
    /**
     * RSA公钥加密
     *
     * @param str
     *            加密字符串
     * @param publicKey
     *            公钥
     * @return 密文
     * @throws Exception
     *             加密过程中的异常信息
     */
    public static String encrypt( String str, String publicKey ) throws Exception{
        //base64编码的公钥
        byte[] decoded = Base64.decodeBase64(publicKey);
        RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
        //RSA加密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, pubKey);
        String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
        return outStr;
    }

    /**
     * RSA私钥解密
     *
     * @param str
     *            加密字符串
     * @param privateKey
     *            私钥
     * @return 铭文
     * @throws Exception
     *             解密过程中的异常信息
     */
    public static String decrypt(String str, String privateKey) throws Exception{
        //64位解码加密后的字符串
        byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
        //base64编码的私钥
        byte[] decoded = Base64.decodeBase64(privateKey);
        RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
        //RSA解密
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, priKey);
        String outStr = new String(cipher.doFinal(inputByte));
        return outStr;
    }


}

  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是一个简单的Java RSA加密工具类的代码示例: import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.SecureRandom; import javax.crypto.Cipher; public class RSAUtils { // 生成密钥对 public static KeyPair generateKeyPair() throws NoSuchAlgorithmException { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom secureRandom = new SecureRandom(); keyPairGenerator.initialize(2048, secureRandom); // 密钥长度为2048位 return keyPairGenerator.generateKeyPair(); } // 加密 public static byte[] encrypt(byte[] input, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(input); } // 解密 public static byte[] decrypt(byte[] input, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(input); } } 使用方法: // 生成密钥对 KeyPair keyPair = RSAUtils.generateKeyPair(); PublicKey publicKey = keyPair.getPublic(); PrivateKey privateKey = keyPair.getPrivate(); // 加密 byte[] data = "Hello, world!".getBytes(); byte[] encrypted = RSAUtils.encrypt(data, publicKey); // 解密 byte[] decrypted = RSAUtils.decrypt(encrypted, privateKey); String message = new String(decrypted); System.out.println(message); // 输出:Hello, world!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

浮生若梦01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值