在Java中,可以使用Java Cryptography Extension (JCE)来实现字符串的加密和解密。JCE提供了一套密码学框架,包括各种加密算法,如AES、DES、RSA等。以下是一个使用AES算法进行字符串加密和解密的示例:
首先,需要导入Java的安全包:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
然后,创建一个加密解密工具类:
public class AESUtil {
private static final String ALGORITHM = "AES";
private static final String KEY = "your-secret-key"; // 用于加密和解密的密钥
public static String encrypt(String data) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedData);
}
public static String decrypt(String encryptedData) throws Exception {
SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(StandardCharsets.UTF_8), ALGORITHM);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decodedData = Base64.getDecoder().decode(encryptedData);
byte[] decryptedData = cipher.doFinal(decodedData);
return new String(decryptedData, StandardCharsets.UTF_8);
}
}
现在,可以使用这个工具类来加密和解密字符串:
public class Main {
public static void main(String[] args) {
try {
String originalData = "Hello, World!";
System.out.println("Original data: " + originalData);
String encryptedData = AESUtil.encrypt(originalData);
System.out.println("Encrypted data: " + encryptedData);
String decryptedData = AESUtil.decrypt(encryptedData);
System.out.println("Decrypted data: " + decryptedData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意:在实际应用中,密钥(KEY)应该是一个足够复杂且不容易被猜测的字符串。此外,为了保证安全性,建议使用更安全的加密模式(如CBC)和填充方案(如PKCS5Padding)。本示例仅用于演示目的。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。