Java实现分组对称密码加解密分组
时间: 2023-06-26 14:07:11 浏览: 51
Java中实现分组对称密码加解密可以使用Java内置的加密类库javax.crypto。下面是一个示例代码:
```java
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class SymmetricEncryption {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/ECB/PKCS5Padding";
public static void main(String[] args) throws Exception {
String plaintext = "Hello World!";
String key = "0123456789abcdef";
byte[] cipherText = encrypt(plaintext, key);
System.out.println("Encrypted Text: " + new String(cipherText));
String decryptedText = decrypt(cipherText, key);
System.out.println("Decrypted Text: " + decryptedText);
}
public static byte[] encrypt(String plaintext, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(plaintext.getBytes());
}
public static String decrypt(byte[] cipherText, String key) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
}
```
上述代码使用AES算法进行加解密,使用ECB模式和PKCS5Padding填充方案。在加密和解密时,需要指定密钥。