Ошибка несоответствия тегов при использовании реализации Java AES для расшифровки файлов JSON, зашифрованных в реализациJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Ошибка несоответствия тегов при использовании реализации Java AES для расшифровки файлов JSON, зашифрованных в реализаци

Сообщение Anonymous »

Я получил файл JSON, зашифрованный с Golang AES/GCM/NOPADDING ,, и я внедрил AES/GCM/NOPADDING с помощью Java. Я могу зашифровать файл JSON и расшифровать его, а другая сторона (Golang) также может зашифровать файл JSON и расшифровать его. Мы используем один и тот же ключ и одинаковые параметры шифрования и дешифрования (IV длина, длина тега). < /P>
Но когда я использую код Java, чтобы расшифровать файлы JSON, зашифрованные Golang, я встречаю ошибку: «Mansatch Missate».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>
Crypto -код: < /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>
Crypto Code Golang: < /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>
и json data: < /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>
Я искал соответствующие проблемы в Stackoverflow, но без подобной ситуации. И я спросил ЧАТГПТ несколько раз, но это не решило проблему. Я не могу определить причину, кто -нибудь знает причину?

Подробнее здесь: https://stackoverflow.com/questions/796 ... files-encr
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»