snippets

More or less useful code snippets
Log | Files | Refs

commit f1a7d841bcae96c96867a5f9f29aae96eb5d81de
parent 4648a03faa732e9e7e203de9a00726a0bcba27c2
Author: Vetle Haflan <vetle@haflan.dev>
Date:   Wed, 13 Apr 2022 16:21:23 +0200

Add old simcrypt.go (simple decrypt / encrypt)

Seems like I meant for this to be used in other Go projects, so the main
function is not implemented yet.

Diffstat:
Asimcrypt.go | 95+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 95 insertions(+), 0 deletions(-)

diff --git a/simcrypt.go b/simcrypt.go @@ -0,0 +1,95 @@ +package main + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/rand" + "crypto/sha256" + "filippo.io/age" + "io" +) + +func sha256Sum(password []byte) []byte { + pwSha := sha256.Sum256(password) + return pwSha[:] +} + +// Simple password-based encryption functions, +// AES-GCM (faster) and scrypt via `age` (more secure). + +// Symmetric encryption for extra private key protection +func encrypt(plaintext, encryptionKey []byte) ([]byte, error) { + keyHash := sha256Sum(encryptionKey) + block, err := aes.NewCipher(keyHash) + if err != nil { + return nil, err + } + aesgcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + nonce := make([]byte, aesgcm.NonceSize()) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } + ciphertext := aesgcm.Seal(nonce, nonce, []byte(plaintext), nil) + return ciphertext, nil +} + +func decrypt(cipherbundle, encryptionKey []byte) ([]byte, error) { + keyHash := sha256Sum(encryptionKey) + block, err := aes.NewCipher(keyHash) + if err != nil { + return nil, err + } + aesgcm, err := cipher.NewGCM(block) + if err != nil { + return nil, err + } + nonce := cipherbundle[:aesgcm.NonceSize()] + ciphertext := cipherbundle[aesgcm.NonceSize():] + return aesgcm.Open(nil, nonce, ciphertext, nil) +} + +func ageEncrypt(plain, encryptionKey []byte) ([]byte, error) { + if len(plain) == 0 { + return []byte{}, nil + } + sr, err := age.NewScryptRecipient(string(encryptionKey)) + if err != nil { + return nil, err + } + var b bytes.Buffer + ew, err := age.Encrypt(&b, sr) + if err != nil { + return nil, err + } + _, err = ew.Write(plain) + if err != nil { + return nil, err + } + err = ew.Close() + return b.Bytes(), err +} + +func ageDecrypt(cipher, encryptionKey []byte) ([]byte, error) { + if len(cipher) == 0 { + return []byte{}, nil + } + sr, err := age.NewScryptIdentity(string(encryptionKey)) + if err != nil { + return nil, err + } + var b bytes.Buffer + ew, err := age.Decrypt(&b, sr) + if err != nil { + return nil, err + } + _, err = ew.Read(cipher) + return b.Bytes(), err +} + +func main() { + // TODO: read args etc... +}