├── .gitignore ├── dh ├── dh_test.go └── dh.go ├── he ├── he_test.go └── he.go ├── image ├── 1.png ├── 10.png ├── 11.png ├── 12.png ├── 13.png ├── 14.png ├── 15.png ├── 16.png ├── 2.png ├── 3.png ├── 4.png ├── 5.png ├── 6.png ├── 7.png ├── 8.png └── 9.png ├── go.mod ├── hash ├── sha1.go ├── sha512.go ├── sha256.go ├── hmac_test.go ├── hmac.go └── sha_test.go ├── pkcs5padding.go ├── utils.go ├── aes ├── aesecb_test.go ├── aesctr_test.go ├── aescbc_test.go ├── aesctr.go ├── aescbc.go └── aesecb.go ├── ecc ├── getecckey.go ├── ecccrypt.go ├── eccsign.go ├── ecc_test.go └── ecies.go ├── rsa ├── getrsakey.go ├── rsasign.go ├── rsacrypt.go └── rsa_test.go ├── des ├── descbc_test.go ├── tripledes_test.go ├── descbc.go └── tripledescbc.go ├── go.sum └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /dh/dh_test.go: -------------------------------------------------------------------------------- 1 | package dh 2 | -------------------------------------------------------------------------------- /he/he_test.go: -------------------------------------------------------------------------------- 1 | package he 2 | -------------------------------------------------------------------------------- /he/he.go: -------------------------------------------------------------------------------- 1 | package he 2 | 3 | // todo 4 | -------------------------------------------------------------------------------- /image/1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/1.png -------------------------------------------------------------------------------- /image/10.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/10.png -------------------------------------------------------------------------------- /image/11.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/11.png -------------------------------------------------------------------------------- /image/12.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/12.png -------------------------------------------------------------------------------- /image/13.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/13.png -------------------------------------------------------------------------------- /image/14.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/14.png -------------------------------------------------------------------------------- /image/15.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/15.png -------------------------------------------------------------------------------- /image/16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/16.png -------------------------------------------------------------------------------- /image/2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/2.png -------------------------------------------------------------------------------- /image/3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/3.png -------------------------------------------------------------------------------- /image/4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/4.png -------------------------------------------------------------------------------- /image/5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/5.png -------------------------------------------------------------------------------- /image/6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/6.png -------------------------------------------------------------------------------- /image/7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/7.png -------------------------------------------------------------------------------- /image/8.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/8.png -------------------------------------------------------------------------------- /image/9.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wumansgy/goEncrypt/HEAD/image/9.png -------------------------------------------------------------------------------- /dh/dh.go: -------------------------------------------------------------------------------- 1 | package dh 2 | 3 | import "testing" 4 | 5 | 6 | func TestDh(t *testing.T) { 7 | 8 | } -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/wumansgy/goEncrypt 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/sirupsen/logrus v1.8.1 7 | github.com/stretchr/testify v1.8.0 8 | ) 9 | -------------------------------------------------------------------------------- /hash/sha1.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "crypto/sha1" 5 | "encoding/hex" 6 | ) 7 | 8 | func Sha1Hex(data []byte) string { 9 | return hex.EncodeToString(Sha1(data)) 10 | } 11 | 12 | func Sha1(data []byte) []byte { 13 | digest := sha1.New() 14 | digest.Write(data) 15 | return digest.Sum(nil) 16 | } 17 | -------------------------------------------------------------------------------- /hash/sha512.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "crypto/sha512" 5 | "encoding/hex" 6 | ) 7 | 8 | 9 | func Sha512Hex(data []byte)string{ 10 | return hex.EncodeToString(Sha512(data)) 11 | } 12 | 13 | func Sha512(data []byte)[]byte{ 14 | digest:=sha512.New() 15 | digest.Write(data) 16 | return digest.Sum(nil) 17 | } -------------------------------------------------------------------------------- /hash/sha256.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "crypto/sha256" 5 | "encoding/hex" 6 | ) 7 | 8 | 9 | func Sha256Hex(data []byte) string { 10 | return hex.EncodeToString(Sha256(data)) 11 | } 12 | 13 | func Sha256(data []byte) []byte { 14 | digest := sha256.New() 15 | digest.Write(data) 16 | return digest.Sum(nil) 17 | } 18 | -------------------------------------------------------------------------------- /hash/hmac_test.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | var ( 10 | hmac256="ee59ba4d767a2122cd5acebc538b31adce6d378719872e4b2b961d26a87b01cd" 11 | hmac512="ed697fcce5cc626037d96f8f27fe86f4bfbf12ddf1236b9f4a9172acab1d6c02fb987bb453c525f6dbc0167164e7ac18fcf8d36ed09ece8a7a03222473f57363" 12 | ) 13 | 14 | func TestHmacSha256Hex(t *testing.T) { 15 | res:=HmacSha256Hex([]byte("test"),"hmac text") 16 | assert.Equal(t, res, hmac256) 17 | } 18 | 19 | func TestHmacSha512Hex(t *testing.T) { 20 | res:=HmacSha512Hex([]byte("test"),"hmac text") 21 | assert.Equal(t, res, hmac512) 22 | } 23 | 24 | -------------------------------------------------------------------------------- /hash/hmac.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "crypto/hmac" 5 | "crypto/sha256" 6 | "crypto/sha512" 7 | "encoding/hex" 8 | "io" 9 | ) 10 | 11 | func HmacSha256(key []byte, body string) []byte { 12 | h := hmac.New(sha256.New, key) 13 | io.WriteString(h, body) 14 | return h.Sum(nil) 15 | } 16 | 17 | func HmacSha256Hex(key []byte, body string) string { 18 | return hex.EncodeToString(HmacSha256(key, body)) 19 | } 20 | 21 | func HmacSha512(key []byte, body string) []byte { 22 | h := hmac.New(sha512.New, key) 23 | io.WriteString(h, body) 24 | return h.Sum(nil) 25 | } 26 | 27 | func HmacSha512Hex(key []byte, body string) string { 28 | return hex.EncodeToString(HmacSha512(key, body)) 29 | } -------------------------------------------------------------------------------- /pkcs5padding.go: -------------------------------------------------------------------------------- 1 | package goEncrypt 2 | 3 | import ( 4 | "bytes" 5 | ) 6 | 7 | /* 8 | @Time : 2018/11/1 21:16 9 | @Author : wuman 10 | @File : padding 11 | @Software: GoLand 12 | */ 13 | /** 14 | 1. Group plaintext 15 | If the blocksize is not an integer multiple of blocksize, the blocksize bit should be considered 16 | If des algorithm is used, the block size is 8 bytes 17 | With the AES algorithm, 16 bytes of fast size are filled in 18 | A tool for populating data when using block encryption mode 19 | */ 20 | 21 | // It is populated using pkcs5 22 | 23 | func PKCS5Padding(plainText []byte, blockSize int) []byte { 24 | padding := blockSize - (len(plainText) % blockSize) 25 | padText := bytes.Repeat([]byte{byte(padding)}, padding) 26 | newText := append(plainText, padText...) 27 | return newText 28 | } 29 | 30 | func PKCS5UnPadding(plainText []byte, blockSize int) ([]byte, error) { 31 | length := len(plainText) 32 | number := int(plainText[length-1]) 33 | if number >= length || number > blockSize { 34 | return nil, ErrPaddingSize 35 | } 36 | return plainText[:length-number], nil 37 | } 38 | -------------------------------------------------------------------------------- /hash/sha_test.go: -------------------------------------------------------------------------------- 1 | package hash 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | const ( 10 | shaData = "sha text" 11 | 12 | sha1Hex = "d61babc269a1ccf83d8d08583fdf513eedeb55e6" 13 | sha256Hex = "65294d857d822c8b73af70c78cf6fc4325a0bf28c2efbbcd07c55b19eaf20d20" 14 | sha512Hex = "b4d5cda7b08feeca4ce2bf17e1ffab7d13e5234faca54ae46f4f87f66200a3bbc07b4b37b095eaf3bca2f8dba707bc259af3fe6e6e0b925a43915c9f351d92be" 15 | ) 16 | 17 | func TestSha1Hex(t *testing.T) { 18 | actual := Sha1Hex([]byte(shaData)) 19 | assert.Equal(t, sha1Hex, actual) 20 | } 21 | 22 | func TestSha256Hex(t *testing.T) { 23 | actual := Sha256Hex([]byte(shaData)) 24 | assert.Equal(t, sha256Hex, actual) 25 | } 26 | 27 | func TestSha512Hex(t *testing.T) { 28 | actual := Sha512Hex([]byte(shaData)) 29 | assert.Equal(t, sha512Hex, actual) 30 | } 31 | 32 | func BenchmarkSha256(b *testing.B) { 33 | for i := 0; i < b.N; i++ { 34 | Sha256Hex([]byte(shaData)) 35 | } 36 | } 37 | 38 | func BenchmarkSha512(b *testing.B) { 39 | for i := 0; i < b.N; i++ { 40 | Sha512Hex([]byte(shaData)) 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /utils.go: -------------------------------------------------------------------------------- 1 | package goEncrypt 2 | 3 | import "errors" 4 | 5 | var ( 6 | ErrCipherKey=errors.New("The secret key is wrong and cannot be decrypted. Please check") 7 | ErrKeyLengthSixteen=errors.New("a sixteen or twenty-four or thirty-two length secret key is required") 8 | ErrKeyLengtheEight=errors.New("a eight-length secret key is required") 9 | ErrKeyLengthTwentyFour=errors.New("a twenty-four-length secret key is required") 10 | ErrPaddingSize=errors.New("padding size error please check the secret key or iv") 11 | ErrIvAes=errors.New("a sixteen-length ivaes is required") 12 | ErrIvDes=errors.New("a eight-length ivdes key is required") 13 | ErrRsaBits=errors.New("bits 1024 or 2048") 14 | ) 15 | 16 | const ( 17 | Ivaes="wumansgy12345678" 18 | Ivdes="wumansgy" 19 | 20 | privateFileName="private.pem" 21 | publicFileName="public.pem" 22 | 23 | eccPrivateFileName="eccprivate.pem" 24 | eccPublishFileName="eccpublic.pem" 25 | 26 | privateKeyPrefix=" WUMAN RSA PRIVATE KEY " 27 | publicKeyPrefix=" WUMAN RSA PUBLIC KEY " 28 | 29 | eccPrivateKeyPrefix=" WUMAN ECC PRIVATE KEY " 30 | eccPublicKeyPrefix=" WUMAN ECC PUBLIC KEY " 31 | ) -------------------------------------------------------------------------------- /aes/aesecb_test.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestAesEcb(t *testing.T) { 9 | var ( 10 | key = "1234567812345678" 11 | plaintext = "TestAesEcb" 12 | ) 13 | cipherBytes, err := AesEcbEncrypt([]byte(plaintext), []byte(key)) 14 | assert.Nil(t, err) 15 | text, err := AesEcbDecrypt(cipherBytes, []byte(key)) 16 | assert.Nil(t, err) 17 | assert.Equal(t, string(text), plaintext) 18 | } 19 | 20 | func TestAesEcbEncryptBase64(t *testing.T) { 21 | var ( 22 | key = "1234567812345678" 23 | plaintext = "TestAesEcb" 24 | ) 25 | cipher, err := AesEcbEncryptBase64([]byte(plaintext), []byte(key)) 26 | assert.Nil(t, err) 27 | text, err := AesEcbDecryptByBase64(cipher, []byte(key)) 28 | assert.Nil(t, err) 29 | assert.Equal(t, string(text), plaintext) 30 | 31 | _, err = AesEcbDecryptByBase64("11111", []byte(key)) 32 | assert.NotNil(t, err) 33 | } 34 | 35 | func TestAesEcbEncryptHex(t *testing.T) { 36 | var ( 37 | key = "1234567812345678" 38 | plaintext = "TestAesEcb" 39 | ) 40 | cipher, err := AesEcbEncryptHex([]byte(plaintext), []byte(key)) 41 | assert.Nil(t, err) 42 | text, err := AesEcbDecryptByHex(cipher, []byte(key)) 43 | assert.Nil(t, err) 44 | assert.Equal(t, string(text), plaintext) 45 | 46 | _, err = AesEcbDecryptByHex("11111", []byte(key)) 47 | assert.NotNil(t, err) 48 | } 49 | -------------------------------------------------------------------------------- /ecc/getecckey.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/elliptic" 6 | "crypto/rand" 7 | "crypto/x509" 8 | "encoding/base64" 9 | "encoding/hex" 10 | ) 11 | 12 | type EccKey struct { 13 | PrivateKey string 14 | PublicKey string 15 | } 16 | 17 | func GenerateEccKeyHex() (EccKey, error) { 18 | privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 19 | if err != nil { 20 | return EccKey{}, err 21 | } 22 | privateBytes, err := x509.MarshalECPrivateKey(privateKey) 23 | if err != nil { 24 | return EccKey{}, err 25 | } 26 | publicBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey) 27 | if err != nil { 28 | return EccKey{}, err 29 | } 30 | 31 | return EccKey{ 32 | PrivateKey: hex.EncodeToString(privateBytes), 33 | PublicKey: hex.EncodeToString(publicBytes), 34 | }, nil 35 | } 36 | 37 | func GenerateEccKeyBase64() (EccKey, error) { 38 | privateKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 39 | if err != nil { 40 | return EccKey{}, err 41 | } 42 | privateBytes, err := x509.MarshalECPrivateKey(privateKey) 43 | if err != nil { 44 | return EccKey{}, err 45 | } 46 | publicBytes, err := x509.MarshalPKIXPublicKey(&privateKey.PublicKey) 47 | if err != nil { 48 | return EccKey{}, err 49 | } 50 | return EccKey{ 51 | PrivateKey: base64.StdEncoding.EncodeToString(privateBytes), 52 | PublicKey: base64.StdEncoding.EncodeToString(publicBytes), 53 | }, nil 54 | } 55 | -------------------------------------------------------------------------------- /rsa/getrsakey.go: -------------------------------------------------------------------------------- 1 | package rsa 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/rsa" 6 | "crypto/x509" 7 | "encoding/base64" 8 | "encoding/hex" 9 | 10 | "github.com/wumansgy/goEncrypt" 11 | ) 12 | 13 | /* 14 | Asymmetric encryption requires the generation of a pair of keys rather than a key, so before encryption here you need to get a pair of keys, public and private, respectively 15 | Generate the public and private keys all at once 16 | Encryption: plaintext to the power E Mod N to output ciphertext 17 | Decryption: ciphertext to the power D Mod N outputs plaintext 18 | 19 | Encryption operations take a long time? Encryption is faster 20 | 21 | The data is encrypted and cannot be easily decrypted 22 | */ 23 | 24 | type RsaKey struct { 25 | PrivateKey string 26 | PublicKey string 27 | } 28 | 29 | func GenerateRsaKeyHex(bits int) (RsaKey, error) { 30 | if bits != 1024 && bits != 2048 { 31 | return RsaKey{}, goEncrypt.ErrRsaBits 32 | } 33 | privateKey, err := rsa.GenerateKey(rand.Reader, bits) 34 | if err != nil { 35 | return RsaKey{}, err 36 | } 37 | return RsaKey{ 38 | PrivateKey: hex.EncodeToString(x509.MarshalPKCS1PrivateKey(privateKey)), 39 | PublicKey: hex.EncodeToString(x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)), 40 | }, nil 41 | } 42 | 43 | func GenerateRsaKeyBase64(bits int) (RsaKey, error) { 44 | if bits != 1024 && bits != 2048 { 45 | return RsaKey{}, goEncrypt.ErrRsaBits 46 | } 47 | privateKey, err := rsa.GenerateKey(rand.Reader, bits) 48 | if err != nil { 49 | return RsaKey{}, err 50 | } 51 | return RsaKey{ 52 | PrivateKey: base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PrivateKey(privateKey)), 53 | PublicKey: base64.StdEncoding.EncodeToString(x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)), 54 | }, nil 55 | } 56 | -------------------------------------------------------------------------------- /des/descbc_test.go: -------------------------------------------------------------------------------- 1 | package des 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | var ( 10 | key = "111" 11 | key8 = "12345678" 12 | plaintext = "TestDesCbc" 13 | badiv = "11111" 14 | goodiv = "12345678" 15 | ) 16 | 17 | func TestDesCbc(t *testing.T) { 18 | 19 | cipherBytes, err := DesCbcEncrypt([]byte(plaintext), []byte(key8), nil) 20 | assert.Nil(t, err) 21 | text, err := DesCbcDecrypt(cipherBytes, []byte(key8), nil) 22 | assert.Nil(t, err) 23 | assert.Equal(t, string(text), plaintext) 24 | 25 | cipherBytes, err = DesCbcEncrypt([]byte(plaintext), []byte(key), nil) 26 | assert.NotNil(t, err) 27 | 28 | cipherBytes, err = DesCbcEncrypt([]byte(plaintext), []byte(key8), []byte(badiv)) 29 | assert.NotNil(t, err) 30 | 31 | cipherBytes, err = DesCbcEncrypt([]byte(plaintext), []byte(key8), []byte(goodiv)) 32 | assert.Nil(t, err) 33 | text, err = DesCbcDecrypt(cipherBytes, []byte(key8), []byte(goodiv)) 34 | assert.Nil(t, err) 35 | assert.Equal(t, string(text), plaintext) 36 | 37 | } 38 | 39 | func TestDesEncryptBase64(t *testing.T) { 40 | cipher, err := DesCbcEncryptBase64([]byte(plaintext), []byte(key8), nil) 41 | assert.Nil(t, err) 42 | text, err := DesCbcDecryptByBase64(cipher, []byte(key8), nil) 43 | assert.Nil(t, err) 44 | assert.Equal(t, string(text), plaintext) 45 | 46 | _, err = DesCbcDecryptByBase64("11111", []byte(key8), nil) 47 | assert.NotNil(t, err) 48 | } 49 | 50 | func TestDesEncryptHex(t *testing.T) { 51 | cipher, err := DesCbcEncryptHex([]byte(plaintext), []byte(key8), nil) 52 | assert.Nil(t, err) 53 | text, err := DesCbcDecryptByHex(cipher, []byte(key8), nil) 54 | assert.Nil(t, err) 55 | assert.Equal(t, string(text), plaintext) 56 | 57 | _, err = DesCbcDecryptByHex("11111", []byte(key8), nil) 58 | assert.NotNil(t, err) 59 | } -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 5 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 6 | github.com/sirupsen/logrus v1.8.1 h1:dJKuHgqk1NNQlqoA6BTlM1Wf9DOH3NBjQyu0h9+AZZE= 7 | github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= 8 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 9 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= 10 | github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= 11 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 12 | github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk= 13 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= 14 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037 h1:YyJpGZS1sBuBCzLAR1VEpK193GlqGZbnPFnPV/5Rsb4= 15 | golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= 16 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 17 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 18 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 19 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= 20 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 21 | -------------------------------------------------------------------------------- /des/tripledes_test.go: -------------------------------------------------------------------------------- 1 | package des 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | var ( 9 | key24 = "123456781234567812345678" 10 | plainText = "TestTripleDes" 11 | ) 12 | 13 | func TestTripleDesCbc(t *testing.T) { 14 | cipherBytes, err := TripleDesEncrypt([]byte(plaintext), []byte(key24), nil) 15 | assert.Nil(t, err) 16 | text, err := TripleDesDecrypt(cipherBytes, []byte(key24), nil) 17 | assert.Nil(t, err) 18 | assert.Equal(t, string(text), plaintext) 19 | assert.NotEqual(t, string(text), "test") 20 | 21 | cipherBytes, err = TripleDesEncrypt([]byte(plaintext), []byte(key24), []byte(goodiv)) 22 | assert.Nil(t, err) 23 | text, err = TripleDesDecrypt(cipherBytes, []byte(key24), []byte(goodiv)) 24 | assert.Nil(t, err) 25 | assert.Equal(t, string(text), plaintext) 26 | assert.NotEqual(t, string(text), "test") 27 | 28 | cipherBytes, err = TripleDesEncrypt([]byte(plaintext), []byte(key24), []byte(badiv)) 29 | assert.NotNil(t, err) 30 | 31 | cipherBytes, err = TripleDesEncrypt([]byte(plaintext), []byte(badiv), []byte(badiv)) 32 | assert.NotNil(t, err) 33 | 34 | } 35 | 36 | func TestTripleDesEncryptBase64(t *testing.T) { 37 | cipher, err := TripleDesEncryptBase64([]byte(plainText), []byte(key24), nil) 38 | assert.Nil(t, err) 39 | text, err := TripleDesDecryptByBase64(cipher, []byte(key24), nil) 40 | assert.Nil(t, err) 41 | assert.Equal(t, string(text), plainText) 42 | 43 | _, err = TripleDesDecryptByBase64("11111", []byte(key24), nil) 44 | assert.NotNil(t, err) 45 | } 46 | 47 | func TestTripleDesEncryptHex(t *testing.T) { 48 | cipher, err := TripleDesEncryptHex([]byte(plainText), []byte(key24), nil) 49 | assert.Nil(t, err) 50 | text, err := TripleDesDecryptByHex(cipher, []byte(key24), nil) 51 | assert.Nil(t, err) 52 | assert.Equal(t, string(text), plainText) 53 | 54 | _, err = TripleDesDecryptByHex("11111", []byte(key24), nil) 55 | assert.NotNil(t, err) 56 | } -------------------------------------------------------------------------------- /aes/aesctr_test.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | func TestAesCtr(t *testing.T) { 9 | var ( 10 | key = "111" 11 | key16 = "1234567812345678" 12 | key24 = "123456781234567812345678" 13 | key32 = "12345678123456781234567812345678" 14 | plaintext = "TestAesCtr" 15 | ) 16 | cipherBytes, err := AesCtrEncrypt([]byte(plaintext), []byte(key16), nil) 17 | assert.Nil(t, err) 18 | text, err := AesCtrDecrypt(cipherBytes, []byte(key16), nil) 19 | assert.Nil(t, err) 20 | assert.Equal(t, string(text), plaintext) 21 | 22 | cipherBytes, err = AesCtrEncrypt([]byte(plaintext), []byte(key24), nil) 23 | assert.Nil(t, err) 24 | text, err = AesCtrDecrypt(cipherBytes, []byte(key24), nil) 25 | assert.Nil(t, err) 26 | assert.Equal(t, string(text), plaintext) 27 | 28 | cipherBytes, err = AesCtrEncrypt([]byte(plaintext), []byte(key32), nil) 29 | assert.Nil(t, err) 30 | text, err = AesCtrDecrypt(cipherBytes, []byte(key32), nil) 31 | assert.Nil(t, err) 32 | assert.Equal(t, string(text), plaintext) 33 | 34 | cipherBytes, err = AesCtrEncrypt([]byte(plaintext), []byte(key), nil) 35 | assert.NotNil(t, err) 36 | text, err = AesCtrDecrypt(cipherBytes, []byte(key), nil) 37 | assert.NotNil(t, err) 38 | } 39 | 40 | func TestAesCtrEncryptBase64(t *testing.T) { 41 | cipher, err := AesCtrEncryptBase64([]byte(plaintext), []byte(key16), nil) 42 | assert.Nil(t, err) 43 | text, err := AesCtrDecryptByBase64(cipher, []byte(key16), nil) 44 | assert.Nil(t, err) 45 | assert.Equal(t, string(text), plaintext) 46 | 47 | _, err = AesCtrDecryptByBase64("11111", []byte(key16), nil) 48 | assert.NotNil(t, err) 49 | } 50 | 51 | func TestAesCtrEncryptHex(t *testing.T) { 52 | cipher, err := AesCtrEncryptHex([]byte(plaintext), []byte(key16), nil) 53 | assert.Nil(t, err) 54 | text, err := AesCtrDecryptByHex(cipher, []byte(key16), nil) 55 | assert.Nil(t, err) 56 | assert.Equal(t, string(text), plaintext) 57 | 58 | _, err = AesCtrDecryptByHex("11111", []byte(key16), nil) 59 | assert.NotNil(t, err) 60 | } -------------------------------------------------------------------------------- /aes/aescbc_test.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | var ( 10 | key = "111" 11 | key16 = "1234567812345678" 12 | key24 = "123456781234567812345678" 13 | key32 = "12345678123456781234567812345678" 14 | plaintext = "TestAesCbc" 15 | badiv = "11111" 16 | goodiv = "1234567812345678" 17 | ) 18 | 19 | func TestAesCbc(t *testing.T) { 20 | 21 | cipherBytes, err := AesCbcEncrypt([]byte(plaintext), []byte(key16), nil) 22 | assert.Nil(t, err) 23 | text, err := AesCbcDecrypt(cipherBytes, []byte(key16), nil) 24 | assert.Nil(t, err) 25 | assert.Equal(t, string(text), plaintext) 26 | 27 | _, err = AesCbcDecrypt(cipherBytes, []byte(key24), nil) 28 | assert.NotNil(t, err) 29 | text, err = AesCbcDecrypt([]byte("badtext"), []byte(key24), nil) 30 | assert.Equal(t, string(text), "") 31 | 32 | cipherBytes, err = AesCbcEncrypt([]byte(plaintext), []byte(key24), nil) 33 | assert.Nil(t, err) 34 | text, err = AesCbcDecrypt(cipherBytes, []byte(key24), nil) 35 | assert.Nil(t, err) 36 | assert.Equal(t, string(text), plaintext) 37 | 38 | cipherBytes, err = AesCbcEncrypt([]byte(plaintext), []byte(key32), nil) 39 | assert.Nil(t, err) 40 | text, err = AesCbcDecrypt(cipherBytes, []byte(key32), nil) 41 | assert.Nil(t, err) 42 | assert.Equal(t, string(text), plaintext) 43 | 44 | cipherBytes, err = AesCbcEncrypt([]byte(plaintext), []byte(key), nil) 45 | assert.NotNil(t, err) 46 | text, err = AesCbcDecrypt(cipherBytes, []byte(key), nil) 47 | assert.NotNil(t, err) 48 | 49 | cipherBytes, err = AesCbcEncrypt([]byte(plaintext), []byte(key16), []byte(badiv)) 50 | assert.NotNil(t, err) 51 | text, err = AesCbcDecrypt(cipherBytes, []byte(key16), []byte(badiv)) 52 | assert.NotNil(t, err) 53 | 54 | cipherBytes, err = AesCbcEncrypt([]byte(plaintext), []byte(key16), []byte(goodiv)) 55 | assert.Nil(t, err) 56 | text, err = AesCbcDecrypt(cipherBytes, []byte(key16), []byte(goodiv)) 57 | assert.Nil(t, err) 58 | assert.Equal(t, string(text), plaintext) 59 | } 60 | 61 | func TestAesCbcEncryptBase64(t *testing.T) { 62 | cipher, err := AesCbcEncryptBase64([]byte(plaintext), []byte(key16), nil) 63 | assert.Nil(t, err) 64 | text, err := AesCbcDecryptByBase64(cipher, []byte(key16), nil) 65 | assert.Nil(t, err) 66 | assert.Equal(t, string(text), plaintext) 67 | 68 | _, err = AesCbcDecryptByBase64("11111", []byte(key16), nil) 69 | assert.NotNil(t, err) 70 | } 71 | 72 | func TestAesCbcEncryptHex(t *testing.T) { 73 | cipher, err := AesCbcEncryptHex([]byte(plaintext), []byte(key16), nil) 74 | assert.Nil(t, err) 75 | text, err := AesCbcDecryptByHex(cipher, []byte(key16), nil) 76 | assert.Nil(t, err) 77 | assert.Equal(t, string(text), plaintext) 78 | 79 | _, err = AesCbcDecryptByHex("11111", []byte(key16), nil) 80 | assert.NotNil(t, err) 81 | } 82 | -------------------------------------------------------------------------------- /rsa/rsasign.go: -------------------------------------------------------------------------------- 1 | package rsa 2 | 3 | import ( 4 | "crypto" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | "crypto/x509" 8 | "encoding/base64" 9 | "encoding/hex" 10 | "runtime" 11 | 12 | log "github.com/sirupsen/logrus" 13 | "github.com/wumansgy/goEncrypt/hash" 14 | ) 15 | 16 | func rsaSign(msg, priKey []byte) (sign []byte, err error) { 17 | defer func() { 18 | if err := recover(); err != nil { 19 | switch err.(type) { 20 | case runtime.Error: 21 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 22 | default: 23 | log.Errorf("error=%v,check the cipherText ", err) 24 | } 25 | } 26 | }() 27 | privateKey, err := x509.ParsePKCS1PrivateKey(priKey) 28 | hashed := hash.Sha256(msg) 29 | sign, err = rsa.SignPKCS1v15(rand.Reader, privateKey, crypto.SHA256, hashed) 30 | if err != nil { 31 | return nil, err 32 | } 33 | return sign, nil 34 | } 35 | 36 | func rsaVerifySign(msg []byte, sign []byte, pubKey []byte) bool { 37 | defer func() { 38 | if err := recover(); err != nil { 39 | switch err.(type) { 40 | case runtime.Error: 41 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 42 | default: 43 | log.Errorf("error=%v,check the cipherText ", err) 44 | } 45 | } 46 | }() 47 | publicKey, err := x509.ParsePKCS1PublicKey(pubKey) 48 | if err != nil { 49 | return false 50 | } 51 | hashed := hash.Sha256(msg) 52 | result := rsa.VerifyPKCS1v15(publicKey, crypto.SHA256, hashed, sign) 53 | return result == nil 54 | } 55 | 56 | func RsaSignBase64(msg []byte, base64PriKey string) (base64Sign string, err error) { 57 | priBytes, err := base64.StdEncoding.DecodeString(base64PriKey) 58 | if err != nil { 59 | return "", err 60 | } 61 | sign, err := rsaSign(msg, priBytes) 62 | if err != nil { 63 | return "", err 64 | } 65 | return base64.StdEncoding.EncodeToString(sign), nil 66 | } 67 | 68 | func RsaVerifySignBase64(msg []byte, base64Sign, base64PubKey string) bool { 69 | signBytes, err := base64.StdEncoding.DecodeString(base64Sign) 70 | if err != nil { 71 | return false 72 | } 73 | pubBytes, err := base64.StdEncoding.DecodeString(base64PubKey) 74 | if err != nil { 75 | return false 76 | } 77 | return rsaVerifySign(msg, signBytes, pubBytes) 78 | } 79 | 80 | func RsaSignHex(msg []byte, hexPriKey string) (hexSign string, err error) { 81 | priBytes, err := hex.DecodeString(hexPriKey) 82 | if err != nil { 83 | return "", err 84 | } 85 | sign, err := rsaSign(msg, priBytes) 86 | if err != nil { 87 | return "", err 88 | } 89 | return hex.EncodeToString(sign), nil 90 | } 91 | 92 | func RsaVerifySignHex(msg []byte, hexSign, hexPubKey string) bool { 93 | signBytes, err := hex.DecodeString(hexSign) 94 | if err != nil { 95 | return false 96 | } 97 | pubBytes, err := hex.DecodeString(hexPubKey) 98 | if err != nil { 99 | return false 100 | } 101 | return rsaVerifySign(msg, signBytes, pubBytes) 102 | } 103 | -------------------------------------------------------------------------------- /aes/aesctr.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | "encoding/base64" 7 | "encoding/hex" 8 | "runtime" 9 | 10 | log "github.com/sirupsen/logrus" 11 | "github.com/wumansgy/goEncrypt" 12 | ) 13 | 14 | /* 15 | AES CTR mode encryption and decryption 16 | */ 17 | func AesCtrEncrypt(plainText, secretKey, ivAes []byte) (cipherText []byte, err error) { 18 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 19 | return nil, goEncrypt.ErrKeyLengthSixteen 20 | } 21 | block, err := aes.NewCipher(secretKey) 22 | if err != nil { 23 | return nil, err 24 | } 25 | var iv []byte 26 | if len(ivAes) != 0 { 27 | if len(ivAes) != block.BlockSize() { 28 | return nil, goEncrypt.ErrIvAes 29 | } else { 30 | iv = ivAes 31 | } 32 | } else { 33 | iv = []byte(goEncrypt.Ivaes) 34 | } 35 | stream := cipher.NewCTR(block, iv) 36 | 37 | cipherText = make([]byte, len(plainText)) 38 | stream.XORKeyStream(cipherText, plainText) 39 | 40 | return cipherText, nil 41 | } 42 | 43 | func AesCtrDecrypt(cipherText, secretKey, ivAes []byte) (plainText []byte, err error) { 44 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 45 | return nil, goEncrypt.ErrKeyLengthSixteen 46 | } 47 | block, err := aes.NewCipher(secretKey) 48 | if err != nil { 49 | return nil, err 50 | } 51 | 52 | defer func() { 53 | if err := recover(); err != nil { 54 | switch err.(type) { 55 | case runtime.Error: 56 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 57 | default: 58 | log.Errorf("error=%v,check the cipherText ", err) 59 | } 60 | } 61 | }() 62 | 63 | var iv []byte 64 | if len(ivAes) != 0 { 65 | if len(ivAes) != block.BlockSize() { 66 | return nil, goEncrypt.ErrIvAes 67 | } else { 68 | iv = ivAes 69 | } 70 | } else { 71 | iv = []byte(goEncrypt.Ivaes) 72 | } 73 | stream := cipher.NewCTR(block, iv) 74 | 75 | plainText = make([]byte, len(cipherText)) 76 | stream.XORKeyStream(plainText, cipherText) 77 | 78 | return plainText, nil 79 | } 80 | 81 | func AesCtrEncryptBase64(plainText, secretKey, ivAes []byte) (cipherTextBase64 string, err error) { 82 | encryBytes, err := AesCtrEncrypt(plainText, secretKey, ivAes) 83 | return base64.StdEncoding.EncodeToString(encryBytes), err 84 | } 85 | 86 | func AesCtrEncryptHex(plainText, secretKey, ivAes []byte) (cipherTextHex string, err error) { 87 | encryBytes, err := AesCtrEncrypt(plainText, secretKey, ivAes) 88 | return hex.EncodeToString(encryBytes), err 89 | } 90 | 91 | func AesCtrDecryptByBase64(cipherTextBase64 string, secretKey, ivAes []byte) (plainText []byte, err error) { 92 | plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64) 93 | if err != nil { 94 | return []byte{}, err 95 | } 96 | return AesCtrDecrypt(plainTextBytes, secretKey, ivAes) 97 | } 98 | 99 | func AesCtrDecryptByHex(cipherTextHex string, secretKey, ivAes []byte) (plainText []byte, err error) { 100 | plainTextBytes, err := hex.DecodeString(cipherTextHex) 101 | if err != nil { 102 | return []byte{}, err 103 | } 104 | return AesCtrDecrypt(plainTextBytes, secretKey, ivAes) 105 | } 106 | -------------------------------------------------------------------------------- /aes/aescbc.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | "encoding/base64" 7 | "encoding/hex" 8 | "runtime" 9 | 10 | log "github.com/sirupsen/logrus" 11 | "github.com/wumansgy/goEncrypt" 12 | ) 13 | 14 | /** 15 | eencrypt 16 | Note: the key length is 16 bytes 17 | */ 18 | 19 | func init() { 20 | log.SetFormatter(&log.JSONFormatter{}) 21 | log.SetReportCaller(true) 22 | } 23 | 24 | // encrypt 25 | func AesCbcEncrypt(plainText, secretKey, ivAes []byte) (cipherText []byte, err error) { 26 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 27 | return nil, goEncrypt.ErrKeyLengthSixteen 28 | } 29 | block, err := aes.NewCipher(secretKey) 30 | if err != nil { 31 | return nil, err 32 | } 33 | paddingText := goEncrypt.PKCS5Padding(plainText, block.BlockSize()) 34 | 35 | var iv []byte 36 | if len(ivAes) != 0 { 37 | if len(ivAes) != block.BlockSize() { 38 | return nil, goEncrypt.ErrIvAes 39 | } else { 40 | iv = ivAes 41 | } 42 | } else { 43 | iv = []byte(goEncrypt.Ivaes) 44 | } // To initialize the vector, it needs to be the same length as block.blocksize 45 | blockMode := cipher.NewCBCEncrypter(block, iv) 46 | cipherText = make([]byte, len(paddingText)) 47 | blockMode.CryptBlocks(cipherText, paddingText) 48 | return cipherText, nil 49 | } 50 | 51 | // decrypt 52 | func AesCbcDecrypt(cipherText, secretKey, ivAes []byte) (plainText []byte, err error) { 53 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 54 | return nil, goEncrypt.ErrKeyLengthSixteen 55 | } 56 | block, err := aes.NewCipher(secretKey) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | defer func() { 62 | if err := recover(); err != nil { 63 | switch err.(type) { 64 | case runtime.Error: 65 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 66 | default: 67 | log.Errorf("error=%v,check the cipherText ", err) 68 | } 69 | } 70 | }() 71 | var iv []byte 72 | if len(ivAes) != 0 { 73 | if len(ivAes) != block.BlockSize() { 74 | return nil, goEncrypt.ErrIvAes 75 | } else { 76 | iv = ivAes 77 | } 78 | } else { 79 | iv = []byte(goEncrypt.Ivaes) 80 | } 81 | blockMode := cipher.NewCBCDecrypter(block, iv) 82 | paddingText := make([]byte, len(cipherText)) 83 | blockMode.CryptBlocks(paddingText, cipherText) 84 | 85 | plainText, err = goEncrypt.PKCS5UnPadding(paddingText, block.BlockSize()) 86 | if err != nil { 87 | return nil, err 88 | } 89 | return plainText, nil 90 | } 91 | 92 | func AesCbcEncryptBase64(plainText, secretKey, ivAes []byte) (cipherTextBase64 string, err error) { 93 | encryBytes, err := AesCbcEncrypt(plainText, secretKey, ivAes) 94 | return base64.StdEncoding.EncodeToString(encryBytes), err 95 | } 96 | 97 | func AesCbcEncryptHex(plainText, secretKey, ivAes []byte) (cipherTextHex string, err error) { 98 | encryBytes, err := AesCbcEncrypt(plainText, secretKey, ivAes) 99 | return hex.EncodeToString(encryBytes), err 100 | } 101 | 102 | func AesCbcDecryptByBase64(cipherTextBase64 string, secretKey, ivAes []byte) (plainText []byte, err error) { 103 | plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64) 104 | if err != nil { 105 | return []byte{}, err 106 | } 107 | return AesCbcDecrypt(plainTextBytes, secretKey, ivAes) 108 | } 109 | 110 | func AesCbcDecryptByHex(cipherTextHex string, secretKey, ivAes []byte) (plainText []byte, err error) { 111 | plainTextBytes, err := hex.DecodeString(cipherTextHex) 112 | if err != nil { 113 | return []byte{}, err 114 | } 115 | return AesCbcDecrypt(plainTextBytes, secretKey, ivAes) 116 | } 117 | -------------------------------------------------------------------------------- /des/descbc.go: -------------------------------------------------------------------------------- 1 | package des 2 | 3 | import ( 4 | "crypto/cipher" 5 | "crypto/des" 6 | "encoding/base64" 7 | "encoding/hex" 8 | "runtime" 9 | 10 | log "github.com/sirupsen/logrus" 11 | "github.com/wumansgy/goEncrypt" 12 | ) 13 | 14 | /** 15 | 1. Group plaintext 16 | DES CBC mode encryption and decryption, is an 8-byte block encryption 17 | If the group is not an integer multiple of 8, you need to consider completing the 8 bits2. 18 | */ 19 | func init() { 20 | log.SetFormatter(&log.JSONFormatter{}) 21 | log.SetReportCaller(true) 22 | } 23 | 24 | func DesCbcEncrypt(plainText, secretKey, ivDes []byte) (cipherText []byte, err error) { 25 | if len(secretKey) != 8 { 26 | return nil, goEncrypt.ErrKeyLengtheEight 27 | } 28 | block, err := des.NewCipher(secretKey) 29 | if err != nil { 30 | return nil, err 31 | } 32 | paddingText := goEncrypt.PKCS5Padding(plainText, block.BlockSize()) 33 | 34 | var iv []byte 35 | if len(ivDes) != 0 { 36 | if len(ivDes) != block.BlockSize() { 37 | return nil, goEncrypt.ErrIvDes 38 | } else { 39 | iv = ivDes 40 | } 41 | } else { 42 | iv = []byte(goEncrypt.Ivdes) 43 | } // Initialization vector 44 | blockMode := cipher.NewCBCEncrypter(block, iv) 45 | 46 | cipherText = make([]byte, len(paddingText)) 47 | blockMode.CryptBlocks(cipherText, paddingText) 48 | return cipherText, nil 49 | } 50 | 51 | func DesCbcDecrypt(cipherText, secretKey, ivDes []byte) (plainText []byte, err error) { 52 | if len(secretKey) != 8 { 53 | return nil, goEncrypt.ErrKeyLengtheEight 54 | } 55 | block, err := des.NewCipher(secretKey) 56 | if err != nil { 57 | return nil, err 58 | } 59 | 60 | defer func() { 61 | if err := recover(); err != nil { 62 | switch err.(type) { 63 | case runtime.Error: 64 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 65 | default: 66 | log.Errorf("error=%v,check the cipherText ", err) 67 | } 68 | } 69 | }() 70 | 71 | var iv []byte 72 | if len(ivDes) != 0 { 73 | if len(ivDes) != block.BlockSize() { 74 | return nil, goEncrypt.ErrIvDes 75 | } else { 76 | iv = ivDes 77 | } 78 | } else { 79 | iv = []byte(goEncrypt.Ivdes) 80 | } // Initialization vector 81 | blockMode := cipher.NewCBCDecrypter(block, iv) 82 | 83 | plainText = make([]byte, len(cipherText)) 84 | blockMode.CryptBlocks(plainText, cipherText) 85 | 86 | unPaddingText, err := goEncrypt.PKCS5UnPadding(plainText, block.BlockSize()) 87 | if err != nil { 88 | return nil, err 89 | } 90 | return unPaddingText, nil 91 | } 92 | 93 | func DesCbcEncryptBase64(plainText, secretKey, ivAes []byte) (cipherTextBase64 string, err error) { 94 | encryBytes, err := DesCbcEncrypt(plainText, secretKey, ivAes) 95 | return base64.StdEncoding.EncodeToString(encryBytes), err 96 | } 97 | 98 | func DesCbcEncryptHex(plainText, secretKey, ivAes []byte) (cipherTextHex string, err error) { 99 | encryBytes, err := DesCbcEncrypt(plainText, secretKey, ivAes) 100 | return hex.EncodeToString(encryBytes), err 101 | } 102 | 103 | func DesCbcDecryptByBase64(cipherTextBase64 string, secretKey, ivAes []byte) (plainText []byte, err error) { 104 | plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64) 105 | if err != nil { 106 | return []byte{}, err 107 | } 108 | return DesCbcDecrypt(plainTextBytes, secretKey, ivAes) 109 | } 110 | 111 | func DesCbcDecryptByHex(cipherTextHex string, secretKey, ivAes []byte) (plainText []byte, err error) { 112 | plainTextBytes, err := hex.DecodeString(cipherTextHex) 113 | if err != nil { 114 | return []byte{}, err 115 | } 116 | return DesCbcDecrypt(plainTextBytes, secretKey, ivAes) 117 | } 118 | -------------------------------------------------------------------------------- /aes/aesecb.go: -------------------------------------------------------------------------------- 1 | package aes 2 | 3 | import ( 4 | "crypto/aes" 5 | "crypto/cipher" 6 | "encoding/base64" 7 | "encoding/hex" 8 | 9 | "github.com/wumansgy/goEncrypt" 10 | ) 11 | 12 | /* 13 | Ecb is not recommended,use cbc 14 | */ 15 | type aesEcb struct { 16 | b cipher.Block 17 | blockSize int 18 | } 19 | 20 | func newECB(b cipher.Block) *aesEcb { 21 | return &aesEcb{ 22 | b: b, 23 | blockSize: b.BlockSize(), 24 | } 25 | } 26 | 27 | type ecbEncrypter aesEcb 28 | 29 | func newECBEncrypter(b cipher.Block) cipher.BlockMode { 30 | return (*ecbEncrypter)(newECB(b)) 31 | } 32 | 33 | func (x *ecbEncrypter) BlockSize() int { return x.blockSize } 34 | 35 | func (x *ecbEncrypter) CryptBlocks(dst, src []byte) { 36 | if len(src)%x.blockSize != 0 { 37 | return 38 | } 39 | if len(dst) < len(src) { 40 | return 41 | } 42 | 43 | for len(src) > 0 { 44 | x.b.Encrypt(dst, src[:x.blockSize]) 45 | src = src[x.blockSize:] 46 | dst = dst[x.blockSize:] 47 | } 48 | } 49 | 50 | type ecbDecrypter aesEcb 51 | 52 | func newECBDecrypter(b cipher.Block) cipher.BlockMode { 53 | return (*ecbDecrypter)(newECB(b)) 54 | } 55 | 56 | func (x *ecbDecrypter) BlockSize() int { 57 | return x.blockSize 58 | } 59 | 60 | func (x *ecbDecrypter) CryptBlocks(dst, src []byte) { 61 | if len(src)%x.blockSize != 0 { 62 | return 63 | } 64 | if len(dst) < len(src) { 65 | return 66 | } 67 | 68 | for len(src) > 0 { 69 | x.b.Decrypt(dst, src[:x.blockSize]) 70 | src = src[x.blockSize:] 71 | dst = dst[x.blockSize:] 72 | } 73 | } 74 | 75 | func AesEcbEncrypt(plainText, secretKey []byte) (cipherText []byte, err error) { 76 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 77 | return nil, goEncrypt.ErrKeyLengthSixteen 78 | } 79 | block, err := aes.NewCipher(secretKey) 80 | if err != nil { 81 | return nil, err 82 | } 83 | 84 | paddingText := goEncrypt.PKCS5Padding(plainText, block.BlockSize()) 85 | 86 | crypted := make([]byte, len(paddingText)) 87 | encrypter := newECBEncrypter(block) 88 | encrypter.CryptBlocks(crypted, paddingText) 89 | 90 | return crypted, nil 91 | } 92 | 93 | func AesEcbDecrypt(plainText, secretKey []byte) (cipjerText []byte, err error) { 94 | if len(secretKey) != 16 && len(secretKey) != 24 && len(secretKey) != 32 { 95 | return nil, goEncrypt.ErrKeyLengthSixteen 96 | } 97 | block, err := aes.NewCipher(secretKey) 98 | if err != nil { 99 | return nil, err 100 | } 101 | 102 | ecbDecrypter := newECBDecrypter(block) 103 | decrypted := make([]byte, len(plainText)) 104 | ecbDecrypter.CryptBlocks(decrypted, plainText) 105 | 106 | return goEncrypt.PKCS5UnPadding(decrypted, ecbDecrypter.BlockSize()) 107 | } 108 | 109 | func AesEcbEncryptBase64(plainText, key []byte) (cipherTextBase64 string, err error) { 110 | encryBytes, err := AesEcbEncrypt(plainText, key) 111 | return base64.StdEncoding.EncodeToString(encryBytes), err 112 | } 113 | 114 | func AesEcbEncryptHex(plainText, key []byte) (cipherTextHex string, err error) { 115 | encryBytes, err := AesEcbEncrypt(plainText, key) 116 | return hex.EncodeToString(encryBytes), err 117 | } 118 | 119 | func AesEcbDecryptByBase64(cipherTextBase64 string, key []byte) (plainText []byte, err error) { 120 | plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64) 121 | if err != nil { 122 | return []byte{}, err 123 | } 124 | return AesEcbDecrypt(plainTextBytes, key) 125 | } 126 | 127 | func AesEcbDecryptByHex(cipherTextHex string, key []byte) (plainText []byte, err error) { 128 | plainTextBytes, err := hex.DecodeString(cipherTextHex) 129 | if err != nil { 130 | return []byte{}, err 131 | } 132 | return AesEcbDecrypt(plainTextBytes, key) 133 | } 134 | -------------------------------------------------------------------------------- /ecc/ecccrypt.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/rand" 6 | "crypto/x509" 7 | "encoding/base64" 8 | "encoding/hex" 9 | "runtime" 10 | 11 | log "github.com/sirupsen/logrus" 12 | ) 13 | 14 | func init() { 15 | log.SetFormatter(&log.JSONFormatter{}) 16 | log.SetReportCaller(true) 17 | } 18 | 19 | // The public key and plaintext are passed in for encryption 20 | func eccEncrypt(plainText, pubKey []byte) (cipherText []byte, err error) { 21 | defer func() { 22 | if err := recover(); err != nil { 23 | switch err.(type) { 24 | case runtime.Error: 25 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 26 | default: 27 | log.Errorf("error=%v,check the cipherText ", err) 28 | } 29 | } 30 | }() 31 | tempPublicKey, err := x509.ParsePKIXPublicKey(pubKey) 32 | if err != nil { 33 | return nil, err 34 | } 35 | // Decode to get the private key in the ecdsa package 36 | publicKey1 := tempPublicKey.(*ecdsa.PublicKey) 37 | // Convert to the public key in the ecies package in the ethereum package 38 | publicKey := ImportECDSAPublic(publicKey1) 39 | cipherText, err = Encrypt(rand.Reader, publicKey, plainText, nil, nil) 40 | return cipherText, err 41 | 42 | } 43 | 44 | // The private key and plaintext are passed in for decryption 45 | func eccDecrypt(cipherText, priKey []byte) (msg []byte, err error) { 46 | defer func() { 47 | if err := recover(); err != nil { 48 | switch err.(type) { 49 | case runtime.Error: 50 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 51 | default: 52 | log.Errorf("error=%v,check the cipherText ", err) 53 | } 54 | } 55 | }() 56 | tempPrivateKey, err := x509.ParseECPrivateKey(priKey) 57 | if err != nil { 58 | return nil, err 59 | } 60 | // Decode to get the private key in the ecdsa package 61 | // Convert to the private key in the ecies package in the ethereum package 62 | privateKey := ImportECDSA(tempPrivateKey) 63 | plainText, err := privateKey.Decrypt(cipherText, nil, nil) 64 | if err != nil { 65 | return nil, err 66 | } 67 | return plainText, nil 68 | } 69 | 70 | func EccEncryptToBase64(plainText []byte, base64PubKey string) (base64CipherText string, err error) { 71 | pub, err := base64.StdEncoding.DecodeString(base64PubKey) 72 | if err != nil { 73 | return "", err 74 | } 75 | cipherBytes, err := eccEncrypt(plainText, pub) 76 | if err != nil { 77 | return "", err 78 | } 79 | return base64.StdEncoding.EncodeToString(cipherBytes), nil 80 | } 81 | 82 | // 83 | func EccDecryptByBase64(base64CipherText, base64PriKey string) (plainText []byte, err error) { 84 | privateBytes, err := base64.StdEncoding.DecodeString(base64PriKey) 85 | if err != nil { 86 | return nil, err 87 | } 88 | cipherTextBytes, err := base64.StdEncoding.DecodeString(base64CipherText) 89 | if err != nil { 90 | return nil, err 91 | } 92 | return eccDecrypt(cipherTextBytes, privateBytes) 93 | } 94 | 95 | func EccEncryptToHex(plainText []byte, hexPubKey string) (hexCipherText string, err error) { 96 | pub, err := hex.DecodeString(hexPubKey) 97 | if err != nil { 98 | return "", err 99 | } 100 | cipherBytes, err := eccEncrypt(plainText, pub) 101 | if err != nil { 102 | return "", err 103 | } 104 | return hex.EncodeToString(cipherBytes), nil 105 | } 106 | 107 | func EccDecryptByHex(hexCipherText, hexPriKey string) (plainText []byte, err error) { 108 | privateBytes, err := hex.DecodeString(hexPriKey) 109 | if err != nil { 110 | return nil, err 111 | } 112 | cipherTextBytes, err := hex.DecodeString(hexCipherText) 113 | if err != nil { 114 | return nil, err 115 | } 116 | return eccDecrypt(cipherTextBytes, privateBytes) 117 | } 118 | -------------------------------------------------------------------------------- /ecc/eccsign.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "crypto/ecdsa" 5 | "crypto/rand" 6 | "crypto/x509" 7 | "encoding/base64" 8 | "encoding/hex" 9 | "math/big" 10 | "runtime" 11 | 12 | log "github.com/sirupsen/logrus" 13 | "github.com/wumansgy/goEncrypt/hash" 14 | ) 15 | 16 | func eccSign(msg []byte, priKey []byte) (rSign []byte, sSign []byte, err error) { 17 | defer func() { 18 | if err := recover(); err != nil { 19 | switch err.(type) { 20 | case runtime.Error: 21 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 22 | default: 23 | log.Errorf("error=%v,check the cipherText ", err) 24 | } 25 | } 26 | }() 27 | privateKey, err := x509.ParseECPrivateKey(priKey) 28 | if err != nil { 29 | return nil, nil, err 30 | } 31 | resultHash := hash.Sha256(msg) 32 | r, s, err := ecdsa.Sign(rand.Reader, privateKey, resultHash) 33 | if err != nil { 34 | return nil, nil, err 35 | } 36 | 37 | rText, err := r.MarshalText() 38 | if err != nil { 39 | return nil, nil, err 40 | } 41 | sText, err := s.MarshalText() 42 | if err != nil { 43 | return nil, nil, err 44 | } 45 | return rText, sText, nil 46 | } 47 | 48 | func eccVerifySign(msg []byte, pubKey []byte, rText, sText []byte) bool { 49 | defer func() { 50 | if err := recover(); err != nil { 51 | switch err.(type) { 52 | case runtime.Error: 53 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 54 | default: 55 | log.Errorf("error=%v,check the cipherText ", err) 56 | } 57 | } 58 | }() 59 | publicKeyInterface, _ := x509.ParsePKIXPublicKey(pubKey) 60 | publicKey := publicKeyInterface.(*ecdsa.PublicKey) 61 | resultHash := hash.Sha256(msg) 62 | 63 | var r, s big.Int 64 | r.UnmarshalText(rText) 65 | s.UnmarshalText(sText) 66 | result := ecdsa.Verify(publicKey, resultHash, &r, &s) 67 | return result 68 | } 69 | 70 | func EccSignBase64(msg []byte, base64PriKey string) (base64rSign, base64sSign string, err error) { 71 | priBytes, err := base64.StdEncoding.DecodeString(base64PriKey) 72 | if err != nil { 73 | return "", "", err 74 | } 75 | rSign, sSign, err := eccSign(msg, priBytes) 76 | if err != nil { 77 | return "", "", err 78 | } 79 | return base64.StdEncoding.EncodeToString(rSign), base64.StdEncoding.EncodeToString(sSign), nil 80 | } 81 | 82 | func EccVerifySignBase64(msg []byte, base64rSign, base64sSign, base64PubKey string) bool { 83 | rSignBytes, err := base64.StdEncoding.DecodeString(base64rSign) 84 | if err != nil { 85 | return false 86 | } 87 | sSignBytes, err := base64.StdEncoding.DecodeString(base64sSign) 88 | if err != nil { 89 | return false 90 | } 91 | pubBytes, err := base64.StdEncoding.DecodeString(base64PubKey) 92 | if err != nil { 93 | return false 94 | } 95 | return eccVerifySign(msg, pubBytes, rSignBytes, sSignBytes) 96 | } 97 | 98 | func EccSignHex(msg []byte, hexPriKey string) (hexrSign, hexsSign string, err error) { 99 | priBytes, err := hex.DecodeString(hexPriKey) 100 | if err != nil { 101 | return "", "", err 102 | } 103 | rSign, sSign, err := eccSign(msg, priBytes) 104 | if err != nil { 105 | return "", "", err 106 | } 107 | return hex.EncodeToString(rSign), hex.EncodeToString(sSign), nil 108 | } 109 | 110 | func EccVerifySignHex(msg []byte, hexrSign, hexsSign, hexPubKey string) bool { 111 | rSignBytes, err := hex.DecodeString(hexrSign) 112 | if err != nil { 113 | return false 114 | } 115 | sSignBytes, err := hex.DecodeString(hexsSign) 116 | if err != nil { 117 | return false 118 | } 119 | pubBytes, err := hex.DecodeString(hexPubKey) 120 | if err != nil { 121 | return false 122 | } 123 | return eccVerifySign(msg, pubBytes, rSignBytes, sSignBytes) 124 | } 125 | -------------------------------------------------------------------------------- /des/tripledescbc.go: -------------------------------------------------------------------------------- 1 | package des 2 | 3 | import ( 4 | "crypto/cipher" 5 | "crypto/des" 6 | "encoding/base64" 7 | "encoding/hex" 8 | "runtime" 9 | 10 | log "github.com/sirupsen/logrus" 11 | "github.com/wumansgy/goEncrypt" 12 | ) 13 | 14 | /** 15 | Triple des encryption and decryption 16 | algorithm : Encryption: key one encryption -> key two decryption -> key three encryption 17 | Decryption: key three decryption -> key two encryption -> key one decryption 18 | */ 19 | func TripleDesEncrypt(plainText, secretKey, ivDes []byte) (cipherText []byte, err error) { 20 | if len(secretKey) != 24 { 21 | return nil, goEncrypt.ErrKeyLengthTwentyFour 22 | } 23 | block, err := des.NewTripleDESCipher(secretKey) 24 | if err != nil { 25 | return nil, err 26 | } 27 | paddingText := goEncrypt.PKCS5Padding(plainText, block.BlockSize()) 28 | 29 | var iv []byte 30 | if len(ivDes) != 0 { 31 | if len(ivDes) != block.BlockSize() { 32 | return nil, goEncrypt.ErrIvDes 33 | } else { 34 | iv = ivDes 35 | } 36 | } else { 37 | iv = []byte(goEncrypt.Ivdes) 38 | } 39 | blockMode := cipher.NewCBCEncrypter(block, iv) 40 | 41 | cipherText = make([]byte, len(paddingText)) 42 | blockMode.CryptBlocks(cipherText, paddingText) 43 | return cipherText, nil 44 | } 45 | 46 | func TripleDesDecrypt(cipherText, secretKey, ivDes []byte) (plainText []byte, err error) { 47 | if len(secretKey) != 24 { 48 | return nil, goEncrypt.ErrKeyLengthTwentyFour 49 | } 50 | // 1. Specifies that the 3des decryption algorithm creates and returns a cipher.Block interface using the TDEA algorithm。 51 | block, err := des.NewTripleDESCipher(secretKey) 52 | if err != nil { 53 | return nil, err 54 | } 55 | 56 | // 2. Delete the filling 57 | // Before deleting, prevent the user from entering different keys twice and causing panic, so do an error handling 58 | defer func() { 59 | if err := recover(); err != nil { 60 | switch err.(type) { 61 | case runtime.Error: 62 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 63 | default: 64 | log.Errorf("error=%v,check the cipherText ", err) 65 | } 66 | } 67 | }() 68 | 69 | var iv []byte 70 | if len(ivDes) != 0 { 71 | if len(ivDes) != block.BlockSize() { 72 | return nil, goEncrypt.ErrIvDes 73 | } else { 74 | iv = ivDes 75 | } 76 | } else { 77 | iv = []byte(goEncrypt.Ivdes) 78 | } 79 | blockMode := cipher.NewCBCDecrypter(block, iv) 80 | 81 | paddingText := make([]byte, len(cipherText)) // 82 | blockMode.CryptBlocks(paddingText, cipherText) 83 | 84 | plainText, err = goEncrypt.PKCS5UnPadding(paddingText, block.BlockSize()) 85 | if err != nil { 86 | return nil, err 87 | } 88 | return plainText, nil 89 | } 90 | 91 | func TripleDesEncryptBase64(plainText, secretKey, ivAes []byte) (cipherTextBase64 string, err error) { 92 | encryBytes, err := TripleDesEncrypt(plainText, secretKey, ivAes) 93 | return base64.StdEncoding.EncodeToString(encryBytes), err 94 | } 95 | 96 | func TripleDesEncryptHex(plainText, secretKey, ivAes []byte) (cipherTextHex string,err error) { 97 | encryBytes, err := TripleDesEncrypt(plainText, secretKey, ivAes) 98 | return hex.EncodeToString(encryBytes), err 99 | } 100 | 101 | func TripleDesDecryptByBase64(cipherTextBase64 string, secretKey, ivAes []byte) (plainText []byte,err error) { 102 | plainTextBytes, err := base64.StdEncoding.DecodeString(cipherTextBase64) 103 | if err != nil { 104 | return []byte{}, err 105 | } 106 | return TripleDesDecrypt(plainTextBytes, secretKey, ivAes) 107 | } 108 | 109 | func TripleDesDecryptByHex(cipherTextHex string, secretKey, ivAes []byte) (plainText []byte, err error) { 110 | plainTextBytes, err := hex.DecodeString(cipherTextHex) 111 | if err != nil { 112 | return []byte{}, err 113 | } 114 | return TripleDesDecrypt(plainTextBytes, secretKey, ivAes) 115 | } 116 | -------------------------------------------------------------------------------- /ecc/ecc_test.go: -------------------------------------------------------------------------------- 1 | package ecc 2 | 3 | import ( 4 | "github.com/stretchr/testify/assert" 5 | "testing" 6 | ) 7 | 8 | var ( 9 | msg = "床前明月光,疑是地上霜,举头望明月,低头思故乡" 10 | base64PubKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAElJ+LbZBekYTu/Md4T/j3DJsmJFf/3wLLmfUR7sLXCzS1PsDpHIC0QXRdVVdzS9BmP5GdtpesR4Oeh7g0TBBoLA==" 11 | base64PriKey = "MHcCAQEEIKPH4RlH9IQYwalxykgwlZkV9JjxQW2mHM+oGp4dxkMGoAoGCCqGSM49AwEHoUQDQgAElJ+LbZBekYTu/Md4T/j3DJsmJFf/3wLLmfUR7sLXCzS1PsDpHIC0QXRdVVdzS9BmP5GdtpesR4Oeh7g0TBBoLA==" 12 | 13 | hexPubKey = "3059301306072a8648ce3d020106082a8648ce3d030107034200043d39b48322518e8c6053ff63ef0426537fb1d5e16d128802c4c54104d61f84605b6bfa3266cc7f38968c0174d672e3690e50a93c819589f6d0f6bb44a57bcee8" 14 | hexPriKey = "30770201010420af9497e1c61ffe6019592a25f22a12e079e87d935b01bd2dc6d817744053a849a00a06082a8648ce3d030107a144034200043d39b48322518e8c6053ff63ef0426537fb1d5e16d128802c4c54104d61f84605b6bfa3266cc7f38968c0174d672e3690e50a93c819589f6d0f6bb44a57bcee8" 15 | ) 16 | 17 | func TestEccEncryptBase64(t *testing.T) { 18 | base64Key, err := GenerateEccKeyBase64() 19 | assert.Nil(t, err) 20 | 21 | cipherText, err := EccEncryptToBase64([]byte(msg), base64PubKey) 22 | assert.Nil(t, err) 23 | _, err = EccEncryptToBase64([]byte(msg), base64PriKey) 24 | assert.NotNil(t, err) 25 | plainText, err := EccDecryptByBase64(cipherText, base64PriKey) 26 | assert.Nil(t, err) 27 | assert.Equal(t, msg, string(plainText)) 28 | 29 | cipherText, err = EccEncryptToBase64([]byte(msg), base64Key.PublicKey) 30 | assert.Nil(t, err) 31 | plainText, err = EccDecryptByBase64(cipherText, base64Key.PrivateKey) 32 | assert.Nil(t, err) 33 | assert.Equal(t, msg, string(plainText)) 34 | _, err = EccDecryptByBase64(cipherText, base64Key.PublicKey) 35 | assert.NotNil(t, err) 36 | _, err = EccDecryptByBase64("badText", base64Key.PrivateKey) 37 | assert.NotNil(t, err) 38 | _, err = EccDecryptByBase64(cipherText, "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAElJ") 39 | assert.NotNil(t, err) 40 | 41 | } 42 | 43 | func TestEccEncryptHex(t *testing.T) { 44 | hexKey, err := GenerateEccKeyHex() 45 | assert.Nil(t, err) 46 | 47 | cipherText, err := EccEncryptToHex([]byte(msg), hexPubKey) 48 | assert.Nil(t, err) 49 | _, err = EccEncryptToHex([]byte(msg), hexPriKey) 50 | assert.NotNil(t, err) 51 | plainText, err := EccDecryptByHex(cipherText, hexPriKey) 52 | assert.Nil(t, err) 53 | assert.Equal(t, msg, string(plainText)) 54 | 55 | cipherText, err = EccEncryptToHex([]byte(msg), hexKey.PublicKey) 56 | assert.Nil(t, err) 57 | plainText, err = EccDecryptByHex(cipherText, hexKey.PrivateKey) 58 | assert.Nil(t, err) 59 | assert.Equal(t, msg, string(plainText)) 60 | _, err = EccDecryptByHex(cipherText, hexKey.PublicKey) 61 | assert.NotNil(t, err) 62 | _, err = EccDecryptByHex("badText", hexKey.PrivateKey) 63 | assert.NotNil(t, err) 64 | _, err = EccDecryptByHex(cipherText, "3059301306072a8648ce3d020106082a8648ce3d03") 65 | assert.NotNil(t, err) 66 | 67 | } 68 | 69 | func TestEccSignBase64(t *testing.T) { 70 | base64Key, err := GenerateEccKeyBase64() 71 | assert.Nil(t, err) 72 | 73 | rText, sText, err := EccSignBase64([]byte(msg), base64Key.PrivateKey) 74 | assert.Nil(t, err) 75 | _, _, err = EccSignBase64([]byte(msg), base64Key.PublicKey) 76 | assert.NotNil(t, err) 77 | _, _, err = EccSignBase64([]byte(msg), base64PubKey) 78 | assert.NotNil(t, err) 79 | 80 | res := EccVerifySignBase64([]byte(msg), rText, sText, base64Key.PublicKey) 81 | assert.Equal(t, res, true) 82 | 83 | res = EccVerifySignBase64([]byte(msg), rText, sText, base64Key.PrivateKey) 84 | assert.Equal(t, res, false) 85 | res = EccVerifySignBase64([]byte(msg), sText, rText, base64Key.PrivateKey) 86 | assert.Equal(t, res, false) 87 | } 88 | 89 | func TestEccSignHex(t *testing.T) { 90 | hexKey, err := GenerateEccKeyHex() 91 | assert.Nil(t, err) 92 | 93 | rText, sText, err := EccSignHex([]byte(msg), hexKey.PrivateKey) 94 | assert.Nil(t, err) 95 | _, _, err = EccSignHex([]byte(msg), hexKey.PublicKey) 96 | assert.NotNil(t, err) 97 | _, _, err = EccSignHex([]byte(msg), hexPubKey) 98 | assert.NotNil(t, err) 99 | 100 | res := EccVerifySignHex([]byte(msg), rText, sText, hexKey.PublicKey) 101 | assert.Equal(t, res, true) 102 | 103 | res = EccVerifySignHex([]byte(msg), rText, sText, hexKey.PrivateKey) 104 | assert.Equal(t, res, false) 105 | res = EccVerifySignHex([]byte(msg), sText, rText, hexKey.PrivateKey) 106 | assert.Equal(t, res, false) 107 | } 108 | -------------------------------------------------------------------------------- /rsa/rsacrypt.go: -------------------------------------------------------------------------------- 1 | package rsa 2 | 3 | import ( 4 | "bytes" 5 | "crypto/rand" 6 | "crypto/rsa" 7 | "crypto/x509" 8 | "encoding/base64" 9 | "encoding/hex" 10 | "runtime" 11 | 12 | log "github.com/sirupsen/logrus" 13 | ) 14 | 15 | /* 16 | Operation with rsa encryption 17 | */ 18 | func init() { 19 | log.SetFormatter(&log.JSONFormatter{}) 20 | log.SetReportCaller(true) 21 | } 22 | 23 | func rsaEncrypt(plainText, publicKey []byte) (cipherText []byte, err error) { 24 | defer func() { 25 | if err := recover(); err != nil { 26 | switch err.(type) { 27 | case runtime.Error: 28 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 29 | default: 30 | log.Errorf("error=%v,check the cipherText ", err) 31 | } 32 | } 33 | }() 34 | pub, err := x509.ParsePKCS1PublicKey(publicKey) 35 | if err != nil { 36 | return nil, err 37 | } 38 | pubSize, plainTextSize := pub.Size(), len(plainText) 39 | // EncryptPKCS1v15 encrypts the given message with RSA and the padding 40 | // scheme from PKCS #1 v1.5. The message must be no longer than the 41 | // length of the public modulus minus 11 bytes. 42 | // 43 | // The rand parameter is used as a source of entropy to ensure that 44 | // encrypting the same message twice doesn't result in the same 45 | // ciphertext. 46 | // 47 | // WARNING: use of this function to encrypt plaintexts other than 48 | // session keys is dangerous. Use RSA OAEP in new protocols. 49 | offSet, once := 0, pubSize-11 50 | buffer := bytes.Buffer{} 51 | for offSet < plainTextSize { 52 | endIndex := offSet + once 53 | if endIndex > plainTextSize { 54 | endIndex = plainTextSize 55 | } 56 | bytesOnce, err := rsa.EncryptPKCS1v15(rand.Reader, pub, plainText[offSet:endIndex]) 57 | if err != nil { 58 | return nil, err 59 | } 60 | buffer.Write(bytesOnce) 61 | offSet = endIndex 62 | } 63 | cipherText = buffer.Bytes() 64 | return cipherText, nil 65 | } 66 | 67 | func rsaDecrypt(cipherText, privateKey []byte) (plainText []byte, err error) { 68 | defer func() { 69 | if err := recover(); err != nil { 70 | switch err.(type) { 71 | case runtime.Error: 72 | log.Errorf("runtime err=%v,Check that the key or text is correct", err) 73 | default: 74 | log.Errorf("error=%v,check the cipherText ", err) 75 | } 76 | } 77 | }() 78 | pri, err := x509.ParsePKCS1PrivateKey(privateKey) 79 | if err != nil { 80 | return []byte{}, err 81 | } 82 | priSize, cipherTextSize := pri.Size(), len(cipherText) 83 | var offSet = 0 84 | var buffer = bytes.Buffer{} 85 | for offSet < cipherTextSize { 86 | endIndex := offSet + priSize 87 | if endIndex > cipherTextSize { 88 | endIndex = cipherTextSize 89 | } 90 | bytesOnce, err := rsa.DecryptPKCS1v15(rand.Reader, pri, cipherText[offSet:endIndex]) 91 | if err != nil { 92 | return nil, err 93 | } 94 | buffer.Write(bytesOnce) 95 | offSet = endIndex 96 | } 97 | plainText = buffer.Bytes() 98 | return plainText, nil 99 | } 100 | 101 | func RsaEncryptToBase64(plainText []byte, base64PubKey string) (base64CipherText string, err error) { 102 | pub, err := base64.StdEncoding.DecodeString(base64PubKey) 103 | if err != nil { 104 | return "", err 105 | } 106 | cipherBytes, err := rsaEncrypt(plainText, pub) 107 | if err != nil { 108 | return "", err 109 | } 110 | return base64.StdEncoding.EncodeToString(cipherBytes), nil 111 | } 112 | 113 | // 114 | func RsaDecryptByBase64(base64CipherText, base64PriKey string) (plainText []byte, err error) { 115 | privateBytes, err := base64.StdEncoding.DecodeString(base64PriKey) 116 | if err != nil { 117 | return nil, err 118 | } 119 | cipherTextBytes, err := base64.StdEncoding.DecodeString(base64CipherText) 120 | if err != nil { 121 | return nil, err 122 | } 123 | return rsaDecrypt(cipherTextBytes, privateBytes) 124 | } 125 | 126 | func RsaEncryptToHex(plainText []byte, hexPubKey string) (hexCipherText string, err error) { 127 | pub, err := hex.DecodeString(hexPubKey) 128 | if err != nil { 129 | return "", err 130 | } 131 | cipherBytes, err := rsaEncrypt(plainText, pub) 132 | if err != nil { 133 | return "", err 134 | } 135 | return hex.EncodeToString(cipherBytes), nil 136 | } 137 | 138 | func RsaDecryptByHex(hexCipherText, hexPriKey string) (plainText []byte, err error) { 139 | privateBytes, err := hex.DecodeString(hexPriKey) 140 | if err != nil { 141 | return nil, err 142 | } 143 | cipherTextBytes, err := hex.DecodeString(hexCipherText) 144 | if err != nil { 145 | return nil, err 146 | } 147 | return rsaDecrypt(cipherTextBytes, privateBytes) 148 | } 149 | -------------------------------------------------------------------------------- /ecc/ecies.go: -------------------------------------------------------------------------------- 1 | // Copyright (c) 2013 Kyle Isom 2 | // Copyright (c) 2012 The Go Authors. All rights reserved. 3 | // 4 | // Redistribution and use in source and binary forms, with or without 5 | // modification, are permitted provided that the following conditions are 6 | // met: 7 | // 8 | // * Redistributions of source code must retain the above copyright 9 | // notice, this list of conditions and the following disclaimer. 10 | // * Redistributions in binary form must reproduce the above 11 | // copyright notice, this list of conditions and the following disclaimer 12 | // in the documentation and/or other materials provided with the 13 | // distribution. 14 | // * Neither the name of Google Inc. nor the names of its 15 | // contributors may be used to endorse or promote products derived from 16 | // this software without specific prior written permission. 17 | // 18 | // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 | // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 | // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 | // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 | // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 | // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 | // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 | // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 | // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 | // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | 30 | package ecc 31 | 32 | import ( 33 | "crypto" 34 | "crypto/aes" 35 | "crypto/cipher" 36 | "crypto/ecdsa" 37 | "crypto/elliptic" 38 | "crypto/hmac" 39 | "crypto/sha256" 40 | "crypto/sha512" 41 | "crypto/subtle" 42 | "fmt" 43 | "hash" 44 | "io" 45 | "math/big" 46 | ) 47 | 48 | var ( 49 | ErrImport = fmt.Errorf("ecies: failed to import key") 50 | ErrInvalidCurve = fmt.Errorf("ecies: invalid elliptic curve") 51 | ErrInvalidParams = fmt.Errorf("ecies: invalid ECIES parameters") 52 | ErrInvalidPublicKey = fmt.Errorf("ecies: invalid public key") 53 | ErrSharedKeyIsPointAtInfinity = fmt.Errorf("ecies: shared key is point at infinity") 54 | ErrSharedKeyTooBig = fmt.Errorf("ecies: shared key params are too big") 55 | ErrUnsupportedECIESParameters = fmt.Errorf("ecies: unsupported ECIES parameters") 56 | 57 | ) 58 | 59 | // PublicKey is a representation of an elliptic curve public key. 60 | type PublicKey struct { 61 | X *big.Int 62 | Y *big.Int 63 | elliptic.Curve 64 | Params *ECIESParams 65 | } 66 | 67 | // Export an ECIES public key as an ECDSA public key. 68 | func (pub *PublicKey) ExportECDSA() *ecdsa.PublicKey { 69 | return &ecdsa.PublicKey{Curve: pub.Curve, X: pub.X, Y: pub.Y} 70 | } 71 | 72 | // Import an ECDSA public key as an ECIES public key. 73 | func ImportECDSAPublic(pub *ecdsa.PublicKey) *PublicKey { 74 | return &PublicKey{ 75 | X: pub.X, 76 | Y: pub.Y, 77 | Curve: pub.Curve, 78 | Params: ParamsFromCurve(pub.Curve), 79 | } 80 | } 81 | 82 | // PrivateKey is a representation of an elliptic curve private key. 83 | type PrivateKey struct { 84 | PublicKey 85 | D *big.Int 86 | } 87 | 88 | // Export an ECIES private key as an ECDSA private key. 89 | func (prv *PrivateKey) ExportECDSA() *ecdsa.PrivateKey { 90 | pub := &prv.PublicKey 91 | pubECDSA := pub.ExportECDSA() 92 | return &ecdsa.PrivateKey{PublicKey: *pubECDSA, D: prv.D} 93 | } 94 | 95 | // Import an ECDSA private key as an ECIES private key. 96 | func ImportECDSA(prv *ecdsa.PrivateKey) *PrivateKey { 97 | pub := ImportECDSAPublic(&prv.PublicKey) 98 | return &PrivateKey{*pub, prv.D} 99 | } 100 | 101 | // Generate an elliptic curve public / private keypair. If params is nil, 102 | // the recommended default parameters for the key will be chosen. 103 | func GenerateKey(rand io.Reader, curve elliptic.Curve, params *ECIESParams) (prv *PrivateKey, err error) { 104 | pb, x, y, err := elliptic.GenerateKey(curve, rand) 105 | if err != nil { 106 | return 107 | } 108 | prv = new(PrivateKey) 109 | prv.PublicKey.X = x 110 | prv.PublicKey.Y = y 111 | prv.PublicKey.Curve = curve 112 | prv.D = new(big.Int).SetBytes(pb) 113 | if params == nil { 114 | params = ParamsFromCurve(curve) 115 | } 116 | prv.PublicKey.Params = params 117 | return 118 | } 119 | 120 | // MaxSharedKeyLength returns the maximum length of the shared key the 121 | // public key can produce. 122 | func MaxSharedKeyLength(pub *PublicKey) int { 123 | return (pub.Curve.Params().BitSize + 7) / 8 124 | } 125 | 126 | // ECDH key agreement method used to establish secret keys for encryption. 127 | func (prv *PrivateKey) GenerateShared(pub *PublicKey, skLen, macLen int) (sk []byte, err error) { 128 | if prv.PublicKey.Curve != pub.Curve { 129 | return nil, ErrInvalidCurve 130 | } 131 | if skLen+macLen > MaxSharedKeyLength(pub) { 132 | return nil, ErrSharedKeyTooBig 133 | } 134 | 135 | x, _ := pub.Curve.ScalarMult(pub.X, pub.Y, prv.D.Bytes()) 136 | if x == nil { 137 | return nil, ErrSharedKeyIsPointAtInfinity 138 | } 139 | 140 | sk = make([]byte, skLen+macLen) 141 | skBytes := x.Bytes() 142 | copy(sk[len(sk)-len(skBytes):], skBytes) 143 | return sk, nil 144 | } 145 | 146 | var ( 147 | ErrKeyDataTooLong = fmt.Errorf("ecies: can't supply requested key data") 148 | ErrSharedTooLong = fmt.Errorf("ecies: shared secret is too long") 149 | ErrInvalidMessage = fmt.Errorf("ecies: invalid message") 150 | ) 151 | 152 | var ( 153 | big2To32 = new(big.Int).Exp(big.NewInt(2), big.NewInt(32), nil) 154 | big2To32M1 = new(big.Int).Sub(big2To32, big.NewInt(1)) 155 | ) 156 | 157 | func incCounter(ctr []byte) { 158 | if ctr[3]++; ctr[3] != 0 { 159 | return 160 | } 161 | if ctr[2]++; ctr[2] != 0 { 162 | return 163 | } 164 | if ctr[1]++; ctr[1] != 0 { 165 | return 166 | } 167 | if ctr[0]++; ctr[0] != 0 { 168 | return 169 | } 170 | } 171 | 172 | // NIST SP 800-56 Concatenation Key Derivation Function (see section 5.8.1). 173 | func concatKDF(hash hash.Hash, z, s1 []byte, kdLen int) (k []byte, err error) { 174 | if s1 == nil { 175 | s1 = make([]byte, 0) 176 | } 177 | 178 | reps := ((kdLen + 7) * 8) / (hash.BlockSize() * 8) 179 | if big.NewInt(int64(reps)).Cmp(big2To32M1) > 0 { 180 | fmt.Println(big2To32M1) 181 | return nil, ErrKeyDataTooLong 182 | } 183 | 184 | counter := []byte{0, 0, 0, 1} 185 | k = make([]byte, 0) 186 | 187 | for i := 0; i <= reps; i++ { 188 | hash.Write(counter) 189 | hash.Write(z) 190 | hash.Write(s1) 191 | k = append(k, hash.Sum(nil)...) 192 | hash.Reset() 193 | incCounter(counter) 194 | } 195 | 196 | k = k[:kdLen] 197 | return 198 | } 199 | 200 | // messageTag computes the MAC of a message (called the tag) as per 201 | // SEC 1, 3.5. 202 | func messageTag(hash func() hash.Hash, km, msg, shared []byte) []byte { 203 | mac := hmac.New(hash, km) 204 | mac.Write(msg) 205 | mac.Write(shared) 206 | tag := mac.Sum(nil) 207 | return tag 208 | } 209 | 210 | // Generate an initialisation vector for CTR mode. 211 | func generateIV(params *ECIESParams, rand io.Reader) (iv []byte, err error) { 212 | iv = make([]byte, params.BlockSize) 213 | _, err = io.ReadFull(rand, iv) 214 | return 215 | } 216 | 217 | // symEncrypt carries out CTR encryption using the block cipher specified in the 218 | // parameters. 219 | func symEncrypt(rand io.Reader, params *ECIESParams, key, m []byte) (ct []byte, err error) { 220 | c, err := params.Cipher(key) 221 | if err != nil { 222 | return 223 | } 224 | 225 | iv, err := generateIV(params, rand) 226 | if err != nil { 227 | return 228 | } 229 | ctr := cipher.NewCTR(c, iv) 230 | 231 | ct = make([]byte, len(m)+params.BlockSize) 232 | copy(ct, iv) 233 | ctr.XORKeyStream(ct[params.BlockSize:], m) 234 | return 235 | } 236 | 237 | // symDecrypt carries out CTR decryption using the block cipher specified in 238 | // the parameters 239 | func symDecrypt(params *ECIESParams, key, ct []byte) (m []byte, err error) { 240 | c, err := params.Cipher(key) 241 | if err != nil { 242 | return 243 | } 244 | 245 | ctr := cipher.NewCTR(c, ct[:params.BlockSize]) 246 | 247 | m = make([]byte, len(ct)-params.BlockSize) 248 | ctr.XORKeyStream(m, ct[params.BlockSize:]) 249 | return 250 | } 251 | 252 | // Encrypt encrypts a message using ECIES as specified in SEC 1, 5.1. 253 | // 254 | // s1 and s2 contain shared information that is not part of the resulting 255 | // ciphertext. s1 is fed into key derivation, s2 is fed into the MAC. If the 256 | // shared information parameters aren't being used, they should be nil. 257 | func Encrypt(rand io.Reader, pub *PublicKey, m, s1, s2 []byte) (ct []byte, err error) { 258 | params := pub.Params 259 | if params == nil { 260 | if params = ParamsFromCurve(pub.Curve); params == nil { 261 | err = ErrUnsupportedECIESParameters 262 | return 263 | } 264 | } 265 | R, err := GenerateKey(rand, pub.Curve, params) 266 | if err != nil { 267 | return 268 | } 269 | 270 | hash := params.Hash() 271 | z, err := R.GenerateShared(pub, params.KeyLen, params.KeyLen) 272 | if err != nil { 273 | return 274 | } 275 | K, err := concatKDF(hash, z, s1, params.KeyLen+params.KeyLen) 276 | if err != nil { 277 | return 278 | } 279 | Ke := K[:params.KeyLen] 280 | Km := K[params.KeyLen:] 281 | hash.Write(Km) 282 | Km = hash.Sum(nil) 283 | hash.Reset() 284 | 285 | em, err := symEncrypt(rand, params, Ke, m) 286 | if err != nil || len(em) <= params.BlockSize { 287 | return 288 | } 289 | 290 | d := messageTag(params.Hash, Km, em, s2) 291 | 292 | Rb := elliptic.Marshal(pub.Curve, R.PublicKey.X, R.PublicKey.Y) 293 | ct = make([]byte, len(Rb)+len(em)+len(d)) 294 | copy(ct, Rb) 295 | copy(ct[len(Rb):], em) 296 | copy(ct[len(Rb)+len(em):], d) 297 | return 298 | } 299 | 300 | // Decrypt decrypts an ECIES ciphertext. 301 | func (prv *PrivateKey) Decrypt(c, s1, s2 []byte) (m []byte, err error) { 302 | if len(c) == 0 { 303 | return nil, ErrInvalidMessage 304 | } 305 | params := prv.PublicKey.Params 306 | if params == nil { 307 | if params = ParamsFromCurve(prv.PublicKey.Curve); params == nil { 308 | err = ErrUnsupportedECIESParameters 309 | return 310 | } 311 | } 312 | hash := params.Hash() 313 | 314 | var ( 315 | rLen int 316 | hLen int = hash.Size() 317 | mStart int 318 | mEnd int 319 | ) 320 | 321 | switch c[0] { 322 | case 2, 3, 4: 323 | rLen = (prv.PublicKey.Curve.Params().BitSize + 7) / 4 324 | if len(c) < (rLen + hLen + 1) { 325 | err = ErrInvalidMessage 326 | return 327 | } 328 | default: 329 | err = ErrInvalidPublicKey 330 | return 331 | } 332 | 333 | mStart = rLen 334 | mEnd = len(c) - hLen 335 | 336 | R := new(PublicKey) 337 | R.Curve = prv.PublicKey.Curve 338 | R.X, R.Y = elliptic.Unmarshal(R.Curve, c[:rLen]) 339 | if R.X == nil { 340 | err = ErrInvalidPublicKey 341 | return 342 | } 343 | if !R.Curve.IsOnCurve(R.X, R.Y) { 344 | err = ErrInvalidCurve 345 | return 346 | } 347 | 348 | z, err := prv.GenerateShared(R, params.KeyLen, params.KeyLen) 349 | if err != nil { 350 | return 351 | } 352 | 353 | K, err := concatKDF(hash, z, s1, params.KeyLen+params.KeyLen) 354 | if err != nil { 355 | return 356 | } 357 | 358 | Ke := K[:params.KeyLen] 359 | Km := K[params.KeyLen:] 360 | hash.Write(Km) 361 | Km = hash.Sum(nil) 362 | hash.Reset() 363 | 364 | d := messageTag(params.Hash, Km, c[mStart:mEnd], s2) 365 | if subtle.ConstantTimeCompare(c[mEnd:], d) != 1 { 366 | err = ErrInvalidMessage 367 | return 368 | } 369 | 370 | m, err = symDecrypt(params, Ke, c[mStart:mEnd]) 371 | return 372 | } 373 | 374 | 375 | //以下为从以太坊源码/crypt/ecies/params.go中截取过来 376 | func ParamsFromCurve(curve elliptic.Curve) (params *ECIESParams) { 377 | return paramsFromCurve[curve] 378 | } 379 | var paramsFromCurve = map[elliptic.Curve]*ECIESParams{ 380 | //ethcrypto.S256(): ECIES_AES128_SHA256, 381 | elliptic.P256(): ECIES_AES128_SHA256, 382 | elliptic.P384(): ECIES_AES256_SHA384, 383 | elliptic.P521(): ECIES_AES256_SHA512, 384 | } 385 | var ( 386 | ECIES_AES128_SHA256 = &ECIESParams{ 387 | Hash: sha256.New, 388 | hashAlgo: crypto.SHA256, 389 | Cipher: aes.NewCipher, 390 | BlockSize: aes.BlockSize, 391 | KeyLen: 16, 392 | } 393 | 394 | ECIES_AES256_SHA256 = &ECIESParams{ 395 | Hash: sha256.New, 396 | hashAlgo: crypto.SHA256, 397 | Cipher: aes.NewCipher, 398 | BlockSize: aes.BlockSize, 399 | KeyLen: 32, 400 | } 401 | 402 | ECIES_AES256_SHA384 = &ECIESParams{ 403 | Hash: sha512.New384, 404 | hashAlgo: crypto.SHA384, 405 | Cipher: aes.NewCipher, 406 | BlockSize: aes.BlockSize, 407 | KeyLen: 32, 408 | } 409 | 410 | ECIES_AES256_SHA512 = &ECIESParams{ 411 | Hash: sha512.New, 412 | hashAlgo: crypto.SHA512, 413 | Cipher: aes.NewCipher, 414 | BlockSize: aes.BlockSize, 415 | KeyLen: 32, 416 | } 417 | ) 418 | type ECIESParams struct { 419 | Hash func() hash.Hash // hash function 420 | hashAlgo crypto.Hash 421 | Cipher func([]byte) (cipher.Block, error) // symmetric cipher 422 | BlockSize int // block size of symmetric cipher 423 | KeyLen int // length of symmetric key 424 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## goEncrypt 2 | 3 | [![](https://img.shields.io/badge/Auther-blog-blue.svg)](https://github.com/wumansgy) [![](https://img.shields.io/badge/Open%20Source-Y-brightgreen.svg)](https://github.com/wumansgy) 4 | 5 | go语言封装的各种对称加密和非对称加密,可以直接使用,包括3重DES,AES的CBC和CTR模式,还有RSA非对称加密 6 | 7 | 下载到本地可以直接调用 8 | 9 | 使用方法 10 | 11 | ``` 12 | go get github.com/wumansgy/goEncrypt 13 | ``` 14 | 15 | 然后下载到本地可以直接调用,包括了DES的CBC模式的加密解密(虽然DES早就被破解,但是可以参考使用),三重DES的加密解密(可以使用),AES的CBC模式和CTR模式(对称加密中常用的加密算法),非对称加密RSA的加密解密(比较常用的非对称加密算法),椭圆曲线加密算法(后面更新),还有哈希函数sha256,sha512的快速使用(MD5,SHA1已经在2004,2005年被陆续攻破,现在常用sha256和sha512) 16 | 17 | ## 1.1DES的快速使用 18 | 19 | ```go 20 | // des 21 | func main() { 22 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 23 | desSecretKey := "12345678" 24 | base64Text, err := des.DesCbcEncryptBase64([]byte(msg), []byte(desSecretKey), nil) 25 | if err != nil { 26 | fmt.Println(err) 27 | return 28 | } 29 | fmt.Printf("DES模式加密后的base64密文为:\n%s\n", base64Text) 30 | plaintext, err := des.DesCbcDecryptByBase64(base64Text, []byte(desSecretKey), nil) 31 | if err != nil { 32 | fmt.Println(err) 33 | return 34 | } 35 | fmt.Printf("DES模式解密后:\n%s\n", string(plaintext)) 36 | 37 | /*DES模式加密后的base64密文为: 38 | kzott0GFh9Rg0rsg1X2RP/F4YQ0tOBe6NfKjmAqiDfUrgqcw1P8Dix6IWe07DS2kJ7RZinPynHyiG+xB3NTajXBog4ayohan 39 | DES模式解密后: 40 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 41 | 42 | hexText, err := des.DesCbcEncryptHex([]byte(msg), []byte(desSecretKey), nil) 43 | if err != nil { 44 | fmt.Println(err) 45 | return 46 | } 47 | fmt.Printf("DES模式加密后的hex密文为:\n%s\n", hexText) 48 | plaintext, err = des.DesCbcDecryptByHex(hexText, []byte(desSecretKey), nil) 49 | if err != nil { 50 | fmt.Println(err) 51 | return 52 | } 53 | fmt.Printf("DES模式解密后:\n%s\n", string(plaintext)) 54 | 55 | /*DES模式加密后的hex密文为: 56 | 933a2db7418587d460d2bb20d57d913ff178610d2d3817ba35f2a3980aa20df52b82a730d4ff038b1e8859ed3b0d2da427b4598a73f29c7ca21bec41dcd4da8d70688386b2a216a7 57 | DES模式解密后: 58 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 59 | } 60 | ``` 61 | 62 | ## 1.2三重DES的快速使用 63 | 64 | ```go 65 | // triple_des 66 | func main() { 67 | 68 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 69 | tripleDesSecretKey := "123456781234567812345678" 70 | base64Text, err := des.TripleDesEncryptBase64([]byte(msg), []byte(tripleDesSecretKey), nil) 71 | if err != nil { 72 | fmt.Println(err) 73 | return 74 | } 75 | fmt.Printf("三重DES模式加密后的base64密文为:\n%s\n", base64Text) 76 | plaintext, err := des.TripleDesDecryptByBase64(base64Text, []byte(tripleDesSecretKey), nil) 77 | if err != nil { 78 | fmt.Println(err) 79 | return 80 | } 81 | fmt.Printf("三重DES模式解密后:\n%s\n", string(plaintext)) 82 | 83 | /*三重DES模式加密后的base64密文为: 84 | kzott0GFh9Rg0rsg1X2RP/F4YQ0tOBe6NfKjmAqiDfUrgqcw1P8Dix6IWe07DS2kJ7RZinPynHyiG+xB3NTajXBog4ayohan 85 | 三重DES模式解密后: 86 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 87 | 88 | hexText, err := des.TripleDesEncryptHex([]byte(msg), []byte(tripleDesSecretKey), nil) 89 | if err != nil { 90 | fmt.Println(err) 91 | return 92 | } 93 | fmt.Printf("三重DES模式加密后的hex密文为:\n%s\n", hexText) 94 | plaintext, err = des.TripleDesDecryptByHex(hexText, []byte(tripleDesSecretKey), nil) 95 | if err != nil { 96 | fmt.Println(err) 97 | return 98 | } 99 | fmt.Printf("三重DES模式解密后:\n%s\n", string(plaintext)) 100 | 101 | /*三重DES模式加密后的hex密文为: 102 | 933a2db7418587d460d2bb20d57d913ff178610d2d3817ba35f2a3980aa20df52b82a730d4ff038b1e8859ed3b0d2da427b4598a73f29c7ca21bec41dcd4da8d70688386b2a216a7 103 | 三重DES模式解密后: 104 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 105 | } 106 | 107 | ``` 108 | 109 | 110 | ## 2.1AES的CBC模式的快速使用 111 | 112 | ```go 113 | func main() { 114 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 115 | aesSecretKey := "1234567812345678" 116 | base64Text, err := aes.AesCbcEncryptBase64([]byte(msg), []byte(aesSecretKey), nil) 117 | if err != nil { 118 | fmt.Println(err) 119 | return 120 | } 121 | fmt.Printf("AES的CBC模式加密后的base64密文为:\n%s\n", base64Text) 122 | plaintext, err := aes.AesCbcDecryptByBase64(base64Text, []byte(aesSecretKey), nil) 123 | if err != nil { 124 | fmt.Println(err) 125 | return 126 | } 127 | fmt.Printf("AES的CBC模式解密后:\n%s\n", string(plaintext)) 128 | 129 | /*AES的CBC模式加密后的base64密文为: 130 | Y8uCrLL8SavXyiUzpnU+Lmn4mODprYL/odSK3MVmGlseuftpJ6A6szrGl/bfDK18z+EkD7TXNI4WemUdvbHZCtSQ1OwexzDtDWcFETU2Ml8= 131 | AES的CBC模式解密后: 132 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 133 | 134 | hexText, err := aes.AesCbcEncryptHex([]byte(msg), []byte(aesSecretKey), nil) 135 | if err != nil { 136 | fmt.Println(err) 137 | return 138 | } 139 | fmt.Printf("AES的CBC模式加密后的hex密文为:\n%s\n", hexText) 140 | plaintext, err = aes.AesCbcDecryptByHex(hexText, []byte(aesSecretKey), nil) 141 | if err != nil { 142 | fmt.Println(err) 143 | return 144 | } 145 | fmt.Printf("AES的CBC模式解密后:\n%s\n", string(plaintext)) 146 | 147 | /*AES的CBC模式加密后的hex密文为: 148 | 63cb82acb2fc49abd7ca2533a6753e2e69f898e0e9ad82ffa1d48adcc5661a5b1eb9fb6927a03ab33ac697f6df0cad7ccfe124067a651dbdb1d90ad490d4ec1ec730ed0d6705113536325f 149 | AES的CBC模式解密后: 150 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 151 | } 152 | ``` 153 | 154 | 155 | ## 2.2AES的CTR模式的快速使用 156 | 157 | ```go 158 | func main() { 159 | 160 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 161 | aesSecretKey := "1234567812345678" 162 | base64Text, err := aes.AesCtrEncryptBase64([]byte(msg), []byte(aesSecretKey), nil) 163 | if err != nil { 164 | fmt.Println(err) 165 | return 166 | } 167 | fmt.Printf("AES的CTR模式加密后的base64密文为:\n%s\n", base64Text) 168 | plaintext, err := aes.AesCtrDecryptByBase64(base64Text, []byte(aesSecretKey), nil) 169 | if err != nil { 170 | fmt.Println(err) 171 | return 172 | } 173 | fmt.Printf("AES的CTR模式解密后:\n%s\n", string(plaintext)) 174 | 175 | /*AES的CTR模式加密后的base64密文为: 176 | PzO1cjrO1q1PZeJEPw/fDM/TmZ2r4V+yao+MkDVTvR6pdlxdbFhzs1LF6rrZhUgC257ZQbofd0NTJFUUDwsc6rCcEL50 177 | AES的CTR模式解密后: 178 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 179 | 180 | hexText, err := aes.AesCtrEncryptHex([]byte(msg), []byte(aesSecretKey), nil) 181 | if err != nil { 182 | fmt.Println(err) 183 | return 184 | } 185 | fmt.Printf("AES的CTR模式加密后的hex密文为:\n%s\n", hexText) 186 | plaintext, err = aes.AesCtrDecryptByHex(hexText, []byte(aesSecretKey), nil) 187 | if err != nil { 188 | fmt.Println(err) 189 | return 190 | } 191 | fmt.Printf("AES的CTR模式解密后:\n%s\n", string(plaintext)) 192 | 193 | /*AES的CTR模式加密后的hex密文为: 194 | 3f33b5723aced6ad4f65e2443f0fdf0ccfd3999dabe15fb26a8f8c903553bd1ea9765c5d6c5873b352c5eabad9854802db9ed941ba1f7743532455140f0b1ceab09c10be74 195 | AES的CTR模式解密后: 196 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 197 | 198 | } 199 | ``` 200 | 201 | ## 2.3AES的ECB模式的快速使用-不推荐 202 | 203 | ```go 204 | func main() { 205 | 206 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 207 | aesSecretKey := "1234567812345678" 208 | base64Text, err := aes.AesEcbEncryptBase64([]byte(msg), []byte(aesSecretKey)) 209 | if err != nil { 210 | fmt.Println(err) 211 | return 212 | } 213 | fmt.Printf("AES的ECB模式加密后的base64密文为:\n%s\n", base64Text) 214 | plaintext, err := aes.AesEcbDecryptByBase64(base64Text, []byte(aesSecretKey)) 215 | if err != nil { 216 | fmt.Println(err) 217 | return 218 | } 219 | fmt.Printf("AES的ECB模式解密后:\n%s\n", string(plaintext)) 220 | 221 | /*AES的ECB模式加密后的base64密文为: 222 | piizmMYegn4S5xLmEPEdcixb4gmyq1OpncCkUzWU21kXe6N7SHjvbf5zvmeQ3FH2ZFEb2J21FTNpzVpHGaBNP7wr+6xw7Ucu3vTiAuzaIew= 223 | AES的ECB模式解密后: 224 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 225 | 226 | hexText, err := aes.AesEcbEncryptHex([]byte(msg), []byte(aesSecretKey)) 227 | if err != nil { 228 | fmt.Println(err) 229 | return 230 | } 231 | fmt.Printf("AES的ECB模式加密后的hex密文为:\n%s\n", hexText) 232 | plaintext, err = aes.AesEcbDecryptByHex(hexText, []byte(aesSecretKey)) 233 | if err != nil { 234 | fmt.Println(err) 235 | return 236 | } 237 | fmt.Printf("AES的ECB模式解密后:\n%s\n", string(plaintext)) 238 | 239 | /*AES的ECB模式加密后的hex密文为: 240 | a628b398c61e827e12e712e610f11d722c5be209b2ab53a99dc0a4533594db59177ba37b4878ef6dfe73be6790dc51f664511bd89db5153369cd5a4719a04d3fbc2bfbac70ed472edef4e202ecda21ec 241 | AES的ECB模式解密后: 242 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 243 | } 244 | ``` 245 | 246 | ## 3. 非对称加密RSA的快速使用 247 | 248 | ##### 非对称加密需要先生成一对公钥和私钥,公钥和私钥是成对出现的,公钥加密只能私钥解密,私钥签名只能公钥验签,(加密都是使用私钥加密,公钥解密,数字签名就是使用私钥签名消息的哈希,然后公钥验证签名) 249 | 250 | #### 3.1 使用 251 | 252 | 253 | ```go 254 | func main() { 255 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 256 | rsaBase64Key, err := rsa.GenerateRsaKeyBase64(1024) 257 | if err != nil { 258 | fmt.Println(err) 259 | return 260 | } 261 | base64Text, err := rsa.RsaEncryptToBase64([]byte(msg), rsaBase64Key.PublicKey) 262 | if err != nil { 263 | fmt.Println(err) 264 | return 265 | } 266 | fmt.Printf("rsa加密后的base64密文为:\n%s\n", base64Text) 267 | plaintext, err := rsa.RsaDecryptByBase64(base64Text, rsaBase64Key.PrivateKey) 268 | if err != nil { 269 | fmt.Println(err) 270 | return 271 | } 272 | fmt.Printf("rsa解密后:\n%s\n", string(plaintext)) 273 | 274 | /*rsa加密后的base64密文为: 275 | seAZe5Bojdp58eIf9hh5jf8PiIREr19IOXTc+re4z5crNR29mmXM6UFq5Uc1S53QLggL1+3nVNkA8AUnrw8jr4BM+oSqIvGqa92STz2XKcF7ukjTIakirWkOMRz3/dl8VIIucuJHedH7AOGtN1zhKVQbL3lejwq03J6cLEvz4WE= 276 | rsa解密后: 277 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 278 | 279 | base64Sign, err := rsa.RsaSignBase64([]byte(msg), rsaBase64Key.PrivateKey) 280 | if err != nil { 281 | fmt.Println(err) 282 | return 283 | } 284 | fmt.Printf("rsa签名的base64为:\n%s\n", base64Sign) 285 | res := rsa.RsaVerifySignBase64([]byte(msg), base64Sign, rsaBase64Key.PublicKey) 286 | fmt.Printf("rsa验签结果为:\n%v\n", res) 287 | 288 | /*rsa签名的base64为: 289 | cxe5nwMJB5dJwdvAmk7DPKSw46lL8mkwdhauwEWUXbcxKhh5EQN+ed/YTvTZh/yoWIQMKRqOlPszd6AnKA48Cy7Z5rfjj8rPobmYwGJzCkIWCCISZcaKYN5MOgLwRhyHSRwEwUcb3ZUdlj0QgCZHwleNq++FTtfTDwa9JuwWlSo= 290 | rsa验签结果为: 291 | true*/ 292 | } 293 | ``` 294 | 295 | ```go 296 | func main() { 297 | 298 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 299 | rsaHexKey, err := rsa.GenerateRsaKeyHex(1024) 300 | if err != nil { 301 | fmt.Println(err) 302 | return 303 | } 304 | HexText, err := rsa.RsaEncryptToHex([]byte(msg), rsaHexKey.PublicKey) 305 | if err != nil { 306 | fmt.Println(err) 307 | return 308 | } 309 | fmt.Printf("rsa加密后的Hex密文为:\n%s\n", HexText) 310 | plaintext, err := rsa.RsaDecryptByHex(HexText, rsaHexKey.PrivateKey) 311 | if err != nil { 312 | fmt.Println(err) 313 | return 314 | } 315 | fmt.Printf("rsa解密后:\n%s\n", string(plaintext)) 316 | 317 | /*rsa加密后的Hex密文为: 318 | 7ff6e0cb36bbb537ffdb142344cf3383a2878253b4123845a16d048c1c22ec5f5e474f6ae3dea15b7d791ded3d34379ccdd452dfd11a21ddd4b35864d97f46798396baeb404b7e0f85239f81f1ed6d7c5b69b5ca7e1590413b7332557f5e02333210c18ad0863f606ff4473cfa70fdfda12ea0f7e8559e304686bda7016a695c 319 | rsa解密后: 320 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 321 | 322 | hexSign, err := rsa.RsaSignHex([]byte(msg), rsaHexKey.PrivateKey) 323 | if err != nil { 324 | fmt.Println(err) 325 | return 326 | } 327 | fmt.Printf("rsa签名的hex为:\n%s\n", hexSign) 328 | res := rsa.RsaVerifySignHex([]byte(msg), hexSign, rsaHexKey.PublicKey) 329 | fmt.Printf("rsa验签结果为:\n%v\n", res) 330 | 331 | /*rsa签名的hex为: 332 | 48b2232ac4183ece8aa2f60393d27befff1e38a4d124cff97daa5877cd30d426ce8d78a2f13bab49e1964a340a35a8c90c8c0cca483ae2bba45e68523d32f0427d3c4f82c812fe79dc65d3729a6f9c45161ae00da955954e8d1b2e16a930d567fbe9fb3232e3c115d278e57397d073f0b8181f44ade76ce6bf548178d29bbf32 333 | rsa验签结果为: 334 | true 335 | */ 336 | } 337 | ``` 338 | 339 | 340 | > **RSA在非对称加密中使用比较广泛** 341 | > 342 | 343 | ## 4.ECC椭圆曲线应用 344 | 345 | **(GO里面只有ECC数字签名的接口,所以我们这里实现了ECC的数字签名功能,ECC椭圆曲线加密使用了区块链以太坊中的相关接口,ECC一般只签名使用加密一般不使用)** 346 | 347 | #### 4.1 ECC使用 348 | 349 | 350 | ```go 351 | func main() { 352 | 353 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 354 | eccBase64Key, err := ecc.GenerateEccKeyBase64() 355 | if err != nil { 356 | fmt.Println(err) 357 | return 358 | } 359 | base64Text, err := ecc.EccEncryptToBase64([]byte(msg), eccBase64Key.PublicKey) 360 | if err != nil { 361 | fmt.Println(err) 362 | return 363 | } 364 | fmt.Printf("ecc加密后的base64密文为:\n%s\n", base64Text) 365 | plaintext, err := ecc.EccDecryptByBase64(base64Text, eccBase64Key.PrivateKey) 366 | if err != nil { 367 | fmt.Println(err) 368 | return 369 | } 370 | fmt.Printf("ecc解密后:\n%s\n", string(plaintext)) 371 | 372 | /*ecc加密后的base64密文为: 373 | BAeEe7isXcDruhexWZixs0DqDJT4GUGEp9666ssgtgyixWpE4kxB/RsUbuFGR/eMA7ix+xJ9jet2glQVxUtPzRrLdmW6a31Dya0/bCb3WqpOsrGuC5MaZ3y6z0xkAbw1LGBVms6Ig/56JseK7jbOPCegvtgAO+5kESpjqptX6C/VynGyqEYDj/8PU0UnBwS2TFeAyG5rmwy1Z5P+kmbfNNfaIvKX4yODvJT4BdhATg9tUDkDDXw= 374 | ecc解密后: 375 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 376 | 377 | rSign, sSign, err := ecc.EccSignBase64([]byte(msg), eccBase64Key.PrivateKey) 378 | if err != nil { 379 | fmt.Println(err) 380 | return 381 | } 382 | fmt.Printf("ecc签名的为:\nrSign=%s\nsSign=%s\n", rSign, sSign) 383 | res := ecc.EccVerifySignBase64([]byte(msg), rSign, sSign, eccBase64Key.PublicKey) 384 | fmt.Printf("ecc验签结果为:\n%v\n", res) 385 | 386 | /*ecc签名的为: 387 | rSign=MzA3NTQyOTA4NzE0MzY1Nzg4MzU0OTkxNzk0NDIxODcyMTk4NjY0NzY5NzgzNDI5MjYxMjUwMTUxNjE1MzYzODM5MDI0ODMyNDg0MDU= 388 | sSign=MTUxMjc1NDAyMTY5NDE1NjY3MDU2ODU2ODk4MjcxNjcxMDMwNzAwODMyMjUwMjUwMTQ3MTU3NDY3NjgyNTEyODE2NDA5NzYwNTYxODQ= 389 | ecc验签结果为: 390 | true 391 | */ 392 | } 393 | ``` 394 | 395 | ```go 396 | func main() { 397 | 398 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 399 | eccHexKey, err := ecc.GenerateEccKeyHex() 400 | if err != nil { 401 | fmt.Println(err) 402 | return 403 | } 404 | hexText, err := ecc.EccEncryptToHex([]byte(msg), eccHexKey.PublicKey) 405 | if err != nil { 406 | fmt.Println(err) 407 | return 408 | } 409 | fmt.Printf("ecc加密后的hex密文为:\n%s\n", hexText) 410 | plaintext, err := ecc.EccDecryptByHex(hexText, eccHexKey.PrivateKey) 411 | if err != nil { 412 | fmt.Println(err) 413 | return 414 | } 415 | fmt.Printf("ecc解密后:\n%s\n", string(plaintext)) 416 | 417 | /*ecc加密后的hex密文为: 418 | 04689a2f57eee52e36d16fa8628353cdb8a13f2686597f6d6b45d1bcc0d4cd75be09562d9ff565879cb333ef16b3c21e2411035d8aaaaf7e2dedc1803a879ca1382d40202aa7122365d71091a4d0683c36fa291f6b1d4ef4b30359cd7bd9c3ae875dc20f2c5e0d33121f01768373ac8b8cecff84511b76331510982753787e38da9ccd6f9f78f46641882cfe08e81db8a7cc1bf9213a63824b3d6d8dddeeaee448cfa0990e1a85c628e23eb2b9b37628b10efcc27c4c 419 | ecc解密后: 420 | 床前明月光,疑是地上霜,举头望明月,低头思故乡*/ 421 | 422 | rSign, sSign, err := ecc.EccSignHex([]byte(msg), eccHexKey.PrivateKey) 423 | if err != nil { 424 | fmt.Println(err) 425 | return 426 | } 427 | fmt.Printf("ecc签名的为:\nrSign=%s\nsSign=%s\n", rSign, sSign) 428 | res := ecc.EccVerifySignHex([]byte(msg), rSign, sSign, eccHexKey.PublicKey) 429 | fmt.Printf("ecc验签结果为:\n%v\n", res) 430 | 431 | /*ecc签名的为: 432 | rSign=35333235363338393635343330383234313231383931333332313533373634353032373036323933363630343834303735383739313330343130353033383139333235373530363834323337 433 | sSign=3533383435343038323339303534363136303332373435323435353130343139313530393637383432373237333735323038333836353934343135343638363231383335383831373838323632 434 | ecc验签结果为: 435 | true 436 | 437 | */ 438 | } 439 | ``` 440 | 441 | 442 | ## 5.sha256和sha512 hmac 443 | 444 | ``` 445 | func main() { 446 | msg := "床前明月光,疑是地上霜,举头望明月,低头思故乡" 447 | fmt.Println(hash.Sha1Hex([]byte(msg))) 448 | fmt.Println(hash.Sha256Hex([]byte(msg))) 449 | fmt.Println(hash.Sha512Hex([]byte(msg))) 450 | 451 | // d2f1f816e0d40a1eb3f8aa60001f70a5b4ac21c4 452 | // 0f721dc0f0b9697a060c5541a389a7e5560e7b9a2dd3eca7f7688e477eee0243 453 | // f81bc5e4f057c28102adf27d31a98c5af8f259b213235225dce3b75815a4b76dccd0b181c7cb5347e118ab89b62542236d317dce584ce18c7c4a3c7f63fdaa52 454 | 455 | fmt.Println(hash.HmacSha256Hex([]byte("key"),msg)) 456 | fmt.Println(hash.HmacSha512Hex([]byte("key"),msg)) 457 | 458 | // e95c72fcfdd336559e6512198bc7b5d4f2c7c6ad2ece0f9e664548a809268904 459 | // 42603a67b53a572cdd6d8d4b8310ca8478391b4676822b66ccc473bf8d989b8f2d7afac8c75e7f7e9e723d2c8fbd7c575d897d6aba272dbfaaf903dfb750b323 460 | } 461 | } 462 | ``` 463 | 464 | 465 | 466 | 467 | -------------------------------------------------------------------------------- /rsa/rsa_test.go: -------------------------------------------------------------------------------- 1 | package rsa 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | var ( 10 | msg = "床前明月光,疑是地上霜,举头望明月,低头思故乡" 11 | base64PubKey1024 = "MIGJAoGBAL8Om9dxnaqfKarF4bewdCTXmymXt4K5FBf3FPT413bq/3zoAaHTWUfzNBmrcAW+rYr5tXDPD+WncqKqI9yo+zW+w+mgOOkSbQsGUDQuah5B4tRNBgV533w+ljSGM+7PxgOhapFyh2vwD/BGQ4GafrZeU2hyHXQDgfL95dfrsbI/AgMBAAE=" 12 | base64PriKey1024 = "MIICWwIBAAKBgQC/DpvXcZ2qnymqxeG3sHQk15spl7eCuRQX9xT0+Nd26v986AGh01lH8zQZq3AFvq2K+bVwzw/lp3KiqiPcqPs1vsPpoDjpEm0LBlA0LmoeQeLUTQYFed98PpY0hjPuz8YDoWqRcodr8A/wRkOBmn62XlNoch10A4Hy/eXX67GyPwIDAQABAoGAYgaDzOk9ROJ+xWDb65w8Kv74XEG8ZPTCq30ZIoteOWRfC14aIEZI45KTo6wDQN9ROSHfhu6mMGVWesEivz9wC4K/Qt5D0wxxQudx5NU8pHj9eDl5OIuWzk5YwjV92rDIl+b/XdeF3HqnphZzzbI9ad0PEbOH2v49wcEh4W7xDMkCQQDtY6vTCOM7faYzyJ5PRg39/sJRPgCyp9zD1VsYvX2Hb9pwpd7/tGWr6sVURACsGpO1fvzBFttrnEZ2dD83SunTAkEAzgkQQRalH/AAEbEZXnal6qmZC50f7dCAIF3i54MnzQsUgg/fcciWJcgz4+gRihtZxOiPVTJO4T0g/9waeeWGZQJAOZqpFEGg2kvIK+Kvv67RMGREhPBVvQSMxpycSWmZ72aODC3D6iq9TTVgAu2peBnO5AjXjodcYUV/t7jHqkQsbwJAAuU7tj50OZus1JLRkXNHZ6HUhcZCgZwRgOLw4mIEeCw0sJM6h6XS/lru58AGJxO1UkAWa5MWarHqOc5FDPt9xQJAU32KUvN2KbchqOqLKCP59dBDMQorv/Y8Ej7whQ//iBhO0APXBBzchM3D948+PRdL3R0be2jJ5eBJTdWNp3BsdQ==" 13 | base64PubKey2048 = "MIIBCgKCAQEA7MnuJs/PIF/lARA3P5KKLwul1sUnlQYBY0mZyi7dgIqDAbfOWAvfGMjryTOqiQ2D06hBKNc5BZXMtD5H3oipDUzGMbtlb+VwnX7xaqWDJlwH1/ZJ/IAkV8fBPukRNhNoeGSdTVPpS9oq3M9w3L1x71wgI77Lnv4lBGDvIi4Qc3etReErWIMrCbttRjv2zXTSJv9r9VCVBQcUJvQDf9Ad3eVwT6Q5iC9frJui8e1psYhfeiqhB2Wo4TUCKnU+6ZaYt3lHgJQ0RTGh0CssoCU56z6DZu9PjsReCNKhGBAN2S/KhrdbQHU+JQzMnNOBkdzfyzLSHz8+c3lgWSTx3uYfMQIDAQAB" 14 | base64PriKey2048 = "MIIEpQIBAAKCAQEA7MnuJs/PIF/lARA3P5KKLwul1sUnlQYBY0mZyi7dgIqDAbfOWAvfGMjryTOqiQ2D06hBKNc5BZXMtD5H3oipDUzGMbtlb+VwnX7xaqWDJlwH1/ZJ/IAkV8fBPukRNhNoeGSdTVPpS9oq3M9w3L1x71wgI77Lnv4lBGDvIi4Qc3etReErWIMrCbttRjv2zXTSJv9r9VCVBQcUJvQDf9Ad3eVwT6Q5iC9frJui8e1psYhfeiqhB2Wo4TUCKnU+6ZaYt3lHgJQ0RTGh0CssoCU56z6DZu9PjsReCNKhGBAN2S/KhrdbQHU+JQzMnNOBkdzfyzLSHz8+c3lgWSTx3uYfMQIDAQABAoIBAQC6Wb0UTG2M5As9B/8DCBe6KKeOW8Dn9j73XcArrzBhbiDmJDq/bjBYuB9gTEoE7F74Hy2Qr7jPnXHp1C4Jg3HP5sD/+KQ/KMm1GWdzb+jEMp91pf3aOxre/nUmRpRmA2YvgbeOWOB88qjS+GqxPmLBZrZgi1KCwS5uwL7SHoCR7XUb1YnGBD6sGKTPu6food58PkDBlpIk0W/9v8qjSoktwto4fR3onyWC39lEJRViYIZqBhRi0v2jByJLMGtHnFhByhNjQD8lRr+0LG5ih4PAhlwlA/Hw4jGfGQErE9GJhWVb+DZqicA8WDRWI9rowAK6s3mqV3NCq+LwcpqFnq1FAoGBAPn7PnwxZM3MVjIhLe2WT6ENQXXajYsmcweW/V8sDA0ZJi1rQH/nfeXodkjN9R5jmSAQpbTR9hKZv3EHUOfxKjOMIOHDylCxeDKcaqGt49lra/G5w5HZwbD2IUrwCCJ1bLiNotgeHV4ISGrbjUTFSwXikNaRc31hkSinKWSXnlk/AoGBAPJ9X6ebCPVZHWAmfzMUqQpV3t++togv+JmCM2wj+NCTId2G3dL2ZFfKj9ZbHLQTXwkehN22Ad4cMafHaKoO9t3CvSeVXuZYFD2oSIxrr86ym6exRS3P/bmZbXCuP2ry4Oax3yDec8vFjBFvRvT62rUU0kPpeauqvG1MgxbKL3uPAoGBAL8KwH0fLn+Mys7yxmvNNLvLKpzL0uJmFwDU5nvmaKtV7fRGA/v7yR58InGPXOXFjg+QSWNAFoOuljzmL3Giv/K3A6YmACbdChP7sA4xm3DchJkus4RyW3FHGLhxanYTMWx1ad8qXJ0xTU7EzViiQqyTsscYT5+hgdMEtUCYEr73AoGAZ1HsM+nnA0MZNSKyB/3BmNnFwOfttlFaR24moukg1x4Zy93vHjhFwPJaHydrL38hey05x44Jda3lqmtYuTzvCsYy+m62pMbauPq/DrXDjvqjP+xUYZTBsxcgfmaANv2Nvj4DqGmgRS7C45raTP+luIpKnQ0Z/n8dEiULpeY4HRkCgYEAs63wYb0EsFsAPTjYqiAo3n7MofaPbt2VvCG+6T6cNubHScA3vU1kah3YoxEhvQdAVUd5yC59+KfgINJitI9RjeOqULBpA22rFmVtQVaYlABRzrFW4gwPgZtuPoFr4th1fd+5CM4SxYffO9FtcpLUPx6COxLejgTNeo301r7TepE=" 15 | 16 | hexPubKey1024 = "30818902818100a751e464a258e5b55c3b3595a14c342d5f9f19e03ad09f814638ea67694a685bc3fc080a1f512473f47615ee2e392d3b31d7c7b03d6f9be3c9ff86c1ce462a3b772bfec18499b056ce81aef04968a74b3d4bdca820b1a20891889b5e46a7e20d6efa6c875f7240212f7b595e61abf989731e7b730f0a3d30b8c6d582cff13b4f0203010001" 17 | hexPriKey1024 = "3082025d02010002818100a751e464a258e5b55c3b3595a14c342d5f9f19e03ad09f814638ea67694a685bc3fc080a1f512473f47615ee2e392d3b31d7c7b03d6f9be3c9ff86c1ce462a3b772bfec18499b056ce81aef04968a74b3d4bdca820b1a20891889b5e46a7e20d6efa6c875f7240212f7b595e61abf989731e7b730f0a3d30b8c6d582cff13b4f020301000102818050cbf3cd40b44ae084143770f4fdd6685eb7768857fe6c37c1d0342911a813b2d475fcefde659183c8f5c8eb4638e805a0b10145b2b515832f050c6ec40c0fd1f56a83fdcca2182e738922cc07261dfe890a185e2f90f6739643b3213355de5e2e88309e211e09270620e2eb6c927948de04e4c92b6aa7397737b683336b4b59024100d49d78a609f3a88abcc61bf66cb592df8b0fa203900eccf64a7c3d417fa67dfd4afa86c18e5a8153e48136323d27147d77d8f96d3c8eaf56014a07c4c4bc02f5024100c9764d2815cd09ca70020b7ae2c5fbafc6637776a8bb91acf01a57b6f2420ceef9bf1c12bb39e97d0356edb96eeeccd53d3dbc5879f288923598e44585d842b3024100a224510cf6cbedbd9806d0ee55ab070e1963db9f31ee479a8fe53d65c4ee786881149b4de2bcdca1d8c23d4d84db57c1f372f18cbfc0e4b0071da8dd03578a3d02403798c43639bdf9e3ba017675953b99f7aa422ce7bc2cf748c8821c8eca505c0d5f32d4667ef0be74d78517d9c2b97821a8e2eea56412008a88ec06a3010aeb6d0241008955162a805c6275045e5865f7e6aa57a1523ae327596a2e2fbbf6b7025bff51339898962b1a14b3c8e5fd675163f7f3cae100d78cdf689f06987e09d2d1a241" 18 | hexPubKey2048 = "3082010a0282010100db8766d4dfc732b9a9b4ac1a243f9426cb0e65f75be04db5a7f0d50c799287eeac8216c8e3db510f974b7c150ec955260bbec8f89226e30f969e3505949cab1dbac6d333239332f82eeba33c64337b7704b29a118d1c19d15f84c810cf1ef3966c0584840ddcdbc04c361eafbb5bd5da67e93a39e6125eedd375f1ba28a95299cc2504d5a6073caeaf83b0e17b01eb9b4cddce80c34e97667cd7c2d31e88855759b454596ac83f3c3f5ea5e5ec1268d747595bf2c18790b9ee3622449b86c4c31bbf3ceacda8337741646e7e9415d9cbf26f468d125b7062f27f4fea7e63cb40e8104501efcb149fdfc9173c4720ed7594323d22c8d43213dadc5207c409e9e30203010001" 19 | hexPriKey2048 = "308204a30201000282010100db8766d4dfc732b9a9b4ac1a243f9426cb0e65f75be04db5a7f0d50c799287eeac8216c8e3db510f974b7c150ec955260bbec8f89226e30f969e3505949cab1dbac6d333239332f82eeba33c64337b7704b29a118d1c19d15f84c810cf1ef3966c0584840ddcdbc04c361eafbb5bd5da67e93a39e6125eedd375f1ba28a95299cc2504d5a6073caeaf83b0e17b01eb9b4cddce80c34e97667cd7c2d31e88855759b454596ac83f3c3f5ea5e5ec1268d747595bf2c18790b9ee3622449b86c4c31bbf3ceacda8337741646e7e9415d9cbf26f468d125b7062f27f4fea7e63cb40e8104501efcb149fdfc9173c4720ed7594323d22c8d43213dadc5207c409e9e302030100010282010041a76d099d2365f840d8d7dfb9978a274ff32e6b9bfea93efacafbec8f2f5397fddfaa10ca947cd9bcd5c67645c5d0c16021ded8f85cc8eb9090202b5b16bfd65455c234391f7ccedcb97c48436f622d662a44099bba1bbe926293b2f33ebe7aee33783e462717519b7954141a648cc094f31b86d558092bf761feb93e0fe5b3ab65b7d3bfdb855ffafd312662d78d4b6fc8c86d085ca2859dcea7c47455bf78ba1317a501bc3490b1463fca7e3ec5d8579139648d46696164803587ae8bba5f2f327d2a62a1b4faf3c3a530f3062af658cdd4bd87d04ecf1116c4e3350b060740d7217cf58d0dddf69ce034ff54dff0f9ac548f0d6ffc79507b7eb20c55f38102818100e0420eab79319069072f6d0df3bf6f94affdaf8d50caa1094579a2dd7750f9d9c8b54a5f981e2df99af607eaf09ffd69b74d3a5175f63fff6cb892132cd837a47c7dfe8843c90dfa77d0aa4f728a08f40d034f75c1d1baf9a2f7a96cd99babface9a162d287953d9297d6fd665633ff1f4db543982aaa2468445f2145fbc68f702818100fa99fc4f7b6ba6e5bb2c9bf80c3299a9723043074a43df58d2caee2e8bea973698fdf8bbd7a9fc31a37b694ecf05b2635b427419ff9099fa7b333e96867602a1f1fd29f21c355b07a5062b91a97fb8a5b11f4d4051d1edd81238fef7c45c5a62a3d3c67f36c89e2693411da7ece59a362ca5175d70ce86b1caed1cb1004e57750281804ce479713409d99119849a68e9459f75a4ee5fee1d608cdcc7f48ff24dc1f71944675ccbf03590dfffd1121fed477e356c434f96b4d2ad58e0275cf6b42ea2cd845e131317e2ed270f43fdd165dd8c7a59a7e3ebe57c0b172358b5bffbd113a3d8891ec777143abac02e2155aac7e01a0f31d0ec33305c99bf2ad87941e6313b02818100eb85370d182897a5872128c099ee205e90f3ecbaf8400bb3b6008493786a148d7a820e77b3fb8d0ab5e3b1982096f10dd1e205adbd73905349e0626d2397db678a3f6d619ec342774fd019b87f3d8b3325e10e4069e54b8c6babe76cc2be2d30515a224ec3150f15a0056db2b9c11c0ad8309c61f438157d190379989c7a04550281804a005d7aed10e75cf149a4645392fef8da4499904e947db0b0fd06faaa7eb3f39a7e4bdc997a654f009be62ca32893d7bde393fd0b2b81a06ea0f5504dea3438b23670765ba073dea1a669697c4d4f192cc68a9fe0a6cb35711535e859c36c8fa5e086cbd874e13b7cc0e8b018c21b72cff697e85a1ab7fad4a62af7458542cb" 20 | ) 21 | 22 | func TestRsaEncryptBase64(t *testing.T) { 23 | base64Key1024, err := GenerateRsaKeyBase64(1024) 24 | assert.Nil(t, err) 25 | base64Key2048, err := GenerateRsaKeyBase64(2048) 26 | assert.Nil(t, err) 27 | _, err = GenerateRsaKeyBase64(204811) 28 | assert.NotNil(t, err) 29 | 30 | // good 31 | base64CipherText, err := RsaEncryptToBase64([]byte(msg), base64Key1024.PublicKey) 32 | assert.Nil(t, err) 33 | // bad 34 | _, err = RsaEncryptToBase64([]byte(msg), "badkey") 35 | assert.NotNil(t, err) 36 | _, err = RsaEncryptToBase64([]byte(msg), hexPubKey1024) 37 | assert.NotNil(t, err) 38 | // good 39 | plainText, err := RsaDecryptByBase64(base64CipherText, base64Key1024.PrivateKey) 40 | assert.Nil(t, err) 41 | assert.Equal(t, string(plainText), msg) 42 | // bad priKey 43 | _, err = RsaDecryptByBase64(base64CipherText, "badPriKey") 44 | assert.NotNil(t, err) 45 | _, err = RsaDecryptByBase64(base64CipherText, base64Key2048.PublicKey) 46 | assert.NotNil(t, err) 47 | _, err = RsaDecryptByBase64(base64CipherText, base64Key2048.PrivateKey) 48 | assert.NotNil(t, err) 49 | _, err = RsaDecryptByBase64(base64CipherText, hexPriKey1024) 50 | assert.NotNil(t, err) 51 | _, err = RsaDecryptByBase64(base64CipherText, hexPriKey2048) 52 | assert.NotNil(t, err) 53 | _, err = RsaDecryptByBase64(base64CipherText, hexPubKey1024) 54 | assert.NotNil(t, err) 55 | _, err = RsaDecryptByBase64("badtext", base64Key1024.PrivateKey) 56 | assert.NotNil(t, err) 57 | 58 | // good 59 | base64CipherText, err = RsaEncryptToBase64([]byte(msg), base64Key2048.PublicKey) 60 | assert.Nil(t, err) 61 | plainText, err = RsaDecryptByBase64(base64CipherText, base64Key2048.PrivateKey) 62 | assert.Nil(t, err) 63 | assert.Equal(t, string(plainText), msg) 64 | 65 | // good 66 | base64CipherText, err = RsaEncryptToBase64([]byte(msg), base64PubKey1024) 67 | assert.Nil(t, err) 68 | plainText, err = RsaDecryptByBase64(base64CipherText, base64PriKey1024) 69 | assert.Nil(t, err) 70 | assert.Equal(t, string(plainText), msg) 71 | 72 | // good 73 | base64CipherText, err = RsaEncryptToBase64([]byte(msg), base64PubKey2048) 74 | assert.Nil(t, err) 75 | plainText, err = RsaDecryptByBase64(base64CipherText, base64PriKey2048) 76 | assert.Nil(t, err) 77 | assert.Equal(t, string(plainText), msg) 78 | } 79 | 80 | func TestRsaEncryptHex(t *testing.T) { 81 | hexKey1024, err := GenerateRsaKeyHex(1024) 82 | assert.Nil(t, err) 83 | hexKey2048, err := GenerateRsaKeyHex(2048) 84 | assert.Nil(t, err) 85 | _, err = GenerateRsaKeyHex(2048111) 86 | assert.NotNil(t, err) 87 | 88 | // good 89 | hexCipherText, err := RsaEncryptToHex([]byte(msg), hexKey1024.PublicKey) 90 | assert.Nil(t, err) 91 | // bad 92 | _, err = RsaEncryptToHex([]byte(msg), "badkey") 93 | assert.NotNil(t, err) 94 | // good 95 | plainText, err := RsaDecryptByHex(hexCipherText, hexKey1024.PrivateKey) 96 | assert.Nil(t, err) 97 | assert.Equal(t, string(plainText), msg) 98 | // bad 99 | _, err = RsaDecryptByHex(hexCipherText, "badkey") 100 | assert.NotNil(t, err) 101 | // bad priKey 102 | _, err = RsaDecryptByHex(hexCipherText, hexPriKey2048) 103 | assert.NotNil(t, err) 104 | _, err = RsaDecryptByHex(hexCipherText, hexPriKey1024) 105 | assert.NotNil(t, err) 106 | _, err = RsaDecryptByHex(hexCipherText, base64PriKey2048) 107 | assert.NotNil(t, err) 108 | _, err = RsaDecryptByHex(hexCipherText, base64PriKey1024) 109 | assert.NotNil(t, err) 110 | _, err = RsaDecryptByHex("ssss", hexKey1024.PrivateKey) 111 | assert.NotNil(t, err) 112 | 113 | // good 114 | hexCipherText, err = RsaEncryptToHex([]byte(msg), hexKey2048.PublicKey) 115 | assert.Nil(t, err) 116 | plainText, err = RsaDecryptByHex(hexCipherText, hexKey2048.PrivateKey) 117 | assert.Nil(t, err) 118 | assert.Equal(t, string(plainText), msg) 119 | 120 | // good 121 | hexCipherText, err = RsaEncryptToHex([]byte(msg), hexPubKey1024) 122 | assert.Nil(t, err) 123 | plainText, err = RsaDecryptByHex(hexCipherText, hexPriKey1024) 124 | assert.Nil(t, err) 125 | assert.Equal(t, string(plainText), msg) 126 | 127 | // good 128 | hexCipherText, err = RsaEncryptToHex([]byte(msg), hexPubKey2048) 129 | assert.Nil(t, err) 130 | plainText, err = RsaDecryptByHex(hexCipherText, hexPriKey2048) 131 | assert.Nil(t, err) 132 | assert.Equal(t, string(plainText), msg) 133 | 134 | } 135 | 136 | func TestRsaSignBase64(t *testing.T) { 137 | base64Key1024, err := GenerateRsaKeyBase64(1024) 138 | assert.Nil(t, err) 139 | base64Key2048, err := GenerateRsaKeyBase64(2048) 140 | assert.Nil(t, err) 141 | _, err = GenerateRsaKeyBase64(204811) 142 | assert.NotNil(t, err) 143 | 144 | base64Sign1024, err := RsaSignBase64([]byte(msg), base64Key1024.PrivateKey) 145 | assert.Nil(t, err) 146 | _, err = RsaSignBase64([]byte(msg), hexPriKey2048) 147 | assert.NotNil(t, err) 148 | res := RsaVerifySignBase64([]byte(msg), base64Sign1024, base64Key1024.PublicKey) 149 | assert.Equal(t, res, true) 150 | res = RsaVerifySignBase64([]byte(msg), base64Sign1024, base64Key2048.PublicKey) 151 | assert.Equal(t, res, false) 152 | res = RsaVerifySignBase64([]byte(msg), "11111", "badpubkey") 153 | assert.Equal(t, res, false) 154 | res = RsaVerifySignBase64([]byte(msg), "11111", base64Key1024.PublicKey) 155 | assert.Equal(t, res, false) 156 | res = RsaVerifySignBase64([]byte(msg), base64Sign1024, base64Key2048.PublicKey) 157 | assert.Equal(t, res, false) 158 | 159 | base64Sign2048, err := RsaSignBase64([]byte(msg), base64Key2048.PrivateKey) 160 | assert.Nil(t, err) 161 | res = RsaVerifySignBase64([]byte(msg), base64Sign2048, base64Key2048.PublicKey) 162 | assert.Equal(t, res, true) 163 | res = RsaVerifySignBase64([]byte(msg), base64Sign2048, base64Key1024.PublicKey) 164 | assert.Equal(t, res, false) 165 | res = RsaVerifySignBase64([]byte(msg), "11111", "badpubkey") 166 | assert.Equal(t, res, false) 167 | res = RsaVerifySignBase64([]byte(msg), base64Sign2048, base64Key1024.PublicKey) 168 | assert.Equal(t, res, false) 169 | res = RsaVerifySignBase64([]byte(msg), base64Sign2048, base64Key1024.PrivateKey) 170 | assert.Equal(t, res, false) 171 | res = RsaVerifySignBase64([]byte(msg), base64Sign2048, base64Key2048.PrivateKey) 172 | assert.Equal(t, res, false) 173 | 174 | } 175 | 176 | func TestRsaSignHex(t *testing.T) { 177 | hexKey1024, err := GenerateRsaKeyHex(1024) 178 | assert.Nil(t, err) 179 | hexKey2048, err := GenerateRsaKeyHex(2048) 180 | assert.Nil(t, err) 181 | _, err = GenerateRsaKeyHex(2048111) 182 | assert.NotNil(t, err) 183 | 184 | hexSign1024, err := RsaSignHex([]byte(msg), hexKey1024.PrivateKey) 185 | assert.Nil(t, err) 186 | _, err = RsaSignHex([]byte(msg), hexKey1024.PublicKey) 187 | assert.NotNil(t, err) 188 | res := RsaVerifySignHex([]byte(msg), hexSign1024, hexKey1024.PublicKey) 189 | assert.Equal(t, res, true) 190 | res = RsaVerifySignHex([]byte(msg), hexSign1024, hexKey2048.PublicKey) 191 | assert.Equal(t, res, false) 192 | res = RsaVerifySignHex([]byte(msg), "11111", "badpubkey") 193 | assert.Equal(t, res, false) 194 | res = RsaVerifySignHex([]byte(msg), "282010100db", hexKey1024.PublicKey) 195 | assert.Equal(t, res, false) 196 | res = RsaVerifySignHex([]byte(msg), hexSign1024, hexKey2048.PublicKey) 197 | assert.Equal(t, res, false) 198 | 199 | hexSign2048, err := RsaSignHex([]byte(msg), hexKey2048.PrivateKey) 200 | assert.Nil(t, err) 201 | _, err = RsaSignHex([]byte(msg), hexPubKey2048) 202 | assert.NotNil(t, err) 203 | res = RsaVerifySignHex([]byte(msg), hexSign2048, hexKey2048.PublicKey) 204 | assert.Equal(t, res, true) 205 | res = RsaVerifySignHex([]byte(msg), hexSign2048, hexKey1024.PublicKey) 206 | assert.Equal(t, res, false) 207 | res = RsaVerifySignHex([]byte(msg), "0a0282010100d", "badpubkey") 208 | assert.Equal(t, res, false) 209 | res = RsaVerifySignHex([]byte(msg), "0a0282010100d", hexKey1024.PublicKey) 210 | assert.Equal(t, res, false) 211 | res = RsaVerifySignHex([]byte(msg), "xxxx", "badpubkey") 212 | assert.Equal(t, res, false) 213 | res = RsaVerifySignHex([]byte(msg), hexSign2048, hexKey1024.PublicKey) 214 | assert.Equal(t, res, false) 215 | res = RsaVerifySignHex([]byte(msg), hexSign2048, hexKey1024.PrivateKey) 216 | assert.Equal(t, res, false) 217 | res = RsaVerifySignHex([]byte(msg), hexSign2048, hexKey2048.PrivateKey) 218 | assert.Equal(t, res, false) 219 | 220 | } 221 | --------------------------------------------------------------------------------