handle.go 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package handle
  2. import (
  3. "crypto"
  4. "crypto/rand"
  5. "crypto/rsa"
  6. "crypto/x509"
  7. "encoding/base64"
  8. "encoding/pem"
  9. "io/ioutil"
  10. "errors"
  11. )
  12. //私钥签名
  13. func RSASign (data []byte,filename string)(string, error){
  14. // 1、选择hash算法,对需要签名的数据进行hash运算
  15. myhash := crypto.SHA256
  16. hashInstance := myhash.New()
  17. hashInstance.Write(data)
  18. hashed := hashInstance.Sum(nil)
  19. // 2、读取私钥文件,解析出私钥对象
  20. privateKey, err := ReadParsePrivateKey(filename)
  21. if err != nil {
  22. return "", err
  23. }
  24. // 3、RSA数字签名(参数是随机数、私钥对象、哈希类型、签名文件的哈希串,生成bash64编码)
  25. bytes, err := rsa.SignPKCS1v15(rand.Reader, privateKey, myhash, hashed)
  26. if err != nil {
  27. return "", err
  28. }
  29. return base64.StdEncoding.EncodeToString(bytes), nil
  30. }
  31. //读取私钥文件,解析出私钥对象
  32. func ReadParsePrivateKey(filename string) (*rsa.PrivateKey, error) {
  33. // 1、读取私钥文件,获取私钥字节
  34. privateKeyBytes, err := ioutil.ReadFile(filename)
  35. if err != nil {
  36. return nil, err
  37. }
  38. // 2、解码私钥字节,生成加密对象
  39. block, _ := pem.Decode(privateKeyBytes)
  40. if block == nil {
  41. return nil, errors.New("私钥信息错误!")
  42. }
  43. // 3、解析DER编码的私钥,生成私钥对象
  44. privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  45. if err != nil {
  46. return nil, err
  47. }
  48. return privateKey, nil
  49. }
  50. //公钥验证
  51. func RSAVerify(data []byte, base64Sig, filename string) error {
  52. // 1、对base64编码的签名内容进行解码,返回签名字节
  53. bytes, err := base64.StdEncoding.DecodeString(base64Sig)
  54. if err != nil {
  55. return err
  56. }
  57. // 2、选择hash算法,对需要签名的数据进行hash运算
  58. myhash := crypto.SHA256
  59. hashInstance := myhash.New()
  60. hashInstance.Write(data)
  61. hashed := hashInstance.Sum(nil)
  62. // 3、读取公钥文件,解析出公钥对象
  63. publicKey, err := ReadParsePublicKey(filename)
  64. if err != nil {
  65. return err
  66. }
  67. // 4、RSA验证数字签名(参数是公钥对象、哈希类型、签名文件的哈希串、签名后的字节)
  68. return rsa.VerifyPKCS1v15(publicKey, myhash, hashed, bytes)
  69. }
  70. //读取公钥文件,解析公钥对象
  71. func ReadParsePublicKey(filename string) (*rsa.PublicKey, error) {
  72. // 1、读取公钥文件,获取公钥字节
  73. publicKeyBytes, err := ioutil.ReadFile(filename)
  74. if err != nil {
  75. return nil, err
  76. }
  77. // 2、解码公钥字节,生成加密对象
  78. block, _ := pem.Decode(publicKeyBytes)
  79. if block == nil {
  80. return nil, errors.New("公钥信息错误!")
  81. }
  82. // 3、解析DER编码的公钥,生成公钥接口
  83. publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  84. if err != nil {
  85. return nil, err
  86. }
  87. // 4、公钥接口转型成公钥对象
  88. publicKey := publicKeyInterface.(*rsa.PublicKey)
  89. return publicKey, nil
  90. }