溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

靜態(tài)類在Java加密與解密操作中的實(shí)現(xiàn)

發(fā)布時(shí)間:2024-09-20 12:14:22 來(lái)源:億速云 閱讀:78 作者:小樊 欄目:編程語(yǔ)言

在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)方法encryptdecrypt,分別用于加密和解密字符串。我們還創(chuàng)建了一個(gè)靜態(tài)內(nèi)部類KeyGeneratorHolder,用于生成AES密鑰。這樣,我們可以確保密鑰只生成一次,而不是每次調(diào)用加密或解密方法時(shí)都生成。

向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI