diff --git a/cryptoaead/crypto_aead_aes256gcm.go b/cryptoaead/crypto_aead_aes256gcm.go index db2f1fe..5c66af4 100644 --- a/cryptoaead/crypto_aead_aes256gcm.go +++ b/cryptoaead/crypto_aead_aes256gcm.go @@ -124,7 +124,7 @@ func CryptoAEADAES256GCMDecryptDetached(c, mac, ad, npub, k []byte) ([]byte, int func CryptoAEADAES256GCMBeforeNM(k []byte) ([]byte, int) { support.CheckSize(k, CryptoAEADAES256GCMKeyBytes(), "secret key") - ctx := make([]byte, CryptoAEADAES256GCMStateBytes()) + ctx := support.AlignedSlice(CryptoAEADAES256GCMStateBytes(), 16) exit := int(C.crypto_aead_aes256gcm_beforenm( (*C.crypto_aead_aes256gcm_state)(unsafe.Pointer(&ctx[0])), diff --git a/cryptogenerichash/crypto_generichash.go b/cryptogenerichash/crypto_generichash.go index 8e084c0..1eb132e 100644 --- a/cryptogenerichash/crypto_generichash.go +++ b/cryptogenerichash/crypto_generichash.go @@ -4,7 +4,10 @@ package generichash // #include // #include import "C" -import "github.com/GoKillers/libsodium-go/support" +import ( + "github.com/GoKillers/libsodium-go/support" + "unsafe" +) func CryptoGenericHashBytesMin() int { return int(C.crypto_generichash_bytes_min()) @@ -68,9 +71,11 @@ func CryptoGenericHashInit(key []byte, outlen int) (*C.struct_crypto_generichash support.CheckSizeInRange(len(key), CryptoGenericHashKeyBytesMin(), CryptoGenericHashKeyBytesMax(), "key") } - state := new(C.struct_crypto_generichash_blake2b_state) + state := (*C.struct_crypto_generichash_blake2b_state)( + unsafe.Pointer(&support.AlignedSlice(CryptoGenericHashStateBytes(), 64)[0])) + exit := int(C.crypto_generichash_init( - (*C.struct_crypto_generichash_blake2b_state)(state), + state, (*C.uchar)(support.BytePointer(key)), (C.size_t)(len(key)), (C.size_t)(outlen))) diff --git a/support/support.go b/support/support.go index cbac049..d4623f2 100644 --- a/support/support.go +++ b/support/support.go @@ -1,6 +1,9 @@ package support -import "fmt" +import ( + "fmt" + "unsafe" +) // // Internal support functions @@ -32,3 +35,10 @@ func BytePointer(b []byte) *uint8 { return nil } } + +// AlignedSlice returns a memory aligned slice +func AlignedSlice(size, alignment int) []byte { + slice := make([]byte, size+alignment) + offset := alignment - int(uintptr(unsafe.Pointer(&slice[0])))%alignment + return slice[offset : offset+size] +}