加密解密

  1. package main
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "errors"
  9. "fmt"
  10. "testing"
  11. )
  12. // 可通过openssl产生
  13. //openssl genrsa -out rsa_private_key.pem 1024
  14. var privateKey = []byte(`
  15. -----BEGIN RSA PRIVATE KEY-----
  16. MIICXQIBAAKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfY
  17. djS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7
  18. Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB
  19. AoGAVqnmZYBht8G4buoief959bQmH1OOHV5+g5PBaSTfdEMWfp0JmrImaZRcHq5z
  20. iBMiyjc1URGK8pRVxy+N44QTweRoEmFjGWuHVoO1exElH3Oh18+Xvlmm3wJ22rpz
  21. MvUqlA0hMhLfo2keSTy4wS4ZNz/lzPImuWPZo08FbjrqfrECQQD4iKLUvw6MLs4S
  22. icaNQYLBHV9fjlZTNCI552ELKs9OLDk8++9FNFxFXOO8T6hdAbhhwoD75m7IPAb3
  23. Kmj1i7T9AkEA1hnHn5ZuX6BIinNe0g6s6DVgPeTTJoIczMst29x78VlhpEa7WX/l
  24. q4vLVH0CtVYmaluUeZOe6d3hVaJw2zbd5QJBAJ+a567mT0pZGH+xOPAn3Pd1jHUK
  25. LIfcWAqFe723LVBPeCagyATSXlsxDxM0uLOZ0jX9ueWLEyPF4NdDxgnCQWUCQQDE
  26. /E8oy/WdUhGsIN4bEpmPxJxaFhEYGxp4anA1G7WFp6EozlNN01jy7toTUDmPskYC
  27. EWSYP3Q05IqQibagWujpAkAo5vcQE7E5NB5Fhmb5fliul+gQ232W+LM8QqScRI2j
  28. F9iSqwhhwFTD/KgEL1cLnO9D4LPaUSaVBN7SL6nK0i3h
  29. -----END RSA PRIVATE KEY-----
  30. `)
  31. //openssl
  32. //openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
  33. var publicKey = []byte(`
  34. -----BEGIN PUBLIC KEY-----
  35. MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP2z9C4/iLNrlzP/RYuKNdJ3Mz
  36. vYh7j2yrGAo9MvZGy4hvCJfYdjS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVI
  37. c0ee13xmh12mpcu6QoOGseD7Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8T
  38. w0Cxp0yhkCPZ3ZVPUQIDAQAB
  39. -----END PUBLIC KEY-----
  40. `)
  41. // 加密
  42. func RsaEncrypt(origData []byte) ([]byte, error) {
  43. //解密pem格式的公钥
  44. block, _ := pem.Decode(publicKey)
  45. if block == nil {
  46. return nil, errors.New("public key error")
  47. }
  48. // 解析公钥
  49. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  50. if err != nil {
  51. return nil, err
  52. }
  53. // 类型断言
  54. pub := pubInterface.(*rsa.PublicKey)
  55. //加密
  56. return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
  57. }
  58. // 解密
  59. func RsaDecrypt(ciphertext []byte) ([]byte, error) {
  60. //解密
  61. block, _ := pem.Decode(privateKey)
  62. if block == nil {
  63. return nil, errors.New("private key error!")
  64. }
  65. //解析PKCS1格式的私钥
  66. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  67. if err != nil {
  68. return nil, err
  69. }
  70. // 解密
  71. return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  72. }
  73. func TestSecurity(t *testing.T) {
  74. data, _ := RsaEncrypt([]byte("hello world"))
  75. fmt.Printf("加密后的密文:%s", base64.StdEncoding.EncodeToString(data))
  76. origData, _ := RsaDecrypt(data)
  77. fmt.Println("start===================end")
  78. fmt.Printf("解密后的明文:%s", string(origData))
  79. }

密钥对不是pem格式

  1. /**
  2. * 密码Rsa加密
  3. */
  4. func RsaPwdEncrypt(password string) (string, error) {
  5. if len(password) == 0 {
  6. return "", nil
  7. }
  8. return rsaEncryptWithSha1Base64(password, "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwPdQAMcV5YdOIK2p3C3efA31Jw/mceoL9Y8EdkBD5OMBeFoPn2RVyMDGfyAjZoPiSJFeXIZMfL/Lwidbs0kMCcOrMOyncf6gydGNUIPVnJXt2vdjAWk7OwOVgwaj2cigSjRjIoV9H6IA7+AA0knf47jFppNPM+yPMM+d3spGvRQIDAQAB")
  9. }
  10. /**
  11. * 密码Rsa解密
  12. */
  13. func RsaPwdDecrypt(password string) (string, error) {
  14. if len(password) == 0 {
  15. return "", nil
  16. }
  17. return rsaDecryptWithSha1Base64(password, "MIICXAIBAAKBgQCwPdQAMcV5YdOIK2p3C3efA31Jw/mceoL9Y8EdkBD5OMBeFoPn2RVyMDGfyAjZoPiSJFeXIZMfL/Lwidbs0kMCcOrMOyncf6gydGNUIPVnJXt2vdjAWk7OwOVgwaj2cigSjRjIoV9H6IA7+AA0knf47jFppNPM+yPMM+d3spGvRQIDAQABAoGALMRXwIDj/1QpDjKxBXIlPX/+aCleky/PbBvVpvO8TAHtYzjm4pKSzwGM6WA/V0B7Q2v1z87YdxiP5ietL1Stblpj3auQlipVLfCgOHhe0Kx2CxRJp+YzvH/WpKofWyszGRrCtno2pEM129BGn/GdwRVHdzo1uFg1j46J5dpn5sECQQDWubPiZRuTP2BZWvDtJVcquOZrvfY9yaW8VvLl3GPHxVIM1xX5bQKheWOfTnq3b9VQMFX0Rnrirpv/eceJUnURAkEA0h5k9DzYf9mNwLL13ryIEC+l5CO8mKCdZAl+IdyTu8Y6f32To7M+X/vNoDYVEzZ6ZUQKe67KVp4g5upmHFVG9QJBAIQdQDukoAHKNbrkxGX02pvzpfpWp+I+ZpXqHYsmPdJVavVxhRixZLP7XztOaxzgVyv+gXRJxSQh8OOQhx/LtzECQHN2KkmgCeQve1qxvLQ565bhaAp2rNM+J17qbHpVCIV9x3V5XyDshVEfQH5SWcBmBloRSqVuhleUq0XY9mWJYuUCQBDFROe00M3qY2ltkDVtpzatXgfcUqZzI+/q2+a2VJgEt/HdNBrnV5qUr3hTNMk50tdED6m99pEaAK9dDkeDHFM=")
  18. }
  19. /**
  20. * (1)加密:采用sha1算法加密后转base64格式
  21. */
  22. func rsaEncryptWithSha1Base64(originalData, publicKey string) (string, error) {
  23. key, _ := base64.StdEncoding.DecodeString(publicKey)
  24. pubKey, _ := x509.ParsePKIXPublicKey(key)
  25. originalData1 := base64.StdEncoding.EncodeToString([]byte(originalData))
  26. originalDataBytes := []byte(originalData1)
  27. originalMaxLen := len(originalDataBytes)
  28. if originalMaxLen > 117 {
  29. var tempByte string
  30. countForm := 0
  31. countTo := 117
  32. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
  33. if err != nil {
  34. return "", err
  35. }
  36. tempByte += string(encryptedData)
  37. for {
  38. if countTo+117 > originalMaxLen {
  39. countForm += 117
  40. countTo = originalMaxLen
  41. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
  42. if err != nil {
  43. return "", err
  44. }
  45. tempByte += string(encryptedData)
  46. break
  47. } else {
  48. countForm += 117
  49. countTo += 117
  50. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), originalDataBytes[countForm:countTo])
  51. if err != nil {
  52. return "", err
  53. }
  54. tempByte += string(encryptedData)
  55. }
  56. }
  57. return base64.StdEncoding.EncodeToString([]byte(tempByte)), err
  58. } else {
  59. encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), []byte(originalData))
  60. return base64.StdEncoding.EncodeToString(encryptedData), err
  61. }
  62. }
  63. /**
  64. * (2)解密:对采用sha1算法加密后转base64格式的数据进行解密(私钥PKCS1格式)
  65. */
  66. func rsaDecryptWithSha1Base64(encryptedData, privateKey string) (string, error) {
  67. key, _ := base64.StdEncoding.DecodeString(privateKey)
  68. prvKey, _ := x509.ParsePKCS1PrivateKey(key)
  69. encryptedDecodeBytes, err := base64.StdEncoding.DecodeString(encryptedData)
  70. if err != nil {
  71. return "", err
  72. }
  73. if len(encryptedDecodeBytes) > 128 {
  74. var tempByte string
  75. for i := 0; i < len(encryptedDecodeBytes)/128; i++ {
  76. originalData, err := rsa.DecryptPKCS1v15(rand.Reader, prvKey, encryptedDecodeBytes[(i*128):128*(i+1)])
  77. if err != nil {
  78. return "", err
  79. }
  80. tempByte += string(originalData)
  81. }
  82. laststr, err := base64.StdEncoding.DecodeString(tempByte)
  83. return string(laststr), err
  84. } else {
  85. originalData, err := rsa.DecryptPKCS1v15(rand.Reader, prvKey, encryptedDecodeBytes)
  86. return string(originalData), err
  87. }
  88. }
  89. func main() {
  90. data, _ := RsaPwdEncrypt("hello world")
  91. fmt.Printf("加密后的密文:%s", data) // O1Hbq/QDmvzvSctf/OJRsv7/FQFFtBbS2Yax9xynn+Y970eyO8r2XHRqyhREEH4h6lJ1bCKck4TBU6/hARjSwM1CUmJ3E97rygCaybaPDwHroht91kxWUc84iDx9ya8X7yFShfs36Irn5mFbbLETX8zZt+V7B+aAYMv4wQqRd6Y=
  92. origData, _ := RsaPwdDecrypt(data)
  93. fmt.Println()
  94. fmt.Printf("解密后的明文:%s", origData) // hello world
  95. }

  1. package main
  2. import (
  3. "crypto/rand"
  4. "crypto/rsa"
  5. "crypto/x509"
  6. "encoding/base64"
  7. "encoding/pem"
  8. "errors"
  9. "fmt"
  10. )
  11. // 可通过openssl产生
  12. //openssl genrsa -out rsa_private_key.pem 1024
  13. var privateKey = []byte(`
  14. -----BEGIN RSA PRIVATE KEY-----
  15. MIICXQIBAAKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfY
  16. djS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7
  17. Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB
  18. AoGAVqnmZYBht8G4buoief959bQmH1OOHV5+g5PBaSTfdEMWfp0JmrImaZRcHq5z
  19. iBMiyjc1URGK8pRVxy+N44QTweRoEmFjGWuHVoO1exElH3Oh18+Xvlmm3wJ22rpz
  20. MvUqlA0hMhLfo2keSTy4wS4ZNz/lzPImuWPZo08FbjrqfrECQQD4iKLUvw6MLs4S
  21. icaNQYLBHV9fjlZTNCI552ELKs9OLDk8++9FNFxFXOO8T6hdAbhhwoD75m7IPAb3
  22. Kmj1i7T9AkEA1hnHn5ZuX6BIinNe0g6s6DVgPeTTJoIczMst29x78VlhpEa7WX/l
  23. q4vLVH0CtVYmaluUeZOe6d3hVaJw2zbd5QJBAJ+a567mT0pZGH+xOPAn3Pd1jHUK
  24. LIfcWAqFe723LVBPeCagyATSXlsxDxM0uLOZ0jX9ueWLEyPF4NdDxgnCQWUCQQDE
  25. /E8oy/WdUhGsIN4bEpmPxJxaFhEYGxp4anA1G7WFp6EozlNN01jy7toTUDmPskYC
  26. EWSYP3Q05IqQibagWujpAkAo5vcQE7E5NB5Fhmb5fliul+gQ232W+LM8QqScRI2j
  27. F9iSqwhhwFTD/KgEL1cLnO9D4LPaUSaVBN7SL6nK0i3h
  28. -----END RSA PRIVATE KEY-----
  29. `)
  30. //openssl
  31. //openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
  32. var publicKey []byte
  33. // 加密
  34. func RsaEncrypt(origData []byte) ([]byte, error) {
  35. //解密pem格式的公钥
  36. block, _ := pem.Decode(publicKey)
  37. if block == nil {
  38. return nil, errors.New("public key error")
  39. }
  40. // 解析公钥
  41. pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
  42. if err != nil {
  43. return nil, err
  44. }
  45. // 类型断言
  46. pub := pubInterface.(*rsa.PublicKey)
  47. //加密
  48. return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
  49. }
  50. // 解密
  51. func RsaDecrypt(ciphertext []byte) ([]byte, error) {
  52. //解密
  53. block, _ := pem.Decode(privateKey)
  54. if block == nil {
  55. return nil, errors.New("private key error!")
  56. }
  57. //解析PKCS1格式的私钥
  58. priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
  59. if err != nil {
  60. return nil, err
  61. }
  62. // 解密
  63. return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
  64. }
  65. func main() {
  66. publicKey = []byte("-----BEGIN PUBLIC KEY-----\n") // 换行符可以有多个,但不能没有
  67. publicKey = append(publicKey, []byte("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDP2z9C4/iLNrlzP/RYuKNdJ3MzvYh7j2yrGAo9MvZGy4hvCJfYdjS+SSXn++YEIORr+9X+SMHu9gHGi3kBxTbEUmVIc0ee13xmh12mpcu6QoOGseD7Q2dPx9Kjc21jeqJU3WS5QSelMN3DZVLrwt9Hjy8Tw0Cxp0yhkCPZ3ZVPUQIDAQAB")...)
  68. publicKey = append(publicKey, []byte("\n-----END PUBLIC KEY-----")...) // 换行符可以有多个,但不能没有
  69. data, _ := RsaEncrypt([]byte("hello world"))
  70. fmt.Printf("加密后的密文:%s\n", base64.StdEncoding.EncodeToString(data))
  71. origData, _ := RsaDecrypt(data)
  72. fmt.Println("start===================end")
  73. fmt.Printf("解密后的明文:%s", string(origData))
  74. }