用java实现密码学的RS4
时间: 2023-09-30 14:06:02 浏览: 47
RSA(不是RS4)是一种非对称加密算法,Java中已经提供了RSA算法的实现。下面是一个简单的RSA加密和解密示例:
```java
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
public class RSAExample {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
String plainText = "Hello, world!";
byte[] encryptedText = RSAExample.encrypt(plainText);
System.out.println("Encrypted: " + new String(encryptedText));
String decryptedText = RSAExample.decrypt(encryptedText);
System.out.println("Decrypted: " + decryptedText);
}
public static byte[] encrypt(String plainText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
KeyPair keyPair = generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encrypted = cipher.doFinal(plainText.getBytes());
return encrypted;
}
public static String decrypt(byte[] encryptedText) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
KeyPair keyPair = generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] decrypted = cipher.doFinal(encryptedText);
return new String(decrypted);
}
private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(2048, new SecureRandom());
return keyPairGen.generateKeyPair();
}
}
```
在这个示例中,我们首先生成一个2048位的RSA公私钥对,然后使用公钥加密明文,使用私钥解密密文。需要注意的是,RSA加密算法只适用于加密短文本,因为加密数据的长度不能超过密钥的长度。如果要加密长文本,需要使用分块加密的方式。