Я получил файл 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>
и код Golang: < /p>
package fileutil
import (
"fmt"
"io"
"log"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"gin-server/config"
)
// FileInfo file information struct
type FileInfo struct {
Path string `json:"path"` // file path
Name string `json:"name"` // file name
Size int64 `json:"size"` // file size
ModTime time.Time `json:"mod_time"` // modification time
IsDir bool `json:"is_dir"` // is directory
Permissions string `json:"permissions"` // permission string
BackupPath string `json:"backup_path"` // backup path
LastBackupAt time.Time `json:"last_backup_at"` // last backup time
}
// normalizePath normalize path handling
func normalizePath(path string) string {
// Use forward slash as path separator
normalized := filepath.ToSlash(path)
// Handle Windows drive prefix
if runtime.GOOS == "windows" && len(normalized) >= 2 {
if normalized[1] == ':' {
normalized = "/" + strings.ToLower(string(normalized[0])) + normalized[2:]
}
}
return normalized
}
// denormalizePath convert back to system-specific path format
func denormalizePath(path string) string {
if runtime.GOOS == "windows" {
// Handle Windows drive prefix
if len(path) >= 3 && path[0] == '/' && path[2] == '/' {
path = string(path[1]) + ":" + path[2:]
}
return filepath.FromSlash(path)
}
return path
}
// EnsureDir ensure directory exists, create if not
func EnsureDir(path string) error {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Ensuring directory exists: %s\n", path)
}
// Convert to system-specific path format
sysPath := denormalizePath(path)
err := os.MkdirAll(sysPath, 0755)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create directory: %v\n", err)
}
return fmt.Errorf("failed to create directory: %w", err)
}
if cfg.DebugLevel == "true" {
log.Printf("Directory ready: %s\n", sysPath)
}
return nil
}
// CopyFile copy file
func CopyFile(src, dst string) error {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Copying file: %s -> %s\n", src, dst)
}
// Open source file
sourceFile, err := os.Open(src)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to open source file: %v\n", err)
}
return fmt.Errorf("failed to open source file: %w", err)
}
defer sourceFile.Close()
// Create destination file
destFile, err := os.Create(dst)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create destination file: %v\n", err)
}
return fmt.Errorf("failed to create destination file: %w", err)
}
defer destFile.Close()
// Copy file content
_, err = io.Copy(destFile, sourceFile)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to copy file content: %v\n", err)
}
return fmt.Errorf("failed to copy file content: %w", err)
}
// Get source file permissions
sourceInfo, err := os.Stat(src)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to get source file info: %v\n", err)
}
return fmt.Errorf("failed to get source file info: %w", err)
}
// Set destination file permissions
err = os.Chmod(dst, sourceInfo.Mode())
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to set destination file permissions: %v\n", err)
}
return fmt.Errorf("failed to set destination file permissions: %w", err)
}
if cfg.DebugLevel == "true" {
log.Printf("File copy completed: %s -> %s\n", src, dst)
}
return nil
}
// BackupFile backup file
func BackupFile(src string) (string, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Starting file backup: %s\n", src)
}
// Check if source file exists
if _, err := os.Stat(src); os.IsNotExist(err) {
if cfg.DebugLevel == "true" {
log.Printf("Source file does not exist: %s\n", src)
}
return "", fmt.Errorf("source file does not exist: %w", err)
}
// Create backup directory
backupDir := filepath.Join(filepath.Dir(src), "backup")
if err := EnsureDir(backupDir); err != nil {
return "", err
}
// Generate backup filename
timestamp := time.Now().Format("20060102150405")
ext := filepath.Ext(src)
baseName := filepath.Base(src[:len(src)-len(ext)])
backupPath := filepath.Join(backupDir, fmt.Sprintf("%s_%s%s", baseName, timestamp, ext))
// Copy file to backup location
if err := CopyFile(src, backupPath); err != nil {
return "", err
}
if cfg.DebugLevel == "true" {
log.Printf("File backup completed: %s -> %s\n", src, backupPath)
}
return backupPath, nil
}
// GetFileInfo get file information
func GetFileInfo(path string) (*FileInfo, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Getting file info: %s\n", path)
}
info, err := os.Stat(path)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to get file info: %v\n", err)
}
return nil, fmt.Errorf("failed to get file info: %w", err)
}
fileInfo := &FileInfo{
Path: path,
Name: info.Name(),
Size: info.Size(),
ModTime: info.ModTime(),
IsDir: info.IsDir(),
Permissions: info.Mode().String(),
}
if cfg.DebugLevel == "true" {
log.Printf("File info: %+v\n", fileInfo)
}
return fileInfo, nil
}
// IsFileExists check if file exists
func IsFileExists(path string) bool {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Checking if file exists: %s\n", path)
}
_, err := os.Stat(path)
exists := !os.IsNotExist(err)
if cfg.DebugLevel == "true" {
log.Printf("File %s exists: %v\n", path, exists)
}
return exists
}
// WriteFile write file
func WriteFile(filePath string, data []byte, perm os.FileMode) error {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Starting to write file: %s, data length: %d\n", filePath, len(data))
}
// Ensure directory exists
dir := filepath.Dir(filePath)
if cfg.DebugLevel == "true" {
log.Printf("Creating directory: %s\n", dir)
}
if err := os.MkdirAll(dir, 0755); err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to create directory: %v\n", err)
}
return fmt.Errorf("failed to create directory: %w", err)
}
// Write file
if err := os.WriteFile(filePath, data, perm); err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to write file: %v\n", err)
}
return fmt.Errorf("failed to write file: %w", err)
}
if cfg.DebugLevel == "true" {
log.Printf("File write completed: %s\n", filePath)
}
return nil
}
// ReadFile read file
func ReadFile(path string) ([]byte, error) {
cfg := config.GetConfig()
if cfg.DebugLevel == "true" {
log.Printf("Reading file: %s\n", path)
}
data, err := os.ReadFile(path)
if err != nil {
if cfg.DebugLevel == "true" {
log.Printf("Failed to read file: %v\n", err)
}
return nil, fmt.Errorf("failed to read file: %w", err)
}
if cfg.DebugLevel == "true" {
log.Printf("File read completed: %s, data length: %d\n", path, len(data))
}
return data, nil
}
< /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
Ошибка несоответствия тегов при использовании реализации Java AES для расшифровки файлов JSON, зашифрованных в реализаци ⇐ JAVA
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение