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

	nonce := make([]byte, C.crypto_aead_chacha20poly1305_NPUBBYTES)
	_, err := rand.Read(nonce)
	if err != nil {
		return nil, errors.New(fmt.Sprintf("generate rand error : %v", err))
	}

	ciphertext := make([]byte, len(plaintext)+C.crypto_aead_chacha20poly1305_ABYTES)
	var clen C.ulonglong
	r, err := C.crypto_aead_chacha20poly1305_encrypt((*C.uchar)(&ciphertext[0]), &clen,
		(*C.uchar)(&plaintext[0]), (C.ulonglong)(len(plaintext)), nil, 0, nil, (*C.uchar)(&nonce[0]),
		(*C.uchar)(&key[0]))
	if err != nil {
		return nil, errors.New(fmt.Sprintf("call encrypt function error : %v", err))
	}

	if r == -1 {
		return nil, errors.New("encrypt data error")
	}

	ciphertextaddnonce := make([]byte, clen+C.crypto_aead_chacha20poly1305_NPUBBYTES)
	copy(ciphertextaddnonce, ciphertext[:clen])
	copy(ciphertextaddnonce[clen:], nonce)
	return ciphertextaddnonce, nil
}
Beispiel #2
0
func (ctx *natrAEAD) Seal(dst, nonce, plaintext, data []byte) []byte {
	out := make([]byte, len(plaintext)+_AEADOverheadBytes)
	rv := C.crypto_aead_chacha20poly1305_encrypt(g2cbt(out), nil,
		g2cbt(plaintext), C.ulonglong(len(plaintext)), g2cbt(data), C.ulonglong(len(data)),
		nil, g2cbt(nonce), g2cbt(ctx.key[:]))
	if rv != 0 {
		panic("crypto_secretbox_easy returned non-zero")
	}
	return append(dst, out...)
}
func Encrypt(message []byte, nonce uint64, key []byte) ([]byte, bool) {
	nonceBytes := make([]byte, 8)
	binary.LittleEndian.PutUint64(nonceBytes, nonce)
	encrypted := make([]byte, len(message)+AuthBytes)
	encryptedLengthLongLong := (C.ulonglong(len(encrypted)))
	ok := int(C.crypto_aead_chacha20poly1305_encrypt(
		(*C.uchar)(&encrypted[0]),
		&encryptedLengthLongLong,
		(*C.uchar)(&message[0]),
		(C.ulonglong)(len(message)),
		(*C.uchar)(nil),
		(C.ulonglong)(0),
		(*C.uchar)(nil),
		(*C.uchar)(&nonceBytes[0]),
		(*C.uchar)(&key[0]))) == 0
	//    PrintBytes( "nonce", nonceBytes )
	//    PrintBytes( "encrypted", encrypted )
	return encrypted, ok
}