hugo-encrypt.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "crypto/sha256"
  8. "encoding/hex"
  9. "fmt"
  10. "io/ioutil"
  11. "os"
  12. "path/filepath"
  13. "strings"
  14. "github.com/PuerkitoBio/goquery"
  15. "golang.org/x/crypto/pbkdf2"
  16. )
  17. func deriveKey(passphrase string, salt []byte) ([]byte, []byte) {
  18. if salt == nil {
  19. salt = make([]byte, 8)
  20. // http://www.ietf.org/rfc/rfc2898.txt
  21. // Salt.
  22. rand.Read(salt)
  23. }
  24. return pbkdf2.Key([]byte(passphrase), salt, 1000, 32, sha256.New), salt
  25. }
  26. func encrypt(passphrase, plaintext string) string {
  27. key, salt := deriveKey(passphrase, nil)
  28. iv := make([]byte, 12)
  29. // http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
  30. // Section 8.2
  31. rand.Read(iv)
  32. b, _ := aes.NewCipher(key)
  33. aesgcm, _ := cipher.NewGCM(b)
  34. data := aesgcm.Seal(nil, iv, []byte(plaintext), nil)
  35. return hex.EncodeToString(salt) + "-" + hex.EncodeToString(iv) + "-" + hex.EncodeToString(data)
  36. }
  37. func encryptPage(path string) {
  38. content, err := ioutil.ReadFile(path)
  39. if err != nil {
  40. panic(err)
  41. }
  42. doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(content))
  43. if err != nil {
  44. panic(err)
  45. }
  46. block := doc.Find("cipher-text")
  47. if len(block.Nodes) == 1 {
  48. fmt.Printf("Processing %s\n", path)
  49. password, _ := block.Attr("data-password")
  50. blockhtml, _ := block.Html()
  51. enchtml := encrypt(password, blockhtml)
  52. block.RemoveAttr("data-password")
  53. block.SetHtml(enchtml)
  54. wholehtml, _ := doc.Html()
  55. ioutil.WriteFile(path, []byte(wholehtml), 0644)
  56. }
  57. }
  58. func main() {
  59. sitePath := os.Args[1]
  60. if !sitePath {
  61. sitePath = "public"
  62. }
  63. err := filepath.Walk(sitePath, func(path string, f os.FileInfo, err error) error {
  64. if f == nil {
  65. return err
  66. }
  67. if f.IsDir() {
  68. return nil
  69. }
  70. ok := strings.HasSuffix(f.Name(), ".html")
  71. if ok {
  72. encryptPage(path)
  73. }
  74. return nil
  75. })
  76. if err != nil {
  77. fmt.Printf("filepath.Walk() returned %v\n", err)
  78. }
  79. }