Forked from kendru/golang-to-node-authenticated-encryption.js
Created
November 2, 2022 20:35
-
-
Save wobondar/645e1a20f822a67f810033ab79f65445 to your computer and use it in GitHub Desktop.
Decrypting AES-256-GCM encoded in Go from Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Usage: go run main.go | node decode.js | |
| /* | |
| // main.go: | |
| package main | |
| import ( | |
| "crypto/aes" | |
| "crypto/cipher" | |
| "crypto/rand" | |
| "encoding/base64" | |
| "fmt" | |
| "io" | |
| ) | |
| func main() { | |
| plaintext := "Quantum Magic" | |
| key, err := base64.StdEncoding.DecodeString("MVYLJBSMa8YakAmm66f9carJp80r9S7hMRyQIWgzCPI=") | |
| checkErr(err) | |
| aesCypher, err := aes.NewCipher(key) | |
| checkErr(err) | |
| gcm, err := cipher.NewGCM(aesCypher) | |
| checkErr(err) | |
| nonce := make([]byte, gcm.NonceSize()) | |
| _, err = io.ReadFull(rand.Reader, nonce) | |
| checkErr(err) | |
| encrypted := gcm.Seal(nonce, nonce, []byte(plaintext), nil) | |
| fmt.Print(base64.StdEncoding.EncodeToString(encrypted)) | |
| } | |
| func checkErr(err error) { | |
| if err != nil { | |
| panic(err) | |
| } | |
| } | |
| */ | |
| // decode.js | |
| const crypto = require('crypto') | |
| const key = Buffer.from('MVYLJBSMa8YakAmm66f9carJp80r9S7hMRyQIWgzCPI=', 'base64'); | |
| const ivLength = 12; | |
| const tagLength = 16; | |
| function decode(input) { | |
| const inputBuffer = Buffer.from(input, 'base64'); | |
| const iv = Buffer.allocUnsafe(ivLength); | |
| const tag = Buffer.allocUnsafe(tagLength); | |
| const data = Buffer.alloc(inputBuffer.length - ivLength - tagLength, 0); | |
| inputBuffer.copy(iv, 0, 0, ivLength); | |
| inputBuffer.copy(tag, 0, inputBuffer.length - tagLength); | |
| inputBuffer.copy(data, 0, ivLength); | |
| // console.log(iv.toString('hex')) | |
| // console.log(spaces(iv) + data.toString('hex')) | |
| // console.log(spaces(iv) + spaces(data) + tag.toString('hex')) | |
| // console.log(inputBuffer.toString('hex')) | |
| const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv) | |
| decipher.setAuthTag(tag); | |
| let dec = decipher.update(data, null, 'utf8'); | |
| dec += decipher.final('utf8'); | |
| return dec; | |
| } | |
| function spaces(b) { | |
| return b.toString('hex') | |
| .split('') | |
| .map(() => ' ') | |
| .join(''); | |
| } | |
| let input = ''; | |
| process.stdin.setEncoding('utf8'); | |
| process.stdin.on('readable', () => { | |
| const chunk = process.stdin.read(); | |
| if (chunk !== null) input += chunk; | |
| }); | |
| process.stdin.on('end', () => { | |
| const decoded = decode(input); | |
| console.log(`Input: ${input}`) | |
| console.log(`Decoded: ${decoded}`) | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment