温馨提示×

java怎么对byte数组进行加密解密

小亿
91
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