├── go.mod ├── image ├── md5.png ├── sha1.png ├── aes_encrypt.png ├── des_encrypt.png ├── rsa_encrypt.png └── triple_des_encrypt.png ├── testdata ├── pub.txt └── pri.txt ├── errors.go ├── output.go ├── tripledes.go ├── md5.go ├── md5_test.go ├── des.go ├── mode.go ├── aes.go ├── sha.go ├── rsa.go ├── example_test.go ├── crypto.go ├── README.md └── LICENSE /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/marspere/goencrypt 2 | 3 | go 1.13 4 | -------------------------------------------------------------------------------- /image/md5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/md5.png -------------------------------------------------------------------------------- /image/sha1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/sha1.png -------------------------------------------------------------------------------- /image/aes_encrypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/aes_encrypt.png -------------------------------------------------------------------------------- /image/des_encrypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/des_encrypt.png -------------------------------------------------------------------------------- /image/rsa_encrypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/rsa_encrypt.png -------------------------------------------------------------------------------- /image/triple_des_encrypt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/marspere/goencrypt/HEAD/image/triple_des_encrypt.png -------------------------------------------------------------------------------- /testdata/pub.txt: -------------------------------------------------------------------------------- 1 | -----BEGIN PUBLIC KEY----- 2 | MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHYEumvLp/7ZJeR6Q0P2dQ+amsYQ 3 | i87QJxuG/acF1uz7S+hcWjQ7LsqRn/xITGe3H1DiL3R+qZa9G5iUTlCWKXsNnumf 4 | dGQdp8hePLgcXfOrCvryd8z6X8C7yhu5EsuRcvOS2Zk0jIvVCeSjv3chX/ZnNEjR 5 | b9lestbKMHHtPFrTAgMBAAE= 6 | -----END PUBLIC KEY----- -------------------------------------------------------------------------------- /errors.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "errors" 5 | "strings" 6 | ) 7 | 8 | const runtimeErr = "runtime error:" 9 | 10 | func handleError(err error) error { 11 | if strings.HasPrefix(err.Error(), runtimeErr) { 12 | return errors.New("encrypted and decrypted passwords are inconsistent") 13 | } 14 | return err 15 | } 16 | -------------------------------------------------------------------------------- /output.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "encoding/base64" 5 | "encoding/hex" 6 | ) 7 | 8 | type CipherText []byte 9 | 10 | const ( 11 | PrintHex = iota 12 | PrintBase64 13 | ) 14 | 15 | func (ct CipherText) hexEncode() string { 16 | return hex.EncodeToString(ct) 17 | } 18 | 19 | func (ct CipherText) base64Encode() string { 20 | return base64.StdEncoding.EncodeToString(ct) 21 | } 22 | 23 | func hexDecode(cipherText string) ([]byte, error) { 24 | return hex.DecodeString(cipherText) 25 | } 26 | 27 | func base64Decode(cipherText string) ([]byte, error) { 28 | return base64.StdEncoding.DecodeString(cipherText) 29 | } 30 | -------------------------------------------------------------------------------- /testdata/pri.txt: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIICWwIBAAKBgHYEumvLp/7ZJeR6Q0P2dQ+amsYQi87QJxuG/acF1uz7S+hcWjQ7 3 | LsqRn/xITGe3H1DiL3R+qZa9G5iUTlCWKXsNnumfdGQdp8hePLgcXfOrCvryd8z6 4 | X8C7yhu5EsuRcvOS2Zk0jIvVCeSjv3chX/ZnNEjRb9lestbKMHHtPFrTAgMBAAEC 5 | gYBM5Fm9X8wNq9cXXF01C39LclSC1UbxsQa51aKvzoswja3wLzOKMkETM/wDd+tn 6 | 65SYszVt9hRyJLW1HHNF6AAPzGf4RdbL2zAqYfPf2YT+98M5ji+byaF7BQQA9ZN4 7 | MlfA+HiqHauNNW/WaZNAXbDfkde4Ag+o715wMpyLE+IfUQJBALkOE1SVlv2U0ISa 8 | 2enuulyfxleQyZ9DiUzEQ6OsSBpiN3kGdUmqOfsJPu+gVqrzn91TY3D6LF4g3UVo 9 | UBMklJkCQQCjQ3YuMZIEJCE2SmCgNMoJwGxJ1jtjVBD50Ug1B6ef9GX7FQ6MNjiL 10 | eUhjSW/lkMbgjZcMJ08nuWvgLx443KJLAkBoFVegAocrV5E0lFgusFxXjnIjfEc6 11 | 8eR+rgERROxFEqr6wjwj07/Kx3eDld5JRr/K34UV3VApHTj3OeWX7sI5AkAmc34C 12 | 9SPJm+TCj5PgR26KC2q1nSIRi7wPyi1yZ+IftwTJtLTfaum4V5En6STUcVuViWNY 13 | tm1bEr2IaDB6/eOvAkEAqbZMNtyWX+D3QybU0XTkAcDW02W0d/6oVVEWawAWxnSD 14 | WvBdaF15QQabm1avsQp/DdOcZYwEdMoVgYY8o6sAGw== 15 | -----END RSA PRIVATE KEY----- -------------------------------------------------------------------------------- /tripledes.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/des" 5 | "errors" 6 | ) 7 | 8 | func (c *CipherDES) TripleDESEncrypt(plainText []byte) (cipherText string, err error) { 9 | block, err := des.NewTripleDESCipher(c.Key) 10 | if err != nil { 11 | return 12 | } 13 | plainData := c.Fill(plainText, block.BlockSize()) 14 | if plainData == nil { 15 | err = errors.New("unsupported content to be encrypted") 16 | return 17 | } 18 | if err = c.Encrypt(block, plainData); err != nil { 19 | return 20 | } 21 | return c.Encode(), nil 22 | } 23 | 24 | func (c *CipherDES) TripleDESDecrypt(cipherText string) (plainText string, err error) { 25 | cipherData, err := c.Decode(cipherText) 26 | if err != nil { 27 | return 28 | } 29 | block, err := des.NewTripleDESCipher(c.Key) 30 | if err != nil { 31 | return 32 | } 33 | if err = c.Decrypt(block, cipherData); err != nil { 34 | return 35 | } 36 | plainData, err := c.UnFill(c.Output) 37 | if err != nil { 38 | return "", handleError(err) 39 | } 40 | return string(plainData), nil 41 | } 42 | -------------------------------------------------------------------------------- /md5.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/md5" 5 | "encoding/hex" 6 | "errors" 7 | "strings" 8 | ) 9 | 10 | type MessageDigest string 11 | 12 | // MD5 information summary, the src has two types: []byte or string 13 | // The default return value is 32-bit lowercase. 14 | func MD5(src interface{}) (md MessageDigest, err error) { 15 | h := md5.New() 16 | value, ok := src.(string) 17 | if !ok { 18 | value1, ok := src.([]byte) 19 | if !ok { 20 | return md, errors.New("unsupported type") 21 | } 22 | if _, err = h.Write(value1); err != nil { 23 | return 24 | } 25 | md = MessageDigest(hex.EncodeToString(h.Sum(nil))) 26 | return 27 | } 28 | if _, err = h.Write([]byte(value)); err != nil { 29 | return 30 | } 31 | md = MessageDigest(hex.EncodeToString(h.Sum(nil))) 32 | return 33 | } 34 | 35 | func (md MessageDigest) UpperCase32() string { 36 | return strings.ToUpper(string(md)) 37 | } 38 | 39 | func (md MessageDigest) UpperCase16() string { 40 | value := md[8:24] 41 | return strings.ToUpper(string(value)) 42 | } 43 | 44 | func (md MessageDigest) LowerCase16() string { 45 | return string(md[8:24]) 46 | } -------------------------------------------------------------------------------- /md5_test.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import "testing" 4 | 5 | type testPair struct { 6 | in interface{} 7 | out string 8 | } 9 | 10 | var pairs = []testPair{ 11 | {"hello world", "5eb63bbbe01eeed093cb22bb8f5acdc3"}, 12 | {123456789, ""}, 13 | {[]byte("hello world"), "5eb63bbbe01eeed093cb22bb8f5acdc3"}, 14 | } 15 | 16 | func TestMD5(t *testing.T) { 17 | for _, p := range pairs { 18 | out, _ := MD5(p.in) 19 | if string(out) != p.out { 20 | t.Errorf("bad return value: got: %s want: %s", string(out), p.out) 21 | } 22 | } 23 | } 24 | 25 | func BenchmarkMD5(b *testing.B) { 26 | for i := 0; i < b.N; i++ { 27 | if i%3 == 0 { 28 | out, _ := MD5(pairs[0].in) 29 | if string(out) != pairs[0].out { 30 | b.Errorf("bad return value: got: %s want: %s", string(out), pairs[0].out) 31 | } 32 | } else if i%3 == 1 { 33 | out, _ := MD5(pairs[1].in) 34 | if string(out) != pairs[1].out { 35 | b.Errorf("bad return value: got: %s want: %s", string(out), pairs[1].out) 36 | } 37 | } else { 38 | out, _ := MD5(pairs[2].in) 39 | if string(out) != pairs[2].out { 40 | b.Errorf("bad return value: got: %s want: %s", string(out), pairs[2].out) 41 | } 42 | } 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /des.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/des" 5 | "errors" 6 | ) 7 | 8 | type CipherDES struct { 9 | Cipher 10 | } 11 | 12 | func NewDESCipher(key, iv []byte, groupMode int, fillMode FillMode, decodeType int) *CipherDES { 13 | return &CipherDES{ 14 | Cipher{ 15 | GroupMode: groupMode, 16 | FillMode: fillMode, 17 | DecodeType: decodeType, 18 | Key: key, 19 | Iv: iv, 20 | }, 21 | } 22 | } 23 | 24 | func (c *CipherDES) DESEncrypt(plainText []byte) (cipherText string, err error) { 25 | block, err := des.NewCipher(c.Key) 26 | if err != nil { 27 | return 28 | } 29 | plainData := c.Fill(plainText, block.BlockSize()) 30 | if plainData == nil { 31 | err = errors.New("unsupported content to be encrypted") 32 | return 33 | } 34 | if err = c.Encrypt(block, plainData); err != nil { 35 | return 36 | } 37 | return c.Encode(), nil 38 | } 39 | 40 | func (c *CipherDES) DESDecrypt(cipherText string) (plainText string, err error) { 41 | cipherData, err := c.Decode(cipherText) 42 | if err != nil { 43 | return 44 | } 45 | block, err := des.NewCipher(c.Key) 46 | if err != nil { 47 | return 48 | } 49 | if err = c.Decrypt(block, cipherData); err != nil { 50 | return 51 | } 52 | plainData, err := c.UnFill(c.Output) 53 | if err != nil { 54 | return "", handleError(err) 55 | } 56 | return string(plainData), nil 57 | } 58 | -------------------------------------------------------------------------------- /mode.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import "bytes" 4 | 5 | const ( 6 | CBCMode = iota 7 | CFBMode 8 | CTRMode 9 | ECBMode 10 | OFBMode 11 | ) 12 | 13 | type FillMode int 14 | 15 | const ( 16 | PkcsZero FillMode = iota 17 | Pkcs7 18 | ) 19 | 20 | // The blockSize argument should be 16, 24, or 32. 21 | // Corresponding AES-128, AES-192, or AES-256. 22 | func (fm FillMode) pkcs7Padding(plainText []byte, blockSize int) []byte { 23 | paddingSize := blockSize - len(plainText)%blockSize 24 | paddingText := bytes.Repeat([]byte{byte(paddingSize)}, paddingSize) 25 | return append(plainText, paddingText...) 26 | } 27 | 28 | func (fm FillMode) pkcsUnPadding(plainText []byte) []byte { 29 | length := len(plainText) 30 | number := int(plainText[length-1]) 31 | return plainText[:length-number] 32 | } 33 | 34 | func (fm FillMode) zeroPadding(plainText []byte, blockSize int) []byte { 35 | if plainText[len(plainText)-1] == 0 { 36 | return nil 37 | } 38 | paddingSize := blockSize - len(plainText)%blockSize 39 | paddingText := bytes.Repeat([]byte{byte(0)}, paddingSize) 40 | return append(plainText, paddingText...) 41 | } 42 | 43 | func (fm FillMode) unZeroPadding(plainText []byte) []byte { 44 | length := len(plainText) 45 | count := 1 46 | for i := length - 1; i > 0; i-- { 47 | if plainText[i] == 0 && plainText[i-1] == plainText[i] { 48 | count++ 49 | } 50 | } 51 | return plainText[:length-count] 52 | } 53 | -------------------------------------------------------------------------------- /aes.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/aes" 5 | "errors" 6 | "strconv" 7 | ) 8 | 9 | type CipherAES struct { 10 | Cipher 11 | } 12 | 13 | const BlockSize = 16 14 | 15 | func NewAESCipher(key, iv []byte, groupMode int, fillMode FillMode, decodeType int) (*CipherAES, error) { 16 | if len(iv) != BlockSize { 17 | return nil, errors.New("IV length must equal block size") 18 | } 19 | if len(key) != 16 && len(key) != 24 && len(key) != 32 { 20 | return nil, errors.New("crypto/aes: invalid key size " + strconv.Itoa(len(key))) 21 | } 22 | return &CipherAES{Cipher{ 23 | GroupMode: groupMode, 24 | FillMode: fillMode, 25 | DecodeType: decodeType, 26 | Key: key, 27 | Iv: iv, 28 | }, 29 | }, nil 30 | } 31 | 32 | func (c *CipherAES) AESEncrypt(plainText []byte) (cipherText string, err error) { 33 | block, err := aes.NewCipher(c.Key) 34 | if err != nil { 35 | return 36 | } 37 | plainData := c.Fill(plainText, block.BlockSize()) 38 | if plainData == nil { 39 | err = errors.New("unsupported content to be encrypted") 40 | return 41 | } 42 | c.Output = make(CipherText, len(plainData)) 43 | if err = c.Encrypt(block, plainData); err != nil { 44 | return 45 | } 46 | return c.Encode(), nil 47 | } 48 | 49 | func (c *CipherAES) AESDecrypt(cipherText string) (plainText string, err error) { 50 | cipherData, err := c.Decode(cipherText) 51 | if err != nil { 52 | return 53 | } 54 | block, err := aes.NewCipher(c.Key) 55 | if err != nil { 56 | return 57 | } 58 | if len(cipherData)%block.BlockSize() != 0 { 59 | err = errors.New("cipher text is not a multiple of the block size") 60 | return 61 | } 62 | if err = c.Decrypt(block, cipherData); err != nil { 63 | return 64 | } 65 | plainData, err := c.UnFill(c.Output) 66 | if err != nil { 67 | return "", handleError(err) 68 | } 69 | return string(plainData), nil 70 | } 71 | -------------------------------------------------------------------------------- /sha.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/sha1" 5 | "crypto/sha256" 6 | "crypto/sha512" 7 | "encoding/base64" 8 | "encoding/hex" 9 | "errors" 10 | "hash" 11 | "io" 12 | "os" 13 | ) 14 | 15 | const ( 16 | SHA1 = iota 17 | SHA256 18 | SHA512 19 | ) 20 | 21 | // SHA implements several hash functions, including sha1, sha256, and sha512. 22 | // Meanwhile, SHA supports file hash. 23 | // When content type is string, it indicates the address of the file. 24 | // decodeType represents the print format, and the result is not encrypted by default. 25 | func SHA(length int, content interface{}, decodeType int) (result string, err error) { 26 | var h hash.Hash 27 | if length == SHA1 { 28 | h = sha1.New() 29 | } else if length == SHA256 { 30 | h = sha256.New() 31 | } else if length == SHA512 { 32 | h = sha512.New() 33 | } else { 34 | return "", errors.New("crypto/sha: unsupported hash algorithm") 35 | } 36 | switch content.(type) { 37 | case []byte: 38 | return shaToString(h, content.([]byte), decodeType) 39 | default: 40 | return shaFileToString(h, content.(string), decodeType) 41 | } 42 | } 43 | 44 | func shaFileToString(h hash.Hash, file string, decodeType int) (string, error) { 45 | f, err := os.Open(file) 46 | if err != nil { 47 | return "", err 48 | } 49 | defer f.Close() 50 | if _, err = io.Copy(h, f); err != nil { 51 | return "", err 52 | } 53 | return shaEncode(h.Sum(nil), decodeType) 54 | } 55 | 56 | func shaToString(h hash.Hash, content []byte, decodeType int) (result string, err error) { 57 | _, err = h.Write(content) 58 | if err != nil { 59 | return 60 | } 61 | return shaEncode(h.Sum(nil), decodeType) 62 | } 63 | 64 | func shaEncode(content []byte, decodeType int) (res string, err error) { 65 | if decodeType == PrintHex { 66 | return hex.EncodeToString(content), nil 67 | } 68 | if decodeType == PrintBase64 { 69 | return base64.StdEncoding.EncodeToString(content), nil 70 | } 71 | return string(content), nil 72 | } 73 | -------------------------------------------------------------------------------- /rsa.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/rand" 5 | "crypto/rsa" 6 | "crypto/x509" 7 | "encoding/pem" 8 | "errors" 9 | "io/ioutil" 10 | 11 | ) 12 | 13 | type CipherRSA struct { 14 | PubKey string 15 | PriKey string 16 | Cipher 17 | } 18 | 19 | // New returns a CipherRSA pointer, the keyFile parameters is address of 20 | // public key or private key. 21 | // If the length of keyFile is 1, which means RSA encryption. 22 | // If the length of keyFile greater than 1, which means RSA decryption. 23 | // Meanwhile, the second element of keyFile represents private key. 24 | func NewRSACipher(decodeType int, keyFile ...string) *CipherRSA { 25 | if len(keyFile) > 1 { 26 | return &CipherRSA{ 27 | keyFile[0], 28 | keyFile[1], 29 | Cipher{ 30 | DecodeType: decodeType, 31 | }, 32 | } 33 | } else { 34 | return &CipherRSA{ 35 | keyFile[0], 36 | "", 37 | Cipher{ 38 | DecodeType: decodeType, 39 | }, 40 | } 41 | } 42 | } 43 | 44 | // Encrypt encrypts the given message with RSA and the padding 45 | // scheme from PKCS#1 v1.5. 46 | func (cr *CipherRSA) RSAEncrypt(plainText []byte) (cipherText string, err error) { 47 | data, err := ioutil.ReadFile(cr.PubKey) 48 | if err != nil { 49 | return 50 | } 51 | block, _ := pem.Decode(data) 52 | if block == nil { 53 | return "", errors.New("public key error") 54 | } 55 | pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) 56 | if err != nil { 57 | return 58 | } 59 | cr.Output, err = rsa.EncryptPKCS1v15(rand.Reader, pubKey.(*rsa.PublicKey), plainText) 60 | if err != nil { 61 | return 62 | } 63 | return cr.Encode(), nil 64 | } 65 | 66 | // Decrypt parses the given message with RSA private key in PKCS#1, ASN.1 DER form. 67 | func (cr *CipherRSA) RSADecrypt(cipherText string) (plainText string, err error) { 68 | data, err := ioutil.ReadFile(cr.PriKey) 69 | if err != nil { 70 | return 71 | } 72 | block, _ := pem.Decode(data) 73 | if block == nil { 74 | return "", errors.New("private key error") 75 | } 76 | priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) 77 | if err != nil { 78 | return 79 | } 80 | cipherData, err := cr.Decode(cipherText) 81 | if err != nil { 82 | return 83 | } 84 | plainData, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, cipherData) 85 | if err != nil { 86 | return 87 | } 88 | return string(plainData), nil 89 | } 90 | -------------------------------------------------------------------------------- /example_test.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import "fmt" 4 | 5 | const defaultPublicFile = "./testdata/pub.txt" 6 | const defaultPrivateFile = "./testdata/pri.txt" 7 | 8 | func ExampleRSAEncryptAndDecrypt() { 9 | // rsa encryption 10 | cipher := NewRSACipher(PrintBase64, defaultPublicFile, defaultPrivateFile) 11 | cipherText, err := cipher.RSAEncrypt([]byte("hello world")) 12 | if err != nil { 13 | fmt.Println(err) 14 | return 15 | } 16 | fmt.Println(cipherText) 17 | 18 | // rsa decryption 19 | plainText, err := cipher.RSADecrypt(cipherText) 20 | if err != nil { 21 | fmt.Println(err) 22 | return 23 | } 24 | fmt.Println(plainText) 25 | } 26 | 27 | func ExampleAESEncryptAndDecrypt() { 28 | // aes decryption 29 | cipher, err := NewAESCipher([]byte("0123456789asdfgh"), []byte("0123456789asdfgh"), CBCMode, Pkcs7, PrintBase64) 30 | if err != nil { 31 | fmt.Println(err) 32 | return 33 | } 34 | cipherText, err := cipher.AESEncrypt([]byte("hello world")) 35 | if err != nil { 36 | fmt.Println(err) 37 | return 38 | } 39 | fmt.Println(cipherText) 40 | 41 | // aes decryption 42 | plainText, err := cipher.AESDecrypt(cipherText) 43 | if err != nil { 44 | fmt.Println(err) 45 | return 46 | } 47 | fmt.Println(plainText) 48 | } 49 | 50 | func ExampleDESEncryptAndDecrypt() { 51 | // des encryption 52 | cipher := NewDESCipher([]byte("12345678"), []byte(""), ECBMode, Pkcs7, PrintBase64) 53 | cipherText, err := cipher.DESEncrypt([]byte("hello world")) 54 | if err != nil { 55 | fmt.Println(err) 56 | return 57 | } 58 | fmt.Println(cipherText) 59 | 60 | // des decryption 61 | plainText, err := cipher.DESDecrypt(cipherText) 62 | if err != nil { 63 | fmt.Println(err) 64 | return 65 | } 66 | fmt.Println(plainText) 67 | } 68 | 69 | func ExampleTripleDESEncryptAndDecrypt() { 70 | // triple des encryption 71 | cipher := NewDESCipher([]byte("12345678abcdefghijklmnop"), []byte("abcdefgh"), CBCMode, Pkcs7, PrintBase64) 72 | cipherText, err := cipher.TripleDESEncrypt([]byte("hello world")) 73 | if err != nil { 74 | fmt.Println(err) 75 | return 76 | } 77 | fmt.Println(cipherText) 78 | 79 | // triple des decryption 80 | plainText, err := cipher.TripleDESDecrypt(cipherText) 81 | if err != nil { 82 | fmt.Println(err) 83 | return 84 | } 85 | fmt.Println(plainText) 86 | } 87 | 88 | func ExampleSHA() { 89 | result, err := SHA(SHA1, []byte("hello world"), PrintHex) 90 | if err != nil { 91 | fmt.Println(err) 92 | return 93 | } 94 | fmt.Println(result) 95 | } 96 | -------------------------------------------------------------------------------- /crypto.go: -------------------------------------------------------------------------------- 1 | package goencrypt 2 | 3 | import ( 4 | "crypto/cipher" 5 | "errors" 6 | "fmt" 7 | ) 8 | 9 | type Crypto interface { 10 | Encrypt(plainText []byte) (string, error) 11 | Decrypt(cipherText string) (string, error) 12 | } 13 | 14 | type Cipher struct { 15 | GroupMode int 16 | FillMode FillMode 17 | DecodeType int 18 | Key []byte 19 | Iv []byte 20 | Output CipherText 21 | } 22 | 23 | func (c *Cipher) Encrypt(block cipher.Block, plainData []byte) (err error) { 24 | c.Output = make([]byte, len(plainData)) 25 | if c.GroupMode == CBCMode { 26 | cipher.NewCBCEncrypter(block, c.Iv).CryptBlocks(c.Output, plainData) 27 | return 28 | } 29 | if c.GroupMode == ECBMode { 30 | c.NewECBEncrypter(block, plainData) 31 | return 32 | } 33 | // todo: 34 | return 35 | } 36 | 37 | func (c *Cipher) Decrypt(block cipher.Block, cipherData []byte) (err error) { 38 | c.Output = make([]byte, len(cipherData)) 39 | if c.GroupMode == CBCMode { 40 | cipher.NewCBCDecrypter(block, c.Iv).CryptBlocks(c.Output, cipherData) 41 | return 42 | } 43 | if c.GroupMode == ECBMode { 44 | c.NewECBDecrypter(block, cipherData) 45 | return 46 | } 47 | // todo: 48 | return 49 | } 50 | 51 | // Encode 52 | // default print format is base64 53 | func (c *Cipher) Encode() string { 54 | if c.DecodeType == PrintHex { 55 | return c.Output.hexEncode() 56 | } else { 57 | return c.Output.base64Encode() 58 | } 59 | } 60 | 61 | func (c *Cipher) Decode(cipherText string) ([]byte, error) { 62 | if c.DecodeType == PrintBase64 { 63 | return base64Decode(cipherText) 64 | } else if c.DecodeType == PrintHex { 65 | return hexDecode(cipherText) 66 | } else { 67 | return nil, errors.New("unsupported print type") 68 | } 69 | } 70 | 71 | func (c *Cipher) Fill(plainText []byte, blockSize int) []byte { 72 | if c.FillMode == PkcsZero { 73 | return c.FillMode.zeroPadding(plainText, blockSize) 74 | } else { 75 | return c.FillMode.pkcs7Padding(plainText, blockSize) 76 | } 77 | } 78 | 79 | func (c *Cipher) UnFill(plainText []byte) (data []byte, err error) { 80 | defer func() { 81 | if r := recover(); r != nil { 82 | var ok bool 83 | err, ok = r.(error) 84 | if !ok { 85 | err = fmt.Errorf("%v", r) 86 | } 87 | } 88 | }() 89 | if c.FillMode == Pkcs7 { 90 | return c.FillMode.pkcsUnPadding(plainText), nil 91 | } else if c.FillMode == PkcsZero { 92 | return c.FillMode.unZeroPadding(plainText), nil 93 | } else { 94 | return nil, errors.New("unsupported fill mode") 95 | } 96 | } 97 | 98 | func (c *Cipher) NewECBEncrypter(block cipher.Block, plainData []byte) { 99 | tempText := c.Output 100 | for len(plainData) > 0 { 101 | block.Encrypt(tempText, plainData[:block.BlockSize()]) 102 | plainData = plainData[block.BlockSize():] 103 | tempText = tempText[block.BlockSize():] 104 | } 105 | } 106 | 107 | func (c *Cipher) NewECBDecrypter(block cipher.Block, cipherData []byte) { 108 | tempText := c.Output 109 | for len(cipherData) > 0 { 110 | block.Decrypt(tempText, cipherData[:block.BlockSize()]) 111 | cipherData = cipherData[block.BlockSize():] 112 | tempText = tempText[block.BlockSize():] 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # goencrypt 2 | 3 | Goencrypt is a library written in pure Go providing a set of encryption algorithms, which including symmetric ciphers(DES, 3DES, AES), asymmetric ciphers (RSA), etc. 4 | 5 | ## Quick Start 6 | 7 | Download and install 8 | 9 | ```bash 10 | go get github.com/marspere/goencrypt@v1.0.7 11 | ``` 12 | 13 | ```bash 14 | # assume the following codes in example.go file 15 | $ cat example.go 16 | ``` 17 | 18 | ``` 19 | package main 20 | 21 | import ( 22 | "fmt" 23 | 24 | "github.com/marspere/goencrypt" 25 | ) 26 | 27 | func main() { 28 | value, err := goencrypt.MD5("hello world") 29 | if err != nil { 30 | fmt.Println(err) 31 | return 32 | } 33 | fmt.Println(value) 34 | // output: 5eb63bbbe01eeed093cb22bb8f5acdc3 35 | } 36 | ``` 37 | 38 | ```bash 39 | # run example.go 40 | $ go run example.go 41 | ``` 42 | 43 | ## API Examples 44 | 45 | You can find a number of examples at goencrypt repository. 46 | 47 | ### MD5 Message-Digest Algorithm 48 | 49 | It is a widely used cryptographic hash function that produces a hash value to ensure complete and consistent information transfer. 50 | 51 | ``` 52 | func main() { 53 | // The return value is 32-bit lowercase. 54 | value, err := goencrypt.MD5("hello world") 55 | fmt.Println(value.Value) 56 | 57 | // UpperCase32 return 32-bit uppercase value. 58 | fmt.Println(value.UpperCase32) 59 | 60 | // LowerCase16 return 16-bit lowercase value. 61 | fmt.Println(value.LowerCase16) 62 | 63 | // UpperCase16 return 16-bit uppercase value. 64 | fmt.Println(value.UpperCase16) 65 | } 66 | ``` 67 | ![](image/md5.png) 68 | 69 | ### RSA Algorithm 70 | 71 | RSA encryption algorithm is an asymmetric encryption algorithm. RSA is also a packet encryption algorithm, except that the packet size can be changed according to the size of the key. 72 | 73 | RSA encryption limits the length of plaintext, and specifies the maximum length of plaintext to be encrypted = len(key) - 11. 74 | 75 | ```gotemplate 76 | func main() { 77 | cipher := goencrypt.NewRSACipher(goencrypt.PrintBase64, defaultPublicFile, defaultPrivateFile) 78 | cipherText, err := cipher.RSAEncrypt([]byte("hello world")) 79 | if err != nil { 80 | fmt.Println(err) 81 | return 82 | } 83 | fmt.Println(cipherText) 84 | } 85 | ``` 86 | 87 | ![](image/rsa_encrypt.png) 88 | 89 | ### AES Algorithm 90 | 91 | AES, Advanced Encryption Standard, also known as Rijndael encryption in cryptography, is a block encryption standard adopted by the US federal government. 92 | 93 | AES block length is fixed at 128 bits, the key length can be 128, 192 or 256 bits. It including AES-ECB,AES-CBC,AES-CTR,AES-OFB,AES-CFB. 94 | 95 | ```gotemplate 96 | func main() { 97 | cipher, err := goencrypt.NewAESCipher([]byte("0123456789asdfgh"), []byte("0123456789asdfgh"), goencrypt.CBCMode, goencrypt.Pkcs7, goencrypt.PrintBase64) 98 | if err != nil { 99 | fmt.Println(err) 100 | return 101 | } 102 | cipherText, err := cipher.AESEncrypt([]byte("hello world")) 103 | if err != nil { 104 | fmt.Println(err) 105 | return 106 | } 107 | fmt.Println(cipherText) 108 | } 109 | ``` 110 | 111 | ![](image/aes_encrypt.png) 112 | 113 | ### DES Algorithm 114 | 115 | ```gotemplate 116 | func main() { 117 | cipher := goencrypt.NewDESCipher([]byte("12345678"), []byte(""), goencrypt.ECBMode, goencrypt.Pkcs5, goencrypt.PrintBase64) 118 | cipherText, err := cipher.DESEncrypt([]byte("hello world")) 119 | if err != nil { 120 | fmt.Println(err) 121 | return 122 | } 123 | fmt.Println(cipherText) 124 | } 125 | ``` 126 | 127 | ![](image/des_encrypt.png) 128 | 129 | ### Triple DES Algorithm 130 | 131 | ```gotemplate 132 | func main() { 133 | cipher := goencrypt.NewDESCipher([]byte("12345678abcdefghijklmnop"), []byte("abcdefgh"), goencrypt.CBCMode, goencrypt.Pkcs5, goencrypt.PrintBase64) 134 | cipherText, err := cipher.TripleDESEncrypt([]byte("hello world")) 135 | if err != nil { 136 | fmt.Println(err) 137 | return 138 | } 139 | fmt.Println(cipherText) 140 | } 141 | ``` 142 | 143 | ![](image/triple_des_encrypt.png) 144 | 145 | ### Secure Hash Algorithm 146 | 147 | ```gotemplate 148 | func main() { 149 | result, err := goencrypt.SHA(goencrypt.SHA1, []byte("hello world"), goencrypt.PrintHex) 150 | if err != nil { 151 | fmt.Println(err) 152 | return 153 | } 154 | fmt.Println(result) 155 | } 156 | ``` 157 | 158 | ![](image/sha1.png) 159 | 160 | ## Contributing 161 | 162 | If you’d like to propose a change please ensure the following: 163 | 164 | - All existing tests are passing. 165 | - There are tests in the test suite that cover the changes you’re making. 166 | - You have added documentation strings (in English) to (at least) the public functions you’ve added or modified. -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------