brix / crypto-js

JavaScript library of crypto standards.
Other
15.77k stars 2.38k forks source link

go crypto/aes: invalid key size 28 #458

Open zsaw opened 1 year ago

zsaw commented 1 year ago

js:

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>
<script>
    var data = {
        email: "test@test.com",
        password: "test+test",
        time: new Date().getTime(),
    };
    var key = CryptoJS.enc.Utf8.parse('dwhuhuzihuidwawbnbjhvxbhbje1');

    data.sign = CryptoJS.AES.encrypt(JSON.stringify(data), key, {
        'iv': CryptoJS.enc.Utf8.parse(''),
        'mode': CryptoJS.mode.CBC,
        'padding': CryptoJS.pad.Pkcs7,
    }).toString();

    console.log(JSON.stringify(data));
</script>

output:

{"email":"test@test.com","password":"test+test","time":1687261972215,"sign":"Aj5TFroaJR3IO+KxzafBbtbnWx8ngiBLTBIUhKoGzeNhcuKBQRu/uaSLEqiMAx3xW39d6pAm10Sqer/0a2nuZ74iI9YLjwnLMM0t2Dg31zE="}

go:

package main

import (
    "crypto/aes"
    "crypto/cipher"
    "encoding/base64"
    "fmt"
    "log"
)

func main() {
    key := []byte("dwhuhuzihuidwawbnbjhvxbhbje1")
    iv := make([]byte, aes.BlockSize)

    text := "Aj5TFroaJR3IO+KxzafBbtbnWx8ngiBLTBIUhKoGzeNhcuKBQRu/uaSLEqiMAx3xW39d6pAm10Sqer/0a2nuZ74iI9YLjwnLMM0t2Dg31zE="
    decryptedData, err := DecryptAES(text, key, iv)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println("Decrypted:", decryptedData)
}

func DecryptAES(encryptedData string, key []byte, iv []byte) (string, error) {
    ciphertext, err := base64.StdEncoding.DecodeString(encryptedData)
    if err != nil {
        return "", err
    }

    block, err := aes.NewCipher(key)
    if err != nil {
        return "", err
    }

    plaintext := make([]byte, len(ciphertext))
    mode := cipher.NewCBCDecrypter(block, iv)
    mode.CryptBlocks(plaintext, ciphertext)

    unpadText := PKCS7Unpad(plaintext)

    return string(unpadText), nil
}

func PKCS7Unpad(data []byte) []byte {
    length := len(data)
    unpadding := int(data[length-1])
    return data[:length-unpadding]
}

output:

2023/06/20 19:53:52 crypto/aes: invalid key size 28

Why is there no limit to the key size of CryptoJS? How can I decrypt it in go?

zsaw commented 1 year ago

I don't understand why CryptoJS has no limit on key size?

Wiki Description of the ciphers AES is based on a design principle known as a substitution–permutation network, and is efficient in both software and hardware.[11] Unlike its predecessor DES, AES does not use a Feistel network. AES is a variant of Rijndael, with a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits. By contrast, Rijndael per se is specified with block and key sizes that may be any multiple of 32 bits, with a minimum of 128 and a maximum of 256 bits. Most AES calculations are done in a particular finite field.

itse4elhaam commented 2 months ago

Did you find any solution?