Java中加密算法的计算通常涉及以下几个步骤:
1. 选择加密算法:根据需求选择合适的加密算法,如AES、DES、RSA等。
4. 解密数据:使用相应的密钥对加密后的数据进行解密。
以下是一个使用AES加密算法的简单示例:
```java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionExample {
public static void main(String[] args) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128); // AES密钥长度为128位
SecretKey secretKey = keyGenerator.generateKey();
byte[] keyBytes = secretKey.getEncoded();
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");
// 2. 加密数据
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
String originalString = "Hello, World!";
byte[] originalBytes = originalString.getBytes();
byte[] encryptedBytes = cipher.doFinal(originalBytes);
// 3. 将加密后的字节数据转换为Base64字符串
String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Encrypted: " + encryptedString);
// 4. 解密数据
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
String decryptedString = new String(decryptedBytes);
System.out.println("Decrypted: " + decryptedString);