JAVA实现RSA加密解密(支持中文)

1、import的包这里下载:http://commons.apache.org/proper/commons-codec/
2、源代码保存时文件编码选UTF-8。

import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

public class RSAEncrypt {
   
	private static Map<Integer, String> keyMap = new HashMap<Integer, String>();  //用于封装随机产生的公钥与私钥
	public static void main(String
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以通过使用Java Cryptography Architecture(JCA)提供的RSA类来实现RSA加密解密。首先,您需要生成一对RSA密钥,其中一个是公钥,另一个是私钥。然后,您可以使用公钥对数据进行加密,使用私钥对加密后的数据进行解密。 下面是一个简单的示例代码,展示了如何使用Java实现RSA加密解密: ```java import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import javax.crypto.Cipher; public class RSAExample { public static void main(String[] args) throws Exception { // 生成RSA密钥对 KeyPair keyPair = generateKeyPair(); // 待加密的明文 String plaintext = "Hello, RSA!"; // 使用公钥加密明文 byte[] encryptedData = encrypt(plaintext, keyPair.getPublic()); // 使用私钥解密密文 String decryptedText = decrypt(encryptedData, keyPair.getPrivate()); System.out.println("明文: " + plaintext); System.out.println("加密后的密文: " + new String(encryptedData)); System.out.println("解密后的明文: " + decryptedText); } // 生成RSA密钥对 public static KeyPair generateKeyPair() throws Exception { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC"); keyPairGenerator.initialize(2048); return keyPairGenerator.generateKeyPair(); } // 使用公钥加密 public static byte[] encrypt(String plaintext, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(plaintext.getBytes()); } // 使用私钥解密 public static String decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedData = cipher.doFinal(encryptedData); return new String(decryptedData); } } ``` 请注意,上述示例使用了Bouncy Castle加密库,您需要在项目中添加Bouncy Castle的相关依赖。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值