零基礎Go語言開發培訓班有嗎?go語言課程講解:非對稱加密算法(二)

6.1.1 核心代碼數組

生成RSA密鑰文件,如例所示。加密

例1-1 生成RSA密鑰文件code

1 package maincdn

2 import (blog

3 "crypto/rand"ip

4 "crypto/rsa"ci

5 "crypto/x509"字符串

6 "encoding/pem"string

7 "flag"it

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 運行結果

相關文章
相關標籤/搜索