RSA加密算法JAVA实现
时间: 2023-11-10 12:48:33 浏览: 71
RSA算法是一种非对称加密算法,可以用于数据的加密和数字签名等领域。下面是RSA算法的JAVA实现代码:
```java
import java.math.BigInteger;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
public class RSA {
private static final String ALGORITHM = "RSA";
private static final int KEY_SIZE = 2048;
public static void main(String[] args) throws Exception {
String originalText = "Hello, world!";
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
byte[] encryptedText = encrypt(publicKey, originalText.getBytes());
System.out.println("Encrypted Text: " + new BigInteger(1, encryptedText).toString(16));
byte[] decryptedText = decrypt(privateKey, encryptedText);
System.out.println("Decrypted Text: " + new String(decryptedText));
}
public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
keyPairGenerator.initialize(KEY_SIZE);
return keyPairGenerator.generateKeyPair();
}
public static byte[] encrypt(PublicKey publicKey, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(data);
}
public static byte[] decrypt(PrivateKey privateKey, byte[] encryptedData) throws Exception {
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(encryptedData);
}
}
```
这段代码中,我们首先生成了一个KeyPair对象,其中包含了公钥和私钥。然后使用公钥对原始数据进行加密,并使用私钥对加密后的数据进行解密。
需要注意的是,RSA算法的密钥长度越长,其安全性越高,但加密和解密的速度也会相应变慢,因此在实际应用中需要根据具体情况选择适当的密钥长度。
阅读全文