用Java实现RSA密码算法,对输入的明文加密,对密文解密。源代码
时间: 2024-04-01 20:38:32 浏览: 29
以下是使用Java实现RSA加密解密的源代码:
```
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSAEncryptionDecryptionExample {
private static final String plainText = "Hello World!";
private static final String ALGORITHM = "RSA";
public static void main(String[] args) throws Exception {
// Generate public and private keys using RSA algorithm
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(2048);
KeyPair keyPair = keyGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
// Create Cipher instance and initialize it to encrypt using public key
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
// Encrypt the plaintext using the public key
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
System.out.println("Encrypted Text : " + new String(encryptedBytes));
// Initialize the Cipher instance to decrypt using the private key
cipher.init(Cipher.DECRYPT_MODE, privateKey);
// Decrypt the ciphertext using the private key
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
System.out.println("Decrypted Text : " + new String(decryptedBytes));
}
}
```
这个例子生成一个2048位的RSA密钥对,并对明文“Hello World!”进行加密和解密。加密和解密过程使用Java密码库中的Cipher类完成。