OWASP / Go-SCP

Golang Secure Coding Practices guide
https://owasp.org/www-project-go-secure-coding-practices-guide/
Creative Commons Attribution Share Alike 4.0 International
4.83k stars 369 forks source link

Somehow avoid passing nonce to decryption method #68

Closed bentcoder closed 3 years ago

bentcoder commented 4 years ago

Hi,

Thanks for this piece of work. The enc/dec example here requires the nonce to be known by both methods. Is there a way to avoid passing to dec method? Similar to this. See example below - same one from the doc but split into enc and dec methods.

Thanks

package main

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

func main() {
    msg := []byte("Hello World!")
    key := []byte("a6df723a921fccda52bdc4ca50851559")

    nonce := make([]byte, 12)
    if _, err := rand.Read(nonce); err != nil {
        panic(err.Error())
    }
    fmt.Println("NONCE:", hex.EncodeToString(nonce))

    enc := enc(msg, key, nonce)
    fmt.Println("ENC:", hex.EncodeToString(enc))

    dec := dec(enc, key, nonce)
    fmt.Println("DEC:", string(dec))
}

func enc(data, key, nonce []byte) []byte {
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }

    return aesgcm.Seal(nil, nonce, data, nil)
}

// Somehow this method should avoid requiring `nonce`.
func dec(enc, key, nonce []byte) []byte  {
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err.Error())
    }

    aesgcm, err := cipher.NewGCM(block)
    if err != nil {
        panic(err.Error())
    }

    decrypted_data, err := aesgcm.Open(nil, nonce, enc, nil)
    if err != nil {
        panic(err.Error())
    }

    return decrypted_data
}
bentcoder commented 3 years ago

Solution: http://www.inanzzz.com/index.php/post/f3pe/data-encryption-and-decryption-with-a-secret-key-in-golang

PauloASilva commented 3 years ago

Hi @BentCoder, The example you've shared is preferable, since there's a better SoC (Separation of Concerns) between encryption and decryption.

Would you like to open a Pull Request with a refactored source code sample? I would love to review and accept it!

Cheers, Paulo A. Silva

bentcoder commented 3 years ago

Hi @PauloASilva I will do and ping you once ready. Thanks

bentcoder commented 3 years ago

Closing this as the update/implementation has been merged here: https://github.com/OWASP/Go-SCP/pull/78