|
| 1 | +package crypto |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + |
| 8 | + "filippo.io/age" |
| 9 | + "filippo.io/age/armor" |
| 10 | +) |
| 11 | + |
| 12 | +type ageX25519Machine struct { |
| 13 | + recipient age.Recipient |
| 14 | + identity age.Identity |
| 15 | +} |
| 16 | + |
| 17 | +func NewAge(privateKey string) (Machine, error) { |
| 18 | + identity, err := age.ParseX25519Identity(privateKey) |
| 19 | + if err != nil { |
| 20 | + return nil, fmt.Errorf("failed to parse private key: %w", err) |
| 21 | + } |
| 22 | + |
| 23 | + return &ageX25519Machine{ |
| 24 | + recipient: identity.Recipient(), |
| 25 | + identity: identity, |
| 26 | + }, nil |
| 27 | +} |
| 28 | + |
| 29 | +func GenerateAgeKeyPair() (publicKey string, privateKey string, err error) { |
| 30 | + identity, err := age.GenerateX25519Identity() |
| 31 | + if err != nil { |
| 32 | + return "", "", err |
| 33 | + } |
| 34 | + |
| 35 | + return identity.Recipient().String(), identity.String(), nil |
| 36 | +} |
| 37 | + |
| 38 | +func DerivePublicKey(privateKey string) (string, error) { |
| 39 | + identity, err := age.ParseX25519Identity(privateKey) |
| 40 | + if err != nil { |
| 41 | + return "", fmt.Errorf("failed to parse private key: %w", err) |
| 42 | + } |
| 43 | + |
| 44 | + return identity.Recipient().String(), nil |
| 45 | +} |
| 46 | + |
| 47 | +func (a *ageX25519Machine) Encrypt(data []byte) ([]byte, error) { |
| 48 | + var buf bytes.Buffer |
| 49 | + |
| 50 | + armorWriter := armor.NewWriter(&buf) |
| 51 | + ageWriter, err := age.Encrypt(armorWriter, a.recipient) |
| 52 | + if err != nil { |
| 53 | + return nil, err |
| 54 | + } |
| 55 | + |
| 56 | + if _, err := ageWriter.Write(data); err != nil { |
| 57 | + return nil, err |
| 58 | + } |
| 59 | + |
| 60 | + if err := ageWriter.Close(); err != nil { |
| 61 | + return nil, err |
| 62 | + } |
| 63 | + |
| 64 | + if err := armorWriter.Close(); err != nil { |
| 65 | + return nil, err |
| 66 | + } |
| 67 | + |
| 68 | + return buf.Bytes(), nil |
| 69 | +} |
| 70 | + |
| 71 | +func (a *ageX25519Machine) Decrypt(data []byte) ([]byte, error) { |
| 72 | + reader := bytes.NewReader(data) |
| 73 | + |
| 74 | + armorReader := armor.NewReader(reader) |
| 75 | + ageReader, err := age.Decrypt(armorReader, a.identity) |
| 76 | + if err != nil { |
| 77 | + return nil, err |
| 78 | + } |
| 79 | + |
| 80 | + var buf bytes.Buffer |
| 81 | + if _, err := io.Copy(&buf, ageReader); err != nil { |
| 82 | + return nil, err |
| 83 | + } |
| 84 | + |
| 85 | + return buf.Bytes(), nil |
| 86 | +} |
0 commit comments