open-quantum-safe / liboqs-go

Go bindings for liboqs
https://openquantumsafe.org/
MIT License
69 stars 24 forks source link

The calling function cannot get the secretKey exported from the called function #11

Closed buyobuyo404 closed 2 years ago

buyobuyo404 commented 2 years ago

The calling function cannot get the private key exported from the called function. Bellow are my calling function (TestGenerateKeyPQC) and the called function(GenerateKeyPQC),and I want to get the secretKey through GenerateKeyPQC,however, when I execute TestGenerateKeyPQC,I can not gain the secretKey.

func TestGenerateKeyPQC(t *testing.T) {
    sigName := "Dilithium2"
    sk := GenerateKeyPQC(sigName)
    fmt.Println("sk2: ", sk)
}
func GenerateKeyPQC(sigName string) []byte {
    signer := oqs.Signature{}
    defer signer.Clean() // clean up even in case of panic

    if err := signer.Init(sigName, nil); err != nil {
        log.Fatal(err)
    }

    signer.GenerateKeyPair()
    sk := signer.ExportSecretKey()
    fmt.Println("sk: ", sk)
    return sk
}

here is the result, if anyone know what is wrong with the code, please tell me, i am really appreciate. Snipaste_2022-02-03_17-25-43

vsoftco commented 2 years ago

@buyobuyo404 This is intended behaviour.

In the line sk := signer.ExportSecretKey(), the secret key is not copied, but simply its reference is being copied (that is, sk points to the same memory address as the buffer where the secret key is being stored). You then return sk(which again, under the hood, is still a reference to the secret key buffer, and not a copy). However, at the exit of the function, the signer object is destroyed by the deferred signer.Clean(), which, by design, clears the hot memory, including the secret key buffer. So, at the end of the day, the secret key you're referring to has been all zeroed.

You need to make a copy of the secret key before returning. https://gosamples.dev/copy-slice/

On the other hand, are you sure you want to do this? Secret keys should not outlive their corresponding oqs.Signature objects.