Ich habe eine JSON -Datei erhalten, die mit Golang AES/GCM/Nopadding verschlüsselt wurde, und ich habe AES/GCM/Nopadding mit Java implementiert. Ich kann die JSON -Datei verschlüsseln und sie entschlüsseln, und die andere Seite (Golang) kann auch die JSON -Datei verschlüsseln und entschlüsseln. Wir verwenden den gleichen Schlüssel und die gleiche Verschlüsselungs- und Entschlüsselungsparameter (IV -Länge, Taglänge).import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Main {
public static void main(String[] args) {
try {
byte[] key = Files.readAllBytes(Paths.get("key.bin"));
if (key.length != 16 && key.length != 24 && key.length != 32) {
throw new IllegalArgumentException("Invalid key length: " + key.length + ", key length must be 16, 24, or 32 bytes");
}
Crypto crypto = new Crypto(key);
String inputFilePath = "input.json";
byte[] data = Files.readAllBytes(Paths.get(inputFilePath));
byte[] encrypted = crypto.encrypt(data);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
String timestamp = LocalDateTime.now().format(formatter);
String outputFileName = "encrypted_" + timestamp + ".json";
Files.write(Paths.get(outputFileName), encrypted);
System.out.println("Encryption result stored in " + outputFileName);
byte[] encryptedData = Files.readAllBytes(Paths.get(outputFileName));
byte[] decrypted = crypto.decrypt(encryptedData);
String decryptedOutputFilePath = "decrypted_output.json";
Files.write(Paths.get(decryptedOutputFilePath), decrypted);
System.out.println("Decryption result stored in " + decryptedOutputFilePath);
} catch (IOException e) {
System.err.println("File operation failed: " + e.getMessage());
} catch (Exception e) {
System.err.println("Encryption/Decryption failed: " + e.getMessage());
}
}
}
< /code>
Der Crypto -Code: < /p>
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;
public class Crypto {
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_LENGTH = 16;
private final SecretKey key;
public Crypto(byte[] keyBytes) {
this.key = new SecretKeySpec(keyBytes, "AES");
}
public byte[] encrypt(byte[] plaintext) throws Exception {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
byte[] iv = new byte[GCM_IV_LENGTH];
new SecureRandom().nextBytes(iv);
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.ENCRYPT_MODE, key, spec);
byte[] ciphertext = cipher.doFinal(plaintext);
byte[] result = new byte[GCM_IV_LENGTH + ciphertext.length];
System.arraycopy(iv, 0, result, 0, GCM_IV_LENGTH);
System.arraycopy(ciphertext, 0, result, GCM_IV_LENGTH, ciphertext.length);
return result;
}
public byte[] decrypt(byte[] encryptedData) throws Exception {
byte[] iv = new byte[GCM_IV_LENGTH];
System.arraycopy(encryptedData, 0, iv, 0, GCM_IV_LENGTH);
byte[] ciphertext = new byte[encryptedData.length - GCM_IV_LENGTH];
System.arraycopy(encryptedData, GCM_IV_LENGTH, ciphertext, 0, ciphertext.length);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(GCM_TAG_LENGTH * 8, iv);
cipher.init(Cipher.DECRYPT_MODE, key, spec);
return cipher.doFinal(ciphertext);
}
}
< /code>
Der Golang Crypto -Code: < /p>
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"fmt"
"io"
"log"
"gin-server/config"
)
type Encryptor interface {
Encrypt(data []byte) ([]byte, error)
Decrypt(data []byte) ([]byte, error)
}
type AESEncryptor struct {
key []byte
}
func NewAESEncryptorWithKey(key []byte) (*AESEncryptor, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Println("Creating AES encryptor with specified key")
}
keyLength := len(key) * 8
if keyLength != 128 && keyLength != 192 && keyLength != 256 {
return nil, fmt.Errorf("Unsupported AES key length: %d", keyLength)
}
if cfg.DebugLevel == "true" {
log.Println("AES encryptor created successfully")
}
return &AESEncryptor{key: key}, nil
}
func (e *AESEncryptor) GetKey() []byte {
return e.key
}
func (e *AESEncryptor) Encrypt(data []byte) ([]byte, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Starting AES encryption, data length: %d\n", len(data))
}
block, err := aes.NewCipher(e.key)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create AES cipher block: %v\n", err)
}
return nil, fmt.Errorf("Failed to create AES cipher block: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create GCM: %v\n", err)
}
return nil, fmt.Errorf("Failed to create GCM: %w", err)
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to generate nonce: %v\n", err)
}
return nil, fmt.Errorf("Failed to generate nonce: %w", err)
}
ciphertext := gcm.Seal(nonce, nonce, data, nil)
if cfg.DebugLevel == "true" {
log.Printf("AES encryption completed, encrypted data length: %d\n", len(ciphertext))
}
return ciphertext, nil
}
func (e *AESEncryptor) Decrypt(data []byte) ([]byte, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Starting AES decryption, data length: %d\n", len(data))
}
block, err := aes.NewCipher(e.key)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create AES cipher block: %v\n", err)
}
return nil, fmt.Errorf("Failed to create AES cipher block: %w", err)
}
gcm, err := cipher.NewGCM(block)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create GCM: %v\n", err)
}
return nil, fmt.Errorf("Failed to create GCM: %w", err)
}
if len(data) < gcm.NonceSize() {
if cfg.DebugLevel == "true" {
log.Println("Insufficient encrypted data length")
}
return nil, errors.New("Insufficient encrypted data length")
}
nonce := data[:gcm.NonceSize()]
ciphertext := data[gcm.NonceSize():]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to decrypt data: %v\n", err)
}
return nil, fmt.Errorf("Failed to decrypt data: %w", err)
}
if cfg.DebugLevel == "true" {
log.Printf("AES decryption completed, decrypted data length: %d\n", len(plaintext))
}
return plaintext, nil
}
< /code>
und JSON -Daten: < /p>
{
"time_range": {
"start_time": "2024-06-21T15:13:05+08:00",
"duration": 71203
},
"security_events": {
"events": []
},
"performance_events": {
"security_devices": [
{
"device_id": "000000000004",
"cpu_usage": 0,
"memory_usage": 0,
"duration": 89,
"login_status": "online",
"auth_status": "normal",
"gateway_devices": [
{
"device_id": "ID123",
"cpu_usage": 19,
"memory_usage": 34,
"duration": 50,
"login_status": "online",
"auth_status": "normal",
"users": [
{
"user_id": "000000001000",
"login_status": "online",
"auth_status": "forbidden",
"duration": 0,
"behaviors": []
},
{
"user_id": "000000001001",
"login_status": "offline",
"auth_status": "normal",
"duration": 0,
"behaviors": []
}
]
},
{
"device_id": "ID101",
"cpu_usage": 0,
"memory_usage": 0,
"duration": 0,
"login_status": "offline",
"auth_status": "normal",
"users": []
}
]
}
]
},
"error_events": {
"events": []
}
}
< /code>
Ich habe relevante Probleme im Stackoverflow, aber keine ähnliche Situation durchsucht. Und ich fragte Chatgpt mehrmals, aber es hat das Problem nicht gelöst. Ich kann die Ursache nicht bestimmen, jemand kennt den Grund?
Tag -Fehlpaarungsfehler Bei Verwendung von Java AES -Implementierung zum Entschlüsseln von JSON -Dateien, die von Golang ⇐ Java
-
- Similar Topics
- Replies
- Views
- Last post