在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工作模式進行加密和解密操作。在實際應用中,應根據需求選擇適當的加密算法和工作模式,并確保密鑰管理的安全性。