|
| 1 | +# certstore [](https://pkg.go.dev/github.com/github/smimesign/certstore?tab=doc) |
| 2 | + |
| 3 | +Certstore is a Go library for accessing user identities stored in platform certificate stores. On Windows and macOS, certstore can enumerate user identities and sign messages with their private keys. |
| 4 | + |
| 5 | +## Example |
| 6 | + |
| 7 | +```go |
| 8 | +package main |
| 9 | + |
| 10 | +import ( |
| 11 | + "crypto" |
| 12 | + "encoding/hex" |
| 13 | + "errors" |
| 14 | + "fmt" |
| 15 | + |
| 16 | + "crypto/rand" |
| 17 | + "crypto/sha256" |
| 18 | + |
| 19 | + "github.com/github/smimesign/certstore" |
| 20 | +) |
| 21 | + |
| 22 | +func main() { |
| 23 | + sig, err := signWithMyIdentity("Ben Toews", "hello, world!") |
| 24 | + if err != nil { |
| 25 | + panic(err) |
| 26 | + } |
| 27 | + |
| 28 | + fmt.Println(hex.EncodeToString(sig)) |
| 29 | +} |
| 30 | + |
| 31 | +func signWithMyIdentity(cn, msg string) ([]byte, error) { |
| 32 | + // Open the certificate store for use. This must be Close()'ed once you're |
| 33 | + // finished with the store and any identities it contains. |
| 34 | + store, err := certstore.Open() |
| 35 | + if err != nil { |
| 36 | + return nil, err |
| 37 | + } |
| 38 | + defer store.Close() |
| 39 | + |
| 40 | + // Get an Identity slice, containing every identity in the store. Each of |
| 41 | + // these must be Close()'ed when you're done with them. |
| 42 | + idents, err := store.Identities() |
| 43 | + if err != nil { |
| 44 | + return nil, err |
| 45 | + } |
| 46 | + |
| 47 | + // Iterate through the identities, looking for the one we want. |
| 48 | + var me certstore.Identity |
| 49 | + for _, ident := range idents { |
| 50 | + defer ident.Close() |
| 51 | + |
| 52 | + crt, errr := ident.Certificate() |
| 53 | + if errr != nil { |
| 54 | + return nil, errr |
| 55 | + } |
| 56 | + |
| 57 | + if crt.Subject.CommonName == "Ben Toews" { |
| 58 | + me = ident |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + if me == nil { |
| 63 | + return nil, errors.New("Couldn't find my identity") |
| 64 | + } |
| 65 | + |
| 66 | + // Get a crypto.Signer for the identity. |
| 67 | + signer, err := me.Signer() |
| 68 | + if err != nil { |
| 69 | + return nil, err |
| 70 | + } |
| 71 | + |
| 72 | + // Digest and sign our message. |
| 73 | + digest := sha256.Sum256([]byte(msg)) |
| 74 | + signature, err := signer.Sign(rand.Reader, digest[:], crypto.SHA256) |
| 75 | + if err != nil { |
| 76 | + return nil, err |
| 77 | + } |
| 78 | + |
| 79 | + return signature, nil |
| 80 | +} |
| 81 | + |
| 82 | +``` |
0 commit comments