mirror of
https://github.com/rwinkhart/rcw.git
synced 2026-09-06 09:07:16 -04:00
Initial encryption/decryption via ChaCha20-Poly1305
This commit is contained in:
@@ -0,0 +1,71 @@
|
||||
package wrappers
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"io"
|
||||
"log"
|
||||
|
||||
"golang.org/x/crypto/chacha20poly1305"
|
||||
)
|
||||
|
||||
const (
|
||||
nonceSizeCha = chacha20poly1305.NonceSizeX
|
||||
saltSizeCha = 16
|
||||
)
|
||||
|
||||
// EncryptCha encrypts data using ChaCha20-Poly1305
|
||||
func EncryptCha(data []byte, passphrase []byte) []byte {
|
||||
// generate a random salt
|
||||
salt := make([]byte, saltSizeCha)
|
||||
io.ReadFull(rand.Reader, salt)
|
||||
|
||||
// derive key from passphrase using the salt
|
||||
// TODO ensure the passphrase is consistent (store a hashed version to compare against)
|
||||
key := deriveKey(passphrase, salt)
|
||||
|
||||
// create ChaCha20-Poly1305 cipher
|
||||
aead, _ := chacha20poly1305.NewX(key)
|
||||
|
||||
// generate a random nonce
|
||||
nonce := make([]byte, nonceSizeCha)
|
||||
io.ReadFull(rand.Reader, nonce)
|
||||
|
||||
// encrypt the data
|
||||
ciphertext := aead.Seal(nil, nonce, data, nil)
|
||||
|
||||
// format: salt + nonce + ciphertext
|
||||
result := make([]byte, 0, saltSizeCha+nonceSizeCha+len(ciphertext))
|
||||
result = append(result, salt...)
|
||||
result = append(result, nonce...)
|
||||
result = append(result, ciphertext...)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// DecryptCha decrypts data using ChaCha20-Poly1305
|
||||
func DecryptCha(encryptedData []byte, passphrase []byte) []byte {
|
||||
if len(encryptedData) < saltSizeCha+nonceSizeCha {
|
||||
log.Fatalf("encrypted data is too short")
|
||||
return nil
|
||||
}
|
||||
|
||||
// extract salt, nonce, and ciphertext
|
||||
salt := encryptedData[:saltSizeCha]
|
||||
nonce := encryptedData[saltSizeCha : saltSizeCha+nonceSizeCha]
|
||||
ciphertext := encryptedData[saltSizeCha+nonceSizeCha:]
|
||||
|
||||
// derive key from passphrase using the salt
|
||||
key := deriveKey(passphrase, salt)
|
||||
|
||||
// create ChaCha20-Poly1305 cipher
|
||||
aead, _ := chacha20poly1305.NewX(key)
|
||||
|
||||
// decrypt the data
|
||||
plaintext, err := aead.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
log.Fatalf("decryption failed (possibly wrong passphrase): %w", err)
|
||||
return nil
|
||||
}
|
||||
|
||||
return plaintext
|
||||
}
|
||||
Reference in New Issue
Block a user