java rsa解密失败,Java RSA加密/解密

本文演示了Java中RSA加密和解密的过程,包括生成密钥对、保存和加载公钥与私钥,以及使用Cipher进行加解密操作。通过示例代码展示了如何将消息加密为Base64编码的字符串,然后使用公钥或私钥进行解密,恢复原始信息。
摘要由CSDN通过智能技术生成

Java RSA加密&解密如下:

import sun.misc.BASE64Decoder;

import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;

import java.io.IOException;

import java.nio.charset.Charset;

import java.security.*;

import java.security.interfaces.RSAPrivateKey;

import java.security.interfaces.RSAPublicKey;

import java.security.spec.InvalidKeySpecException;

import java.security.spec.PKCS8EncodedKeySpec;

import java.security.spec.X509EncodedKeySpec;

public class Sample {

public static final String RSA_ALGORITHM = "RSA";

public static final Charset UTF8 = Charset.forName("UTF-8");

public static void main(String [] args) throws Exception {

// generate public and private keys

KeyPair keyPair = buildKeyPair();

PublicKey publicKey = keyPair.getPublic();

PrivateKey privateKey = keyPair.getPrivate();

// encrypt the message

byte [] encrypted = encrypt(privateKey, "This is a secret message");

System.out.println(base64Encode(encrypted)); // <>

// decrypt the message

byte[] secret = decrypt(publicKey, encrypted);

System.out.println(new String(secret, UTF8)); // This is a secret message

}

public static KeyPair buildKeyPair() throws NoSuchAlgorithmException {

final int keySize = 2048;

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);

keyPairGenerator.initialize(keySize);

return keyPairGenerator.genKeyPair();

}

public static byte[] encrypt(PrivateKey privateKey, String message) throws Exception {

Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);

cipher.init(Cipher.ENCRYPT_MODE, privateKey);

return cipher.doFinal(message.getBytes(UTF8));

}

public

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值