共計 1369 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 Java 中,可以使用 javax.crypto
包中的 Cipher
類來實現 AES 加密算法。以下是一個簡單的示例代碼來演示如何使用 AES 加密算法對字符串進行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class AESEncryption {public static SecretKey generateAESKey() throws Exception {KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();}
public static String encrypt(String data, SecretKey key) throws Exception {Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
public static String decrypt(String encryptedData, SecretKey key) throws Exception {Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
return new String(decryptedBytes);
}
public static void main(String[] args) throws Exception {SecretKey key = generateAESKey();
String data = "Hello, AES!";
String encryptedData = encrypt(data, key);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = decrypt(encryptedData, key);
System.out.println("Decrypted data: " + decryptedData);
}
}
在上面的示例中,我們首先使用 generateAESKey()
方法生成一個 AES 密鑰,然后使用 encrypt()
方法對字符串進行加密,最后使用 decrypt()
方法將加密后的字符串解密。最后,我們在 main()
方法中演示了整個加密和解密的過程。
丸趣 TV 網 – 提供最優質的資源集合!
正文完