在Java中,常用的加密算法有對稱加密和非對稱加密。以下是一個簡單的示例代碼,展示如何使用對稱加密算法AES進行加密和解密:
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class EncryptionUtils {
private static final String SECRET_KEY = "mysecretkey12345";
public static String encrypt(String plainText) {
try {
SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String decrypt(String encryptedText) {
try {
SecretKeySpec key = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);
byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
return new String(decryptedBytes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String plainText = "Hello, world!";
String encryptedText = encrypt(plainText);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText);
System.out.println("Decrypted text: " + decryptedText);
}
}
在上面的示例中,我們定義了一個EncryptionUtils
類,其中包含了encrypt
和decrypt
方法來進行加密和解密操作。我們使用AES算法和一個固定的密鑰mysecretkey12345
來加密和解密文本數(shù)據(jù)。您可以替換為自己的密鑰來增強安全性。在main
方法中,我們對一個簡單的文本進行加密和解密,并輸出結(jié)果。
請注意,以上示例只是一個簡單的演示,實際應用中需要根據(jù)具體需求選擇更加安全和復雜的加密算法和實現(xiàn)。