Паническое возвращение на AES расшифровывают в Голанге - PullRequest
0 голосов
/ 28 июня 2018

Я реализовал шифрование AES в угловом приложении, которое отправляет зашифрованную строку в API REST, написанный на golang, который затем расшифровывает его, чтобы проверить, является ли его действительный ключ или нет.

Шифрование и дешифрование работает с приложением angular и golang отдельно, но API остальных возвращает панику, когда мы расшифровываем строку, отправленную из приложения angular

Ниже приведен мой код в приложении для шифрования в файле компонента

import * as CryptoJS from 'crypto-js';

var key = "NPZ8fvABP5pKwU3"; // passphrase used to encrypt 
let encrypted_text = CryptoJS.AES.encrypt('Hello World', 'NPZ8fvABP5pKwU3');

Когда я расшифровываю его с помощью следующего кода, он возвращает «Hello World» в угловом приложении

var bytes  = CryptoJS.AES.decrypt(encrypted_text.toString(), 'NPZ8fvABP5pKwU3');
var plaintext = bytes.toString(CryptoJS.enc.Utf8);
console.log(plaintext);

Не удается вернуть тот же текст в остальные API со следующим кодом в файле main.go

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/md5"
    "crypto/rand"
    "encoding/hex"
    "fmt"
    "io"
)

func decrypt(data []byte, passphrase string) []byte {
    key := []byte(createHash(passphrase))
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }
    nonceSize := gcm.NonceSize()
    nonce, ciphertext := data[:nonceSize], data[nonceSize:]
    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        panic(err.Error())
    }
    return plaintext
}

func main() {
    key2 := "NPZ8fvABP5pKwU3"
    key3 := []byte("encrypted string from angular app")

    plaintext := decrypt(key3, key2)
    fmt.Printf(string(plaintext))
}

func createHash(key string) string {
 hasher := md5.New()
 hasher.Write([]byte(key))
 return hex.EncodeToString(hasher.Sum(nil))
}

https://play.golang.org/p/iGYyg0RB-Zi

вернулась ошибка

panic: cipher: message authentication failed

1 Ответ

0 голосов
/ 28 июня 2018

Вам не нужно использовать функцию createHash, просто используйте ключ. Проблема в том, что ваш ключ имеет длину 15 байт, тогда как aes.NewCipher ожидает 16, 24 или 32 байта. Просто поменяйте ключ и используйте этот код:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "crypto/md5"

    "encoding/hex"
    "fmt"
)

func decrypt(data []byte, passphrase string) []byte {
    key := []byte(passphrase)
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }
    gcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }
    nonceSize := gcm.NonceSize()
    nonce, ciphertext := data[:nonceSize], data[nonceSize:]
    plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
    if err != nil {
        panic(err.Error())
    }
    return plaintext
}

func main() {
    key2 := "NPZ8fvABP5pKwU3"
    key3 := []byte("encrypted string from angular app")

    plaintext := decrypt(key3, key2)
    fmt.Printf(string(plaintext))
}
...