您好,登錄后才能下訂單哦!
在Java中,靜態(tài)類是不能被實(shí)例化的類
以下是一個(gè)使用靜態(tài)類實(shí)現(xiàn)加密和解密的示例:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class CryptoUtil {
// 靜態(tài)內(nèi)部類,用于生成密鑰
private static class KeyGeneratorHolder {
private static final SecretKey SECRET_KEY = generateSecretKey();
}
// 生成AES密鑰
private static SecretKey generateSecretKey() {
try {
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
return keyGenerator.generateKey();
} catch (Exception e) {
throw new RuntimeException("Error generating secret key", e);
}
}
// 加密方法
public static String encrypt(String plainText, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
} catch (Exception e) {
throw new RuntimeException("Error encrypting text", e);
}
}
// 解密方法
public static String decrypt(String encryptedText, SecretKey secretKey) {
try {
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
return new String(decryptedBytes);
} catch (Exception e) {
throw new RuntimeException("Error decrypting text", e);
}
}
public static void main(String[] args) {
String plainText = "Hello, World!";
String encryptedText = encrypt(plainText, KeyGeneratorHolder.SECRET_KEY);
System.out.println("Encrypted text: " + encryptedText);
String decryptedText = decrypt(encryptedText, KeyGeneratorHolder.SECRET_KEY);
System.out.println("Decrypted text: " + decryptedText);
}
}
在這個(gè)示例中,我們創(chuàng)建了一個(gè)名為CryptoUtil
的靜態(tài)類,它包含兩個(gè)靜態(tài)方法encrypt
和decrypt
,分別用于加密和解密字符串。我們還創(chuàng)建了一個(gè)靜態(tài)內(nèi)部類KeyGeneratorHolder
,用于生成AES密鑰。這樣,我們可以確保密鑰只生成一次,而不是每次調(diào)用加密或解密方法時(shí)都生成。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。