rsa加密算法java代码实现
时间: 2024-05-22 19:08:52 浏览: 12
RSA加密算法是一种非对称加密算法,它的安全性基于大数分解的困难性。在Java中,可以使用Java Cryptography Extension (JCE)库来实现RSA加密算法。
以下是使用JCE库实现RSA加密算法的Java代码示例:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import javax.crypto.Cipher;
public class RSAEncryptionExample {
public static void main(String[] args) throws Exception {
// Generate a key pair
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
SecureRandom secureRandom = new SecureRandom();
keyPairGenerator.initialize(2048, secureRandom);
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Encrypt the message using the public key
String message = "Hello, world!";
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedBytes = cipher.doFinal(message.getBytes());
// Decrypt the message using the private key
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
String decryptedMessage = new String(decryptedBytes);
// Print out the original message and the decrypted message
System.out.println("Original message: " + message);
System.out.println("Decrypted message: " + decryptedMessage);
}
}
```
在上面的示例中,我们首先使用KeyPairGenerator类生成一个公钥和私钥对,然后使用公钥加密消息,使用私钥解密消息。在实际使用中,我们可能需要将公钥保存在服务器端,将私钥保存在客户端,并通过网络传输加密后的消息。