溫馨提示×

java怎么對byte數組進行加密解密

小億
117
2024-06-03 16:29:19
欄目: 編程語言

在Java中,可以使用Cipher類來對byte數組進行加密和解密。下面是一個簡單的示例代碼,實現了對byte數組的加密和解密:

加密:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Base64;

public class Encryption {

    public static byte[] encrypt(byte[] input, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(input);
    }

    public static void main(String[] args) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        SecretKey secretKey = keyGenerator.generateKey();

        byte[] input = "Hello, World!".getBytes();
        byte[] encryptedBytes = encrypt(input, secretKey);

        String encryptedString = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted string: " + encryptedString);
    }
}

解密:

public static byte[] decrypt(byte[] input, Key key) throws Exception {
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, key);
    return cipher.doFinal(input);
}

public static void main(String[] args) throws Exception {
    KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    keyGenerator.init(128);
    SecretKey secretKey = keyGenerator.generateKey();

    byte[] input = "Hello, World!".getBytes();
    byte[] encryptedBytes = encrypt(input, secretKey);

    byte[] decryptedBytes = decrypt(encryptedBytes, secretKey);
    String decryptedString = new String(decryptedBytes);
    System.out.println("Decrypted string: " + decryptedString);
}

請注意,以上代碼中使用了AES加密算法和ECB工作模式進行加密和解密操作。在實際應用中,應根據需求選擇適當的加密算法和工作模式,并確保密鑰管理的安全性。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女