Exemple #1
0
func DecryptData(key, ciphertextaddnonce []byte) ([]byte, error) {
	if len(key) != C.crypto_aead_chacha20poly1305_KEYBYTES {
		return nil, errors.New("key must be 32 bytes!")
	}

	clen := len(ciphertextaddnonce) - C.crypto_aead_chacha20poly1305_NPUBBYTES
	if clen-C.crypto_aead_chacha20poly1305_ABYTES <= 0 {
		return nil, errors.New("Illegal ciphertext")
	}
	nonce := ciphertextaddnonce[clen:]
	ciphertext := ciphertextaddnonce[:clen]
	plaintext := make([]byte, clen-C.crypto_aead_chacha20poly1305_ABYTES)
	var mlen C.ulonglong
	r, err := C.crypto_aead_chacha20poly1305_decrypt((*C.uchar)(&plaintext[0]), &mlen, nil,
		(*C.uchar)(&ciphertext[0]), (C.ulonglong)(clen), nil, 0, (*C.uchar)(&nonce[0]),
		(*C.uchar)(&key[0]))

	if err != nil {
		return nil, errors.New(fmt.Sprintf("call decrypt function error : %v", err))
	}

	if r != 0 {
		return nil, errors.New("decrypt data error")
	}
	return plaintext[:mlen], nil
}
Exemple #2
0
func (ctx *natrAEAD) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) {
	out := make([]byte, len(ciphertext)-_AEADOverheadBytes)
	rv := C.crypto_aead_chacha20poly1305_decrypt(g2cbt(out), nil, nil,
		g2cbt(ciphertext), C.ulonglong(len(ciphertext)), g2cbt(data), C.ulonglong(len(data)),
		g2cbt(nonce), g2cbt(ctx.key[:]))
	if rv != 0 {
		return nil, errors.New("MAC error")
	}
	return append(dst, out...), nil
}