-
Notifications
You must be signed in to change notification settings - Fork 11
/
hugo-encrypt.go
102 lines (93 loc) · 2.44 KB
/
hugo-encrypt.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha1"
"crypto/sha256"
"encoding/hex"
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/PuerkitoBio/goquery"
"golang.org/x/crypto/pbkdf2"
)
func deriveKey(passphrase string, salt []byte) ([]byte, []byte) {
if salt == nil {
salt = make([]byte, 8)
// http://www.ietf.org/rfc/rfc2898.txt
// Salt.
_, err := rand.Read(salt)
if err != nil {
fmt.Println("Error in reading random number.")
}
}
return pbkdf2.Key([]byte(passphrase), salt, 1000, 32, sha256.New), salt
}
func encrypt(passphrase, plaintext string) string {
key, salt := deriveKey(passphrase, nil)
iv := make([]byte, 12)
// http://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
// Section 8.2
_, err := rand.Read(iv)
if err != nil {
fmt.Println("Error in reading random number.")
}
b, _ := aes.NewCipher(key)
aesgcm, _ := cipher.NewGCM(b)
data := aesgcm.Seal(nil, iv, []byte(plaintext), nil)
return hex.EncodeToString(salt) + "-" + hex.EncodeToString(iv) + "-" + hex.EncodeToString(data)
}
func encryptPage(path string) {
content, err := ioutil.ReadFile(path)
if err != nil {
panic(err)
}
doc, err := goquery.NewDocumentFromReader(bytes.NewBuffer(content))
if err != nil {
panic(err)
}
doc.Find("cipher-text").Each(func(i int, block *goquery.Selection) {
fmt.Printf("Processing %s, %d\n", path, i)
password, _ := block.Attr("data-password")
blockHtml, _ := block.Html()
data := []byte(blockHtml)
sha1ByteArray := sha1.Sum(data)
fmt.Printf("SHA1: % x\n\n", sha1ByteArray)
sha1String := hex.EncodeToString(sha1ByteArray[:])
encryptThis := blockHtml + "\n<div id='hugo-encrypt-sha1sum'>" + sha1String + "</div>"
encryptedHtml := encrypt(password, encryptThis)
block.RemoveAttr("data-password")
block.SetHtml(encryptedHtml)
})
wholeHtml, _ := doc.Html()
err = ioutil.WriteFile(path, []byte(wholeHtml), 0644)
if err != nil {
panic(err)
}
}
func main() {
sitePathPtr := flag.String("sitePath", "./public", "Relative or absolute path of the public directory generated by hugo")
flag.Parse()
err := filepath.Walk(*sitePathPtr, func(path string, f os.FileInfo, err error) error {
if f == nil {
return err
}
if f.IsDir() {
return nil
}
ok := strings.HasSuffix(f.Name(), ".html")
if ok {
encryptPage(path)
}
return nil
})
if err != nil {
fmt.Printf("filepath.Walk() returned %v\n", err)
panic(err)
}
}