Golang Age with two or more receipentsWell, many cryptography programs become blotted over time, and support an increasing number of cryptography methods, and often struggle to integrate the most up-to-date methods. This has happened with OpenSSL, which supports so many symmetric key, hashing and public key encryption methods. With GPG/PGP (Pretty Good Privacy), we also see many methods. This page implements the Age (Actually Good Encryption) encryption method. In this case we will encrypt a message for Bob and Alice using their public keys, and where Bob and Alice can decrypt with their private keys. |
Outline
Age allows us to encrypt a file with two or more public keys. In this case we create key pairs for Bob and Alice, and then encrypt with their public keys:
a, _ := age.GenerateX25519Identity() b, _ := age.GenerateX25519Identity() out := &bytes.Buffer{} w, _ := age.Encrypt(out, a.Recipient(), b.Recipient())
Then Alice can decrypt with her private key:
r, _ := age.Decrypt(out, a) buf := new(bytes.Buffer) buf.ReadFrom(r) strB := buf.String()
The Python code for this is:
package main import ( "bytes" "encoding/base64" "fmt" "io" "log" "os" "filippo.io/age" ) func main() { msg := "Hello" argCount := len(os.Args[1:]) if argCount > 0 { msg = os.Args[1] } a, _ := age.GenerateX25519Identity() b, _ := age.GenerateX25519Identity() out := &bytes.Buffer{} w, _ := age.Encrypt(out, a.Recipient(), b.Recipient()) if _, err := io.WriteString(w, msg); err != nil { log.Fatalf("Failed to write to encrypted file: %v", err) } fmt.Printf("Message:\t%v\n", msg) fmt.Printf("\nEncrypted file size: %d\nCipher\t%v\n", out.Len(), base64.StdEncoding.EncodeToString(out.Bytes())) w.Close() r, _ := age.Decrypt(out, a) buf := new(bytes.Buffer) buf.ReadFrom(r) strB := buf.String() fmt.Printf("\nAlice Public key:\t%v\n", a.Recipient().String()) fmt.Printf("Alice Private key:\t%v\n", a.String()) fmt.Printf("Bpb Public key:\t\t%v\n", b.Recipient().String()) fmt.Printf("Bob Private key:\t%v\n", b.String()) fmt.Println("\n\nAlice Decrypted string\t ", strB) }
and a sample run is:
Message: the quick brown fox jumps over the lazy dog Encrypted file size: 282 Cipher YWdlLWVuY3J5cHRpb24ub3JnL3YxCi0+IFgyNTUxOSA0VW1qQW90ejVncXJxbGRSZUpRZjVxQndKZ3pIYno3Skc0blVjYmxtNFRRCkNnUlgxVVFucFFMeExaSWdORGVkWm91aGtlc1c1YzdQbENjK0o5dmNMbjgKLT4gWDI1NTE5IFRCcERXeng2NUhvU3FOS3dLZkJPdkY0VTZZY3hEOFI2aW5mSlNzRFJ0Q0EKa01nNDBvQ1daeFRMVStyK0hVWDVqcDhVTFo4ZlZ3K2ZDcERNSGJXRWU5WQotLS0gSlBnWGFHYi9iRXFmNDFZSTE5UDZua3ppZmlxTU1TN1daeUFQNURHZEVnOAr3FgdDRn7IVto9u0C39o+e Alice Public key: age14vlk6zanwrdu5zfqsrwnqpsk8493lf94y6mkxed6x6xhspectpxs4t07mm Alice Private key: AGE-SECRET-KEY-14P9CHHY0HQRJL7M48U3MSM3M0V5WNH7C64N272ZZ3XMGY9U9UF5SNMTGPG Bpb Public key: age1vu5hkqzkrxvnlmdjd3r9k243ex8zrswluj52tdrlgk9l4tsntayqxzakyv Bob Private key: AGE-SECRET-KEY-1R8EAECSR4HZU4T9926RRW2YLQHXVYANTR9KGWYPF75UQTDU0VNSQZ5MFRC Alice Decrypted string the quick brown fox jumps over the lazy dog