举一个java应用程序添加加密算法的例子
时间: 2023-05-15 18:07:09 浏览: 52
一个常见的例子是在Java应用程序中使用AES加密算法来加密敏感数据。可以使用Java Cryptography Extension (JCE)提供的API来实现AES加密。以下是一个简单的示例代码:
```
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AESEncryptionExample {
private static final String ALGORITHM = "AES";
private static final String KEY = "mysecretkey12345";
public static byte[] encrypt(String data) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
return cipher.doFinal(data.getBytes());
}
public static String decrypt(byte[] encryptedData) throws Exception {
SecretKeySpec keySpec = new SecretKeySpec(KEY.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, keySpec);
byte[] decryptedData = cipher.doFinal(encryptedData);
return new String(decryptedData);
}
public static void main(String[] args) throws Exception {
String originalData = "Hello, world!";
byte[] encryptedData = encrypt(originalData);
String decryptedData = decrypt(encryptedData);
System.out.println("Original data: " + originalData);
System.out.println("Encrypted data: " + new String(encryptedData));
System.out.println("Decrypted data: " + decryptedData);
}
}
```
在上面的代码中,我们使用了一个固定的密钥字符串"mysecretkey12345"来初始化SecretKeySpec对象。在实际应用中,应该使用更安全的方式来生成密钥,例如使用KeyGenerator类来生成随机密钥。