6.1.1 核心代码
生成RSA密钥文件,如例所示。
例1-1 生成RSA密钥文件
1 package main
2 import (
3 "crypto/rand"
4 "crypto/rsa"
5 "crypto/x509"
6 "encoding/pem"
7 "flag"
8 "log"
9 "os"
10 )
11 func main() {
12 var bits int
13 flag.IntVar(&bits, "b", 2048, "密钥长度,默认为1024位")
14 if err := GenRsaKey(bits); err != nil {
15 log.Fatal("密钥文件生成失败!")
16 }
17 log.Println("密钥文件生成成功!")
18 }
19
20 func GenRsaKey(bits int) error {
21 // 生成私钥文件
22 privateKey, err := rsa.GenerateKey(rand.Reader, bits)
23 if err != nil {
24 return err
25 }
26 derStream := x509.MarshalPKCS1PrivateKey(privateKey)
27 block := &pem.Block{
28 Type: "私钥",
29 Bytes: derStream,
30 }
31 file, err := os.Create("private.pem")
32 if err != nil {
33 return err
34 }
35 err = pem.Encode(file, block)
36 if err != nil {
37 return err
38 }
39 // 生成公钥文件
40 publicKey := &privateKey.PublicKey
41 derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
42 if err != nil {
43 return err
44 }
45 block = &pem.Block{
46 Type: "公钥",
47 Bytes: derPkix,
48 }
49 file, err = os.Create("public.pem")
50 if err != nil {
51 return err
52 }
53 err = pem.Encode(file, block)
54 if err != nil {
55 return err
56 }
57 return nil
58 }
运行结果与秘钥文件生成结果分别如图所示。
图6.1 运行结果
图6.2 生成结果
RSA加密与解密,如例所示。
例1-2 RSA加密与解密
1 package main
2 import (
3 "crypto/rand"
4 "crypto/rsa"
5 "crypto/x509"
6 "encoding/base64"
7 "encoding/pem"
8 "errors"
9 "flag"
10 "fmt"
11 "io/ioutil"
12 "os"
13 )
14 func main() {
15 str := "一篇诗,一斗酒,一曲长歌,一剑天涯"
16 fmt.Println("加密前:", str)
17 data, _ := RsaEncryptString(str)
18 fmt.Println("加密后", data)
19 origData, _ := RsaDecryptString(data)
20 fmt.Println("解密后:", string(origData))
21 }
22 var decrypted string
23 var privateKey, publicKey []byte
24 func init() {
25 var err error
26 flag.StringVar(&decrypted, "d", "", "加密过的数据")
27 flag.Parse()
28 publicKey, err = ioutil.ReadFile("public.pem")
29 if err != nil {
30 os.Exit(-1)
31 }
32 privateKey, err = ioutil.ReadFile("private.pem")
33 if err != nil {
34 os.Exit(-1)
35 }
36 }
37 // 加密字节数组,返回字节数组
38 func RsaEncrypt(origData []byte) ([]byte, error) {
39 block, _ := pem.Decode(publicKey)
40 if block == nil {
41 return nil, errors.New("public key error")
42 }
43 pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
44 if err != nil {
45 return nil, err
46 }
47 pub := pubInterface.(*rsa.PublicKey)
48 return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
49 }
50 // 解密字节数组,返回字节数组
51 func RsaDecrypt(ciphertext []byte) ([]byte, error) {
52 block, _ := pem.Decode(privateKey)
53 if block == nil {
54 return nil, errors.New("private key error!")
55 }
56 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
57 if err != nil {
58 return nil, err
59 }
60 return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
61 }
62 // 加密字符串,返回base64处理的字符串
63 func RsaEncryptString(origData string) (string, error) {
64 block, _ := pem.Decode(publicKey)
65 if block == nil {
66 return "", errors.New("public key error")
67 }
68 pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
69 if err != nil {
70 return "", err
71 }
72 pub := pubInterface.(*rsa.PublicKey)
73 cipherArr, err := rsa.EncryptPKCS1v15(rand.Reader, pub, []byte(origData))
74 if err != nil {
75 return "", err
76 } else {
77 return base64.StdEncoding.EncodeToString(cipherArr), nil
78 }
79 }
80 // 解密经过base64处理的加密字符串,返回加密前的明文
81 func RsaDecryptString(cipherText string) (string, error) {
82 block, _ := pem.Decode(privateKey)
83 if block == nil {
84 return "", errors.New("private key error!")
85 }
86 priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
87 if err != nil {
88 return "", err
89 }
90 cipherArr, _ := base64.StdEncoding.DecodeString(cipherText)
91 originalArr, err := rsa.DecryptPKCS1v15(rand.Reader, priv, cipherArr)
92 if err != nil {
93 return "", err
94 } else {
95 return string(originalArr), nil
96 }
97 }
运行结果如图所示,由于加密后字段过长,这里只截取一部分。
图6.3 运行结果