A clean, Markdown-based publishing platform made for writers. Write together, and build a community. https://writefreely.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

63 lines
1.3 KiB

  1. /*
  2. * Copyright © 2019 A Bunch Tell LLC.
  3. *
  4. * This file is part of WriteFreely.
  5. *
  6. * WriteFreely is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License, included
  8. * in the LICENSE file in this source code package.
  9. */
  10. // Package key holds application keys and utilities around generating them.
  11. package key
  12. import (
  13. "crypto/rand"
  14. )
  15. const (
  16. EncKeysBytes = 32
  17. )
  18. type Keychain struct {
  19. EmailKey, CookieAuthKey, CookieKey []byte
  20. }
  21. // GenerateKeys generates necessary keys for the app on the given Keychain,
  22. // skipping any that already exist.
  23. func (keys *Keychain) GenerateKeys() error {
  24. // Generate keys only if they don't already exist
  25. var err, keyErrs error
  26. if len(keys.EmailKey) == 0 {
  27. keys.EmailKey, err = GenerateBytes(EncKeysBytes)
  28. if err != nil {
  29. keyErrs = err
  30. }
  31. }
  32. if len(keys.CookieAuthKey) == 0 {
  33. keys.CookieAuthKey, err = GenerateBytes(EncKeysBytes)
  34. if err != nil {
  35. keyErrs = err
  36. }
  37. }
  38. if len(keys.CookieKey) == 0 {
  39. keys.CookieKey, err = GenerateBytes(EncKeysBytes)
  40. if err != nil {
  41. keyErrs = err
  42. }
  43. }
  44. return keyErrs
  45. }
  46. // GenerateBytes returns securely generated random bytes.
  47. func GenerateBytes(n int) ([]byte, error) {
  48. b := make([]byte, n)
  49. _, err := rand.Read(b)
  50. if err != nil {
  51. return nil, err
  52. }
  53. return b, nil
  54. }