forked from nareix/tls-example
/
enc.go
62 lines (47 loc) · 1.12 KB
/
enc.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
package main
import (
"crypto/rand"
"crypto/x509"
"encoding/base64"
"fmt"
"io/ioutil"
"os"
)
const ()
func main() {
secretMsg, err := ioutil.ReadFile("cert2.pem")
if err != nil {
fmt.Printf("ReadFile: %s\n", err)
os.Exit(1)
}
blockType := "ENCRYPTED PRIVATE KEY"
password := []byte("password")
// see http://golang.org/pkg/crypto/x509/#pkg-constants
cipherType := x509.PEMCipherAES128
EncryptedPEMBlock, err := x509.EncryptPEMBlock(rand.Reader,
blockType,
[]byte(secretMsg),
password,
cipherType)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
sDec := base64.StdEncoding.EncodeToString(EncryptedPEMBlock.Bytes)
bs := len(sDec)
// fmt.Printf("raw[%d]:\n%q\n", bs, sDec)
fmt.Printf("-----BEGIN %s-----\n", blockType)
for k, v := range EncryptedPEMBlock.Headers {
fmt.Printf("%s: %s\n", k, v)
}
fmt.Printf("\n")
nblks := bs / 64
rem := bs % 64
// fmt.Printf("nBlks = %d, rem = %d\n", nblks, rem)
for i := 0; i < nblks; i++ {
fmt.Printf("%s\n", sDec[i*64:(i+1)*64])
}
// write the remaining bs-((nblks)*64)
fmt.Printf("%s\n", sDec[bs-rem:])
fmt.Printf("-----END %s-----\n", blockType)
}