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

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

Сообщение Anonymous »

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

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

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

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

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

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

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

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