如何解密golang中Node Js加密的文档?

问题描述 投票:0回答:1

使用相同的“加密”模块 aes-256-gcm ,base64 编码且 IV = 16!!
解密在 Nodejs 中使用 IV=16 和 setAuthTag 加密的文档 使用任意 32 或 64 个字符长的密钥并解密 golang 我使用 crypto/cipher 、 crypto/aes 来解密 Nodejs 中的加密文档。

node.js go encryption cryptography node-crypto
1个回答
0
投票
package main

import (
"crypto/aes"
"crypto/cipher"
"encoding/base64"
"encoding/hex"
"fmt"
"strings"

const (
ivBytes   = 16
algorithm = "aes-256-gcm"
secureKey = "<Your Secure Key>"

func main() {
doc := "<Your Encrypted String>"

decrypted, err := decrypt(doc)
if err != nil {
    fmt.Println("Decryption error:", err)
    return
}
fmt.Println("Encrypted text:", decrypted)

}

func decrypt(encrypted string) (string, error) {
// Split the encrypted string into ciphertext, IV, and authentication tag
data := strings.Split(encrypted, ".")
fmt.Println("Data[0]:", data[0])
fmt.Println("Data[1]:", data[1])
fmt.Println("Data[2]:", data[2])
if len(data) != 3 {
    return "", fmt.Errorf("invalid encrypted string format")
}

// Decode base64 strings
ciphertext, err := base64.StdEncoding.DecodeString(data[0])
if err != nil {
    return "", err
}
fmt.Println("CipherTextDecodeString:=", ciphertext)

iv, err := base64.StdEncoding.DecodeString(data[1])
if err != nil {
    return "", err
}
fmt.Println("Length IV=", len(iv))
fmt.Println("IV values=", iv)

authTag, err := base64.StdEncoding.DecodeString(data[2])
if err != nil {
    return "", err
}
fmt.Println("authTag values=", authTag)

//Use this to getAuthTag which is setAuthTag Method setting AuthTag in NodeJs
ciphertext = append(ciphertext, authTag...)

// Decode the secure key from hex
key, err := hex.DecodeString(secureKey)
if err != nil {
    return "", err
}
fmt.Println("key values=", key)

// Create the AES cipher block using the decoded key
block, err := aes.NewCipher(key)
if err != nil {
    return "", err
}
fmt.Println("block values=", key)

aesgcm, err := cipher.NewGCMWithNonceSize(block, ivBytes)//using this when you have IV=16 size or you can use cipher.NewGCM() when IV=12 size
if err != nil {
    return "", err
}
fmt.Println(aesgcm)

// Decrypt the ciphertext using the GCM mode
plaintext, err := aesgcm.Open(nil, iv, ciphertext, nil)
if err != nil {
    return "", fmt.Errorf("decryption failed: %v", err)
}

return string(plaintext), nil

}

© www.soinside.com 2019 - 2024. All rights reserved.