diff --git a/cryptor/aes.go b/cryptor/aes.go deleted file mode 100644 index 3f64d98..0000000 --- a/cryptor/aes.go +++ /dev/null @@ -1,186 +0,0 @@ -// Copyright 2021 dudaodong@gmail.com. All rights reserved. -// Use of this source code is governed by MIT license - -// Package cryptor implements some util functions to encrypt and decrypt. -// Note: -// 1. for aes crypt function, the `key` param length should be 16, 24 or 32. if not, will panic. -package cryptor - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "io" -) - -// AesEcbEncrypt encrypt data with key use AES ECB algorithm -// len(key) should be 16, 24 or 32 -func AesEcbEncrypt(data, key []byte) []byte { - length := (len(data) + aes.BlockSize) / aes.BlockSize - plain := make([]byte, length*aes.BlockSize) - - copy(plain, data) - - pad := byte(len(plain) - len(data)) - for i := len(data); i < len(plain); i++ { - plain[i] = pad - } - - encrypted := make([]byte, len(plain)) - cipher, _ := aes.NewCipher(generateAesKey(key)) - - for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { - cipher.Encrypt(encrypted[bs:be], plain[bs:be]) - } - - return encrypted -} - -// AesEcbDecrypt decrypt data with key use AES ECB algorithm -// len(key) should be 16, 24 or 32 -func AesEcbDecrypt(encrypted, key []byte) []byte { - cipher, _ := aes.NewCipher(generateAesKey(key)) - decrypted := make([]byte, len(encrypted)) - - for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { - cipher.Decrypt(decrypted[bs:be], encrypted[bs:be]) - } - - trim := 0 - if len(decrypted) > 0 { - trim = len(decrypted) - int(decrypted[len(decrypted)-1]) - } - - return decrypted[:trim] -} - -// AesCbcEncrypt encrypt data with key use AES CBC algorithm -// len(key) should be 16, 24 or 32 -func AesCbcEncrypt(data, key []byte) []byte { - block, _ := aes.NewCipher(key) - data = pkcs7Padding(data, block.BlockSize()) - - encrypted := make([]byte, aes.BlockSize+len(data)) - iv := encrypted[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - mode := cipher.NewCBCEncrypter(block, iv) - mode.CryptBlocks(encrypted[aes.BlockSize:], data) - - return encrypted -} - -// AesCbcDecrypt decrypt data with key use AES CBC algorithm -// len(key) should be 16, 24 or 32 -func AesCbcDecrypt(encrypted, key []byte) []byte { - block, _ := aes.NewCipher(key) - - iv := encrypted[:aes.BlockSize] - encrypted = encrypted[aes.BlockSize:] - - mode := cipher.NewCBCDecrypter(block, iv) - mode.CryptBlocks(encrypted, encrypted) - - decrypted := pkcs7UnPadding(encrypted) - return decrypted -} - -// AesCtrCrypt encrypt data with key use AES CTR algorithm -// len(key) should be 16, 24 or 32 -func AesCtrCrypt(data, key []byte) []byte { - block, _ := aes.NewCipher(key) - - iv := bytes.Repeat([]byte("1"), block.BlockSize()) - stream := cipher.NewCTR(block, iv) - - dst := make([]byte, len(data)) - stream.XORKeyStream(dst, data) - - return dst -} - -// AesCfbEncrypt encrypt data with key use AES CFB algorithm -// len(key) should be 16, 24 or 32 -func AesCfbEncrypt(data, key []byte) []byte { - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - encrypted := make([]byte, aes.BlockSize+len(data)) - iv := encrypted[:aes.BlockSize] - - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewCFBEncrypter(block, iv) - stream.XORKeyStream(encrypted[aes.BlockSize:], data) - - return encrypted -} - -// AesCfbDecrypt decrypt data with key use AES CFB algorithm -// len(encrypted) should be great than 16, len(key) should be 16, 24 or 32 -func AesCfbDecrypt(encrypted, key []byte) []byte { - if len(encrypted) < aes.BlockSize { - panic("encrypted data is too short") - } - - block, _ := aes.NewCipher(key) - iv := encrypted[:aes.BlockSize] - encrypted = encrypted[aes.BlockSize:] - - stream := cipher.NewCFBDecrypter(block, iv) - - stream.XORKeyStream(encrypted, encrypted) - - return encrypted -} - -// AesOfbEncrypt encrypt data with key use AES OFB algorithm -// len(key) should be 16, 24 or 32 -func AesOfbEncrypt(data, key []byte) []byte { - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - data = pkcs7Padding(data, aes.BlockSize) - encrypted := make([]byte, aes.BlockSize+len(data)) - iv := encrypted[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewOFB(block, iv) - stream.XORKeyStream(encrypted[aes.BlockSize:], data) - - return encrypted -} - -// AesOfbDecrypt decrypt data with key use AES OFB algorithm -// len(key) should be 16, 24 or 32 -func AesOfbDecrypt(data, key []byte) []byte { - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - iv := data[:aes.BlockSize] - data = data[aes.BlockSize:] - if len(data)%aes.BlockSize != 0 { - return nil - } - - decrypted := make([]byte, len(data)) - mode := cipher.NewOFB(block, iv) - mode.XORKeyStream(decrypted, data) - - decrypted = pkcs7UnPadding(decrypted) - - return decrypted -} diff --git a/cryptor/aes_test.go b/cryptor/aes_test.go deleted file mode 100644 index 3cf2e3f..0000000 --- a/cryptor/aes_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package cryptor - -import ( - "testing" - - "github.com/duke-git/lancet/v2/internal" -) - -func TestAesEcbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefghijklmnop" - - aesEcbEncrypt := AesEcbEncrypt([]byte(data), []byte(key)) - aesEcbDecrypt := AesEcbDecrypt(aesEcbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestAesEcbEncrypt") - assert.Equal(data, string(aesEcbDecrypt)) -} - -func TestAesCbcEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefghijklmnop" - - aesCbcEncrypt := AesCbcEncrypt([]byte(data), []byte(key)) - aesCbcDecrypt := AesCbcDecrypt(aesCbcEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestAesCbcEncrypt") - assert.Equal(data, string(aesCbcDecrypt)) -} - -func TestAesCtrCrypt(t *testing.T) { - data := "hello world" - key := "abcdefghijklmnop" - - aesCtrCrypt := AesCtrCrypt([]byte(data), []byte(key)) - aesCtrDeCrypt := AesCtrCrypt(aesCtrCrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestAesCtrCrypt") - assert.Equal(data, string(aesCtrDeCrypt)) -} - -func TestAesCfbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefghijklmnop" - - aesCfbEncrypt := AesCfbEncrypt([]byte(data), []byte(key)) - aesCfbDecrypt := AesCfbDecrypt(aesCfbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestAesCfbEncrypt") - assert.Equal(data, string(aesCfbDecrypt)) -} - -func TestAesOfbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefghijklmnop" - - aesOfbEncrypt := AesOfbEncrypt([]byte(data), []byte(key)) - aesOfbDecrypt := AesOfbDecrypt(aesOfbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestAesOfbEncrypt") - assert.Equal(data, string(aesOfbDecrypt)) -} diff --git a/cryptor/basic.go b/cryptor/basic.go index c4df12d..074d257 100644 --- a/cryptor/basic.go +++ b/cryptor/basic.go @@ -19,25 +19,28 @@ import ( "os" ) -// Base64StdEncode encode string with base64 encoding +// Base64StdEncode encode string with base64 encoding. +// Play: func Base64StdEncode(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) } -// Base64StdDecode decode a base64 encoded string +// Base64StdDecode decode a base64 encoded string. +// Play: func Base64StdDecode(s string) string { b, _ := base64.StdEncoding.DecodeString(s) return string(b) } -// Md5String return the md5 value of string +// Md5String return the md5 value of string. +// Play: func Md5String(s string) string { h := md5.New() h.Write([]byte(s)) return hex.EncodeToString(h.Sum(nil)) } -// Md5File return the md5 value of file +// Md5File return the md5 value of file. func Md5File(filename string) (string, error) { if fileInfo, err := os.Stat(filename); err != nil { return "", err @@ -69,49 +72,56 @@ func Md5File(filename string) (string, error) { return checksum, nil } -// HmacMd5 return the hmac hash of string use md5 +// HmacMd5 return the hmac hash of string use md5. +// Play: func HmacMd5(data, key string) string { h := hmac.New(md5.New, []byte(key)) h.Write([]byte(data)) return hex.EncodeToString(h.Sum([]byte(""))) } -// HmacSha1 return the hmac hash of string use sha1 +// HmacSha1 return the hmac hash of string use sha1. +// Play: func HmacSha1(data, key string) string { h := hmac.New(sha1.New, []byte(key)) h.Write([]byte(data)) return hex.EncodeToString(h.Sum([]byte(""))) } -// HmacSha256 return the hmac hash of string use sha256 +// HmacSha256 return the hmac hash of string use sha256. +// Play: func HmacSha256(data, key string) string { h := hmac.New(sha256.New, []byte(key)) h.Write([]byte(data)) return hex.EncodeToString(h.Sum([]byte(""))) } -// HmacSha512 return the hmac hash of string use sha512 +// HmacSha512 return the hmac hash of string use sha512. +// Play: func HmacSha512(data, key string) string { h := hmac.New(sha512.New, []byte(key)) h.Write([]byte(data)) return hex.EncodeToString(h.Sum([]byte(""))) } -// Sha1 return the sha1 value (SHA-1 hash algorithm) of string +// Sha1 return the sha1 value (SHA-1 hash algorithm) of string. +// Play: func Sha1(data string) string { sha1 := sha1.New() sha1.Write([]byte(data)) return hex.EncodeToString(sha1.Sum([]byte(""))) } -// Sha256 return the sha256 value (SHA256 hash algorithm) of string +// Sha256 return the sha256 value (SHA256 hash algorithm) of string. +// Play: func Sha256(data string) string { sha256 := sha256.New() sha256.Write([]byte(data)) return hex.EncodeToString(sha256.Sum([]byte(""))) } -// Sha512 return the sha512 value (SHA512 hash algorithm) of string +// Sha512 return the sha512 value (SHA512 hash algorithm) of string. +// Play: func Sha512(data string) string { sha512 := sha512.New() sha512.Write([]byte(data)) diff --git a/cryptor/crypto_example_test.go b/cryptor/crypto_example_test.go new file mode 100644 index 0000000..d4352e0 --- /dev/null +++ b/cryptor/crypto_example_test.go @@ -0,0 +1,410 @@ +package cryptor + +import "fmt" + +func ExampleAesEcbEncrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesEcbEncrypt([]byte(data), []byte(key)) + + decrypted := AesEcbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesEcbDecrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesEcbEncrypt([]byte(data), []byte(key)) + + decrypted := AesEcbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesCbcEncrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesCbcEncrypt([]byte(data), []byte(key)) + + decrypted := AesCbcDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesCbcDecrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesCbcEncrypt([]byte(data), []byte(key)) + + decrypted := AesCbcDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesCtrCrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesCtrCrypt([]byte(data), []byte(key)) + decrypted := AesCtrCrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesCfbEncrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesCfbEncrypt([]byte(data), []byte(key)) + + decrypted := AesCfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesCfbDecrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesCfbEncrypt([]byte(data), []byte(key)) + + decrypted := AesCfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesOfbEncrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesOfbEncrypt([]byte(data), []byte(key)) + + decrypted := AesOfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleAesOfbDecrypt() { + data := "hello" + key := "abcdefghijklmnop" + + encrypted := AesOfbEncrypt([]byte(data), []byte(key)) + + decrypted := AesOfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesEcbEncrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesEcbEncrypt([]byte(data), []byte(key)) + + decrypted := DesEcbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesEcbDecrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesEcbEncrypt([]byte(data), []byte(key)) + + decrypted := DesEcbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesCbcEncrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesCbcEncrypt([]byte(data), []byte(key)) + + decrypted := DesCbcDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesCbcDecrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesCbcEncrypt([]byte(data), []byte(key)) + + decrypted := DesCbcDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesCtrCrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesCtrCrypt([]byte(data), []byte(key)) + decrypted := DesCtrCrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesCfbEncrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesCfbEncrypt([]byte(data), []byte(key)) + + decrypted := DesCfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesCfbDecrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesCfbEncrypt([]byte(data), []byte(key)) + + decrypted := DesCfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesOfbEncrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesOfbEncrypt([]byte(data), []byte(key)) + + decrypted := DesOfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleDesOfbDecrypt() { + data := "hello" + key := "abcdefgh" + + encrypted := DesOfbEncrypt([]byte(data), []byte(key)) + + decrypted := DesOfbDecrypt(encrypted, []byte(key)) + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleGenerateRsaKey() { + // Create ras private and public pem file + err := GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") + if err != nil { + return + } + + fmt.Println("foo") + + // Output: + // foo +} + +func ExampleRsaEncrypt() { + // Create ras private and public pem file + err := GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") + if err != nil { + return + } + + data := []byte("hello") + encrypted := RsaEncrypt(data, "rsa_public.pem") + decrypted := RsaDecrypt(encrypted, "rsa_private.pem") + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleRsaDecrypt() { + // Create ras private and public pem file + err := GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") + if err != nil { + return + } + + data := []byte("hello") + encrypted := RsaEncrypt(data, "rsa_public.pem") + decrypted := RsaDecrypt(encrypted, "rsa_private.pem") + + fmt.Println(string(decrypted)) + + // Output: + // hello +} + +func ExampleBase64StdEncode() { + base64Str := Base64StdEncode("hello") + + fmt.Println(base64Str) + + // Output: + // aGVsbG8= +} + +func ExampleBase64StdDecode() { + str := Base64StdDecode("aGVsbG8=") + + fmt.Println(str) + + // Output: + // hello +} + +func ExampleHmacMd5() { + str := "hello" + key := "12345" + + hms := HmacMd5(str, key) + + fmt.Println(hms) + + // Output: + // e834306eab892d872525d4918a7a639a +} + +func ExampleHmacSha1() { + str := "hello" + key := "12345" + + hms := HmacSha1(str, key) + + fmt.Println(hms) + + // Output: + // 5c6a9db0cccb92e36ed0323fd09b7f936de9ace0 +} + +func ExampleHmacSha256() { + str := "hello" + key := "12345" + + hms := HmacSha256(str, key) + + fmt.Println(hms) + + // Output: + // 315bb93c4e989862ba09cb62e05d73a5f376cb36f0d786edab0c320d059fde75 +} + +func ExampleHmacSha512() { + str := "hello" + key := "12345" + + hms := HmacSha512(str, key) + + fmt.Println(hms) + + // Output: + // dd8f1290a9dd23d354e2526d9a2e9ce8cffffdd37cb320800d1c6c13d2efc363288376a196c5458daf53f8e1aa6b45a6d856303d5c0a2064bff9785861d48cfc +} + +func ExampleMd5String() { + str := "hello" + + md5Str := Md5String(str) + + fmt.Println(md5Str) + + // Output: + // 5d41402abc4b2a76b9719d911017c592 +} + +func ExampleSha1() { + str := "hello" + + result := Sha1(str) + + fmt.Println(result) + + // Output: + // aaf4c61ddcc5e8a2dabede0f3b482cd9aea9434d +} + +func ExampleSha256() { + str := "hello" + + result := Sha256(str) + + fmt.Println(result) + + // Output: + // 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824 +} + +func ExampleSha512() { + str := "hello" + + result := Sha512(str) + + fmt.Println(result) + + // Output: + // 9b71d224bd62f3785d96d46ad3ea3d73319bfbc2890caadae2dff72519673ca72323c3d99ba5c11d7c7acc6e14b8c5da0c4663475c2e5c3adef46f73bcdec043 +} diff --git a/cryptor/des.go b/cryptor/des.go deleted file mode 100644 index 72b52e9..0000000 --- a/cryptor/des.go +++ /dev/null @@ -1,180 +0,0 @@ -// Copyright 2021 dudaodong@gmail.com. All rights reserved. -// Use of this source code is governed by MIT license - -// Package cryptor implements some util functions to encrypt and decrypt. -package cryptor - -import ( - "bytes" - "crypto/cipher" - "crypto/des" - "crypto/rand" - "io" -) - -// DesEcbEncrypt encrypt data with key use DES ECB algorithm -// len(key) should be 8 -func DesEcbEncrypt(data, key []byte) []byte { - length := (len(data) + des.BlockSize) / des.BlockSize - plain := make([]byte, length*des.BlockSize) - copy(plain, data) - - pad := byte(len(plain) - len(data)) - for i := len(data); i < len(plain); i++ { - plain[i] = pad - } - - encrypted := make([]byte, len(plain)) - cipher, _ := des.NewCipher(generateDesKey(key)) - - for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { - cipher.Encrypt(encrypted[bs:be], plain[bs:be]) - } - - return encrypted -} - -// DesEcbDecrypt decrypt data with key use DES ECB algorithm -// len(key) should be 8 -func DesEcbDecrypt(encrypted, key []byte) []byte { - cipher, _ := des.NewCipher(generateDesKey(key)) - decrypted := make([]byte, len(encrypted)) - - for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { - cipher.Decrypt(decrypted[bs:be], encrypted[bs:be]) - } - - trim := 0 - if len(decrypted) > 0 { - trim = len(decrypted) - int(decrypted[len(decrypted)-1]) - } - - return decrypted[:trim] -} - -// DesCbcEncrypt encrypt data with key use DES CBC algorithm -// len(key) should be 8 -func DesCbcEncrypt(data, key []byte) []byte { - block, _ := des.NewCipher(key) - data = pkcs7Padding(data, block.BlockSize()) - - encrypted := make([]byte, des.BlockSize+len(data)) - iv := encrypted[:des.BlockSize] - - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - mode := cipher.NewCBCEncrypter(block, iv) - mode.CryptBlocks(encrypted[des.BlockSize:], data) - - return encrypted -} - -// DesCbcDecrypt decrypt data with key use DES CBC algorithm -// len(key) should be 8 -func DesCbcDecrypt(encrypted, key []byte) []byte { - block, _ := des.NewCipher(key) - - iv := encrypted[:des.BlockSize] - encrypted = encrypted[des.BlockSize:] - - mode := cipher.NewCBCDecrypter(block, iv) - mode.CryptBlocks(encrypted, encrypted) - - decrypted := pkcs7UnPadding(encrypted) - return decrypted -} - -// DesCtrCrypt encrypt data with key use DES CTR algorithm -// len(key) should be 8 -func DesCtrCrypt(data, key []byte) []byte { - block, _ := des.NewCipher(key) - - iv := bytes.Repeat([]byte("1"), block.BlockSize()) - stream := cipher.NewCTR(block, iv) - - dst := make([]byte, len(data)) - stream.XORKeyStream(dst, data) - - return dst -} - -// DesCfbEncrypt encrypt data with key use DES CFB algorithm -// len(key) should be 8 -func DesCfbEncrypt(data, key []byte) []byte { - block, err := des.NewCipher(key) - if err != nil { - panic(err) - } - - encrypted := make([]byte, des.BlockSize+len(data)) - iv := encrypted[:des.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewCFBEncrypter(block, iv) - stream.XORKeyStream(encrypted[des.BlockSize:], data) - - return encrypted -} - -// DesCfbDecrypt decrypt data with key use DES CFB algorithm -// len(encrypted) should be great than 16, len(key) should be 8 -func DesCfbDecrypt(encrypted, key []byte) []byte { - block, _ := des.NewCipher(key) - if len(encrypted) < des.BlockSize { - panic("encrypted data is too short") - } - iv := encrypted[:des.BlockSize] - encrypted = encrypted[des.BlockSize:] - - stream := cipher.NewCFBDecrypter(block, iv) - stream.XORKeyStream(encrypted, encrypted) - - return encrypted -} - -// DesOfbEncrypt encrypt data with key use DES OFB algorithm -// len(key) should be 16, 24 or 32 -func DesOfbEncrypt(data, key []byte) []byte { - block, err := des.NewCipher(key) - if err != nil { - panic(err) - } - data = pkcs7Padding(data, des.BlockSize) - encrypted := make([]byte, des.BlockSize+len(data)) - iv := encrypted[:des.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewOFB(block, iv) - stream.XORKeyStream(encrypted[des.BlockSize:], data) - - return encrypted -} - -// DesOfbDecrypt decrypt data with key use DES OFB algorithm -// len(key) should be 8 -func DesOfbDecrypt(data, key []byte) []byte { - block, err := des.NewCipher(key) - if err != nil { - panic(err) - } - - iv := data[:des.BlockSize] - data = data[des.BlockSize:] - if len(data)%des.BlockSize != 0 { - return nil - } - - decrypted := make([]byte, len(data)) - mode := cipher.NewOFB(block, iv) - mode.XORKeyStream(decrypted, data) - - decrypted = pkcs7UnPadding(decrypted) - - return decrypted -} diff --git a/cryptor/des_test.go b/cryptor/des_test.go deleted file mode 100644 index 1567435..0000000 --- a/cryptor/des_test.go +++ /dev/null @@ -1,62 +0,0 @@ -package cryptor - -import ( - "testing" - - "github.com/duke-git/lancet/v2/internal" -) - -func TestDesEcbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefgh" - - desEcbEncrypt := DesEcbEncrypt([]byte(data), []byte(key)) - desEcbDecrypt := DesEcbDecrypt(desEcbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestDesEcbEncrypt") - assert.Equal(data, string(desEcbDecrypt)) -} - -func TestDesCbcEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefgh" - - desCbcEncrypt := DesCbcEncrypt([]byte(data), []byte(key)) - desCbcDecrypt := DesCbcDecrypt(desCbcEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestDesCbcEncrypt") - assert.Equal(data, string(desCbcDecrypt)) -} - -func TestDesCtrCrypt(t *testing.T) { - data := "hello world" - key := "abcdefgh" - - desCtrCrypt := DesCtrCrypt([]byte(data), []byte(key)) - desCtrDeCrypt := DesCtrCrypt(desCtrCrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestDesCtrCrypt") - assert.Equal(data, string(desCtrDeCrypt)) -} - -func TestDesCfbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefgh" - - desCfbEncrypt := DesCfbEncrypt([]byte(data), []byte(key)) - desCfbDecrypt := DesCfbDecrypt(desCfbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestDesCfbEncrypt") - assert.Equal(data, string(desCfbDecrypt)) -} - -func TestDesOfbEncrypt(t *testing.T) { - data := "hello world" - key := "abcdefgh" - - desOfbEncrypt := DesOfbEncrypt([]byte(data), []byte(key)) - desOfbDecrypt := DesOfbDecrypt(desOfbEncrypt, []byte(key)) - - assert := internal.NewAssert(t, "TestDesOfbEncrypt") - assert.Equal(data, string(desOfbDecrypt)) -} diff --git a/cryptor/encrypt.go b/cryptor/encrypt.go new file mode 100644 index 0000000..4f6af86 --- /dev/null +++ b/cryptor/encrypt.go @@ -0,0 +1,499 @@ +// Copyright 2021 dudaodong@gmail.com. All rights reserved. +// Use of this source code is governed by MIT license + +// Package cryptor implements some util functions to encrypt and decrypt. +// Note: +// 1. for aes crypt function, the `key` param length should be 16, 24 or 32. if not, will panic. +package cryptor + +import ( + "bytes" + "crypto/aes" + "crypto/cipher" + "crypto/des" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "io" + "os" +) + +// AesEcbEncrypt encrypt data with key use AES ECB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/jT5irszHx-j +func AesEcbEncrypt(data, key []byte) []byte { + length := (len(data) + aes.BlockSize) / aes.BlockSize + plain := make([]byte, length*aes.BlockSize) + + copy(plain, data) + + pad := byte(len(plain) - len(data)) + for i := len(data); i < len(plain); i++ { + plain[i] = pad + } + + encrypted := make([]byte, len(plain)) + cipher, _ := aes.NewCipher(generateAesKey(key)) + + for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { + cipher.Encrypt(encrypted[bs:be], plain[bs:be]) + } + + return encrypted +} + +// AesEcbDecrypt decrypt data with key use AES ECB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/jT5irszHx-j +func AesEcbDecrypt(encrypted, key []byte) []byte { + cipher, _ := aes.NewCipher(generateAesKey(key)) + decrypted := make([]byte, len(encrypted)) + + for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { + cipher.Decrypt(decrypted[bs:be], encrypted[bs:be]) + } + + trim := 0 + if len(decrypted) > 0 { + trim = len(decrypted) - int(decrypted[len(decrypted)-1]) + } + + return decrypted[:trim] +} + +// AesCbcEncrypt encrypt data with key use AES CBC algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/IOq_g8_lKZD +func AesCbcEncrypt(data, key []byte) []byte { + block, _ := aes.NewCipher(key) + data = pkcs7Padding(data, block.BlockSize()) + + encrypted := make([]byte, aes.BlockSize+len(data)) + iv := encrypted[:aes.BlockSize] + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + mode := cipher.NewCBCEncrypter(block, iv) + mode.CryptBlocks(encrypted[aes.BlockSize:], data) + + return encrypted +} + +// AesCbcDecrypt decrypt data with key use AES CBC algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/IOq_g8_lKZD +func AesCbcDecrypt(encrypted, key []byte) []byte { + block, _ := aes.NewCipher(key) + + iv := encrypted[:aes.BlockSize] + encrypted = encrypted[aes.BlockSize:] + + mode := cipher.NewCBCDecrypter(block, iv) + mode.CryptBlocks(encrypted, encrypted) + + decrypted := pkcs7UnPadding(encrypted) + return decrypted +} + +// AesCtrCrypt encrypt data with key use AES CTR algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/SpaZO0-5Nsp +func AesCtrCrypt(data, key []byte) []byte { + block, _ := aes.NewCipher(key) + + iv := bytes.Repeat([]byte("1"), block.BlockSize()) + stream := cipher.NewCTR(block, iv) + + dst := make([]byte, len(data)) + stream.XORKeyStream(dst, data) + + return dst +} + +// AesCfbEncrypt encrypt data with key use AES CFB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/tfkF10B13kH +func AesCfbEncrypt(data, key []byte) []byte { + block, err := aes.NewCipher(key) + if err != nil { + panic(err) + } + + encrypted := make([]byte, aes.BlockSize+len(data)) + iv := encrypted[:aes.BlockSize] + + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + stream := cipher.NewCFBEncrypter(block, iv) + stream.XORKeyStream(encrypted[aes.BlockSize:], data) + + return encrypted +} + +// AesCfbDecrypt decrypt data with key use AES CFB algorithm +// len(encrypted) should be great than 16, len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/tfkF10B13kH +func AesCfbDecrypt(encrypted, key []byte) []byte { + if len(encrypted) < aes.BlockSize { + panic("encrypted data is too short") + } + + block, _ := aes.NewCipher(key) + iv := encrypted[:aes.BlockSize] + encrypted = encrypted[aes.BlockSize:] + + stream := cipher.NewCFBDecrypter(block, iv) + + stream.XORKeyStream(encrypted, encrypted) + + return encrypted +} + +// AesOfbEncrypt encrypt data with key use AES OFB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/VtHxtkUj-3F +func AesOfbEncrypt(data, key []byte) []byte { + block, err := aes.NewCipher(key) + if err != nil { + panic(err) + } + + data = pkcs7Padding(data, aes.BlockSize) + encrypted := make([]byte, aes.BlockSize+len(data)) + iv := encrypted[:aes.BlockSize] + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + stream := cipher.NewOFB(block, iv) + stream.XORKeyStream(encrypted[aes.BlockSize:], data) + + return encrypted +} + +// AesOfbDecrypt decrypt data with key use AES OFB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/VtHxtkUj-3F +func AesOfbDecrypt(data, key []byte) []byte { + block, err := aes.NewCipher(key) + if err != nil { + panic(err) + } + + iv := data[:aes.BlockSize] + data = data[aes.BlockSize:] + if len(data)%aes.BlockSize != 0 { + return nil + } + + decrypted := make([]byte, len(data)) + mode := cipher.NewOFB(block, iv) + mode.XORKeyStream(decrypted, data) + + decrypted = pkcs7UnPadding(decrypted) + + return decrypted +} + +// DesEcbEncrypt encrypt data with key use DES ECB algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/8qivmPeZy4P +func DesEcbEncrypt(data, key []byte) []byte { + length := (len(data) + des.BlockSize) / des.BlockSize + plain := make([]byte, length*des.BlockSize) + copy(plain, data) + + pad := byte(len(plain) - len(data)) + for i := len(data); i < len(plain); i++ { + plain[i] = pad + } + + encrypted := make([]byte, len(plain)) + cipher, _ := des.NewCipher(generateDesKey(key)) + + for bs, be := 0, cipher.BlockSize(); bs <= len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { + cipher.Encrypt(encrypted[bs:be], plain[bs:be]) + } + + return encrypted +} + +// DesEcbDecrypt decrypt data with key use DES ECB algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/8qivmPeZy4P +func DesEcbDecrypt(encrypted, key []byte) []byte { + cipher, _ := des.NewCipher(generateDesKey(key)) + decrypted := make([]byte, len(encrypted)) + + for bs, be := 0, cipher.BlockSize(); bs < len(encrypted); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() { + cipher.Decrypt(decrypted[bs:be], encrypted[bs:be]) + } + + trim := 0 + if len(decrypted) > 0 { + trim = len(decrypted) - int(decrypted[len(decrypted)-1]) + } + + return decrypted[:trim] +} + +// DesCbcEncrypt encrypt data with key use DES CBC algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/4cC4QvWfe3_1 +func DesCbcEncrypt(data, key []byte) []byte { + block, _ := des.NewCipher(key) + data = pkcs7Padding(data, block.BlockSize()) + + encrypted := make([]byte, des.BlockSize+len(data)) + iv := encrypted[:des.BlockSize] + + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + mode := cipher.NewCBCEncrypter(block, iv) + mode.CryptBlocks(encrypted[des.BlockSize:], data) + + return encrypted +} + +// DesCbcDecrypt decrypt data with key use DES CBC algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/4cC4QvWfe3_1 +func DesCbcDecrypt(encrypted, key []byte) []byte { + block, _ := des.NewCipher(key) + + iv := encrypted[:des.BlockSize] + encrypted = encrypted[des.BlockSize:] + + mode := cipher.NewCBCDecrypter(block, iv) + mode.CryptBlocks(encrypted, encrypted) + + decrypted := pkcs7UnPadding(encrypted) + return decrypted +} + +// DesCtrCrypt encrypt data with key use DES CTR algorithm +// len(key) should be 8. +// Play: +func DesCtrCrypt(data, key []byte) []byte { + block, _ := des.NewCipher(key) + + iv := bytes.Repeat([]byte("1"), block.BlockSize()) + stream := cipher.NewCTR(block, iv) + + dst := make([]byte, len(data)) + stream.XORKeyStream(dst, data) + + return dst +} + +// DesCfbEncrypt encrypt data with key use DES CFB algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/y-eNxcFBlxL +func DesCfbEncrypt(data, key []byte) []byte { + block, err := des.NewCipher(key) + if err != nil { + panic(err) + } + + encrypted := make([]byte, des.BlockSize+len(data)) + iv := encrypted[:des.BlockSize] + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + stream := cipher.NewCFBEncrypter(block, iv) + stream.XORKeyStream(encrypted[des.BlockSize:], data) + + return encrypted +} + +// DesCfbDecrypt decrypt data with key use DES CFB algorithm +// len(encrypted) should be great than 16, len(key) should be 8. +// Play: https://go.dev/play/p/y-eNxcFBlxL +func DesCfbDecrypt(encrypted, key []byte) []byte { + block, _ := des.NewCipher(key) + if len(encrypted) < des.BlockSize { + panic("encrypted data is too short") + } + iv := encrypted[:des.BlockSize] + encrypted = encrypted[des.BlockSize:] + + stream := cipher.NewCFBDecrypter(block, iv) + stream.XORKeyStream(encrypted, encrypted) + + return encrypted +} + +// DesOfbEncrypt encrypt data with key use DES OFB algorithm +// len(key) should be 16, 24 or 32. +// Play: https://go.dev/play/p/74KmNadjN1J +func DesOfbEncrypt(data, key []byte) []byte { + block, err := des.NewCipher(key) + if err != nil { + panic(err) + } + data = pkcs7Padding(data, des.BlockSize) + encrypted := make([]byte, des.BlockSize+len(data)) + iv := encrypted[:des.BlockSize] + if _, err := io.ReadFull(rand.Reader, iv); err != nil { + panic(err) + } + + stream := cipher.NewOFB(block, iv) + stream.XORKeyStream(encrypted[des.BlockSize:], data) + + return encrypted +} + +// DesOfbDecrypt decrypt data with key use DES OFB algorithm +// len(key) should be 8. +// Play: https://go.dev/play/p/74KmNadjN1J +func DesOfbDecrypt(data, key []byte) []byte { + block, err := des.NewCipher(key) + if err != nil { + panic(err) + } + + iv := data[:des.BlockSize] + data = data[des.BlockSize:] + if len(data)%des.BlockSize != 0 { + return nil + } + + decrypted := make([]byte, len(data)) + mode := cipher.NewOFB(block, iv) + mode.XORKeyStream(decrypted, data) + + decrypted = pkcs7UnPadding(decrypted) + + return decrypted +} + +// GenerateRsaKey make a rsa private key, and return key file name +// Generated key file is `rsa_private.pem` and `rsa_public.pem` in current path. +// Play: https://go.dev/play/p/zutRHrDqs0X +func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error { + // private key + privateKey, err := rsa.GenerateKey(rand.Reader, keySize) + if err != nil { + return err + } + + derText := x509.MarshalPKCS1PrivateKey(privateKey) + + block := pem.Block{ + Type: "rsa private key", + Bytes: derText, + } + + file, err := os.Create(priKeyFile) + if err != nil { + panic(err) + } + err = pem.Encode(file, &block) + if err != nil { + return err + } + + file.Close() + + // public key + publicKey := privateKey.PublicKey + + derpText, err := x509.MarshalPKIXPublicKey(&publicKey) + if err != nil { + return err + } + + block = pem.Block{ + Type: "rsa public key", + Bytes: derpText, + } + + file, err = os.Create(pubKeyFile) + if err != nil { + return err + } + + err = pem.Encode(file, &block) + if err != nil { + return err + } + + file.Close() + + return nil +} + +// RsaEncrypt encrypt data with ras algorithm. +// Play: https://go.dev/play/p/rDqTT01SPkZ +func RsaEncrypt(data []byte, pubKeyFileName string) []byte { + file, err := os.Open(pubKeyFileName) + if err != nil { + panic(err) + } + fileInfo, err := file.Stat() + if err != nil { + panic(err) + } + defer file.Close() + buf := make([]byte, fileInfo.Size()) + + _, err = file.Read(buf) + if err != nil { + panic(err) + } + + block, _ := pem.Decode(buf) + + pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) + if err != nil { + panic(err) + } + pubKey := pubInterface.(*rsa.PublicKey) + + cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, data) + if err != nil { + panic(err) + } + return cipherText +} + +// RsaDecrypt decrypt data with ras algorithm. +// Play: https://go.dev/play/p/rDqTT01SPkZ +func RsaDecrypt(data []byte, privateKeyFileName string) []byte { + file, err := os.Open(privateKeyFileName) + if err != nil { + panic(err) + } + fileInfo, err := file.Stat() + if err != nil { + panic(err) + } + buf := make([]byte, fileInfo.Size()) + defer file.Close() + + _, err = file.Read(buf) + if err != nil { + panic(err) + } + + block, _ := pem.Decode(buf) + + priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) + if err != nil { + panic(err) + } + + plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, data) + if err != nil { + panic(err) + } + return plainText +} diff --git a/cryptor/encrypt_test.go b/cryptor/encrypt_test.go new file mode 100644 index 0000000..34efa86 --- /dev/null +++ b/cryptor/encrypt_test.go @@ -0,0 +1,130 @@ +package cryptor + +import ( + "testing" + + "github.com/duke-git/lancet/v2/internal" +) + +func TestAesEcbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefghijklmnop" + + aesEcbEncrypt := AesEcbEncrypt([]byte(data), []byte(key)) + aesEcbDecrypt := AesEcbDecrypt(aesEcbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestAesEcbEncrypt") + assert.Equal(data, string(aesEcbDecrypt)) +} + +func TestAesCbcEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefghijklmnop" + + aesCbcEncrypt := AesCbcEncrypt([]byte(data), []byte(key)) + aesCbcDecrypt := AesCbcDecrypt(aesCbcEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestAesCbcEncrypt") + assert.Equal(data, string(aesCbcDecrypt)) +} + +func TestAesCtrCrypt(t *testing.T) { + data := "hello world" + key := "abcdefghijklmnop" + + aesCtrCrypt := AesCtrCrypt([]byte(data), []byte(key)) + aesCtrDeCrypt := AesCtrCrypt(aesCtrCrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestAesCtrCrypt") + assert.Equal(data, string(aesCtrDeCrypt)) +} + +func TestAesCfbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefghijklmnop" + + aesCfbEncrypt := AesCfbEncrypt([]byte(data), []byte(key)) + aesCfbDecrypt := AesCfbDecrypt(aesCfbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestAesCfbEncrypt") + assert.Equal(data, string(aesCfbDecrypt)) +} + +func TestAesOfbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefghijklmnop" + + aesOfbEncrypt := AesOfbEncrypt([]byte(data), []byte(key)) + aesOfbDecrypt := AesOfbDecrypt(aesOfbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestAesOfbEncrypt") + assert.Equal(data, string(aesOfbDecrypt)) +} + +func TestDesEcbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefgh" + + desEcbEncrypt := DesEcbEncrypt([]byte(data), []byte(key)) + desEcbDecrypt := DesEcbDecrypt(desEcbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestDesEcbEncrypt") + assert.Equal(data, string(desEcbDecrypt)) +} + +func TestDesCbcEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefgh" + + desCbcEncrypt := DesCbcEncrypt([]byte(data), []byte(key)) + desCbcDecrypt := DesCbcDecrypt(desCbcEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestDesCbcEncrypt") + assert.Equal(data, string(desCbcDecrypt)) +} + +func TestDesCtrCrypt(t *testing.T) { + data := "hello world" + key := "abcdefgh" + + desCtrCrypt := DesCtrCrypt([]byte(data), []byte(key)) + desCtrDeCrypt := DesCtrCrypt(desCtrCrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestDesCtrCrypt") + assert.Equal(data, string(desCtrDeCrypt)) +} + +func TestDesCfbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefgh" + + desCfbEncrypt := DesCfbEncrypt([]byte(data), []byte(key)) + desCfbDecrypt := DesCfbDecrypt(desCfbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestDesCfbEncrypt") + assert.Equal(data, string(desCfbDecrypt)) +} + +func TestDesOfbEncrypt(t *testing.T) { + data := "hello world" + key := "abcdefgh" + + desOfbEncrypt := DesOfbEncrypt([]byte(data), []byte(key)) + desOfbDecrypt := DesOfbDecrypt(desOfbEncrypt, []byte(key)) + + assert := internal.NewAssert(t, "TestDesOfbEncrypt") + assert.Equal(data, string(desOfbDecrypt)) +} + +func TestRsaEncrypt(t *testing.T) { + err := GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") + if err != nil { + t.FailNow() + } + data := []byte("hello world") + encrypted := RsaEncrypt(data, "rsa_public.pem") + decrypted := RsaDecrypt(encrypted, "rsa_private.pem") + + assert := internal.NewAssert(t, "TestRsaEncrypt") + assert.Equal(string(data), string(decrypted)) +} diff --git a/cryptor/rsa.go b/cryptor/rsa.go deleted file mode 100644 index dfc75e2..0000000 --- a/cryptor/rsa.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2021 dudaodong@gmail.com. All rights reserved. -// Use of this source code is governed by MIT license - -// Package cryptor implements some util functions to encrypt and decrypt. -package cryptor - -import ( - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "os" -) - -// GenerateRsaKey make a rsa private key, and return key file name -// Generated key file is `rsa_private.pem` and `rsa_public.pem` in current path -func GenerateRsaKey(keySize int, priKeyFile, pubKeyFile string) error { - // private key - privateKey, err := rsa.GenerateKey(rand.Reader, keySize) - if err != nil { - return err - } - - derText := x509.MarshalPKCS1PrivateKey(privateKey) - - block := pem.Block{ - Type: "rsa private key", - Bytes: derText, - } - - //file,err := os.Create("rsa_private.pem") - file, err := os.Create(priKeyFile) - if err != nil { - panic(err) - } - err = pem.Encode(file, &block) - if err != nil { - return err - } - - file.Close() - - // public key - publicKey := privateKey.PublicKey - - derpText, err := x509.MarshalPKIXPublicKey(&publicKey) - if err != nil { - return err - } - - block = pem.Block{ - Type: "rsa public key", - Bytes: derpText, - } - - file, err = os.Create(pubKeyFile) - if err != nil { - return err - } - - err = pem.Encode(file, &block) - if err != nil { - return err - } - - file.Close() - - return nil -} - -// RsaEncrypt encrypt data with ras algorithm -func RsaEncrypt(data []byte, pubKeyFileName string) []byte { - file, err := os.Open(pubKeyFileName) - if err != nil { - panic(err) - } - fileInfo, err := file.Stat() - if err != nil { - panic(err) - } - defer file.Close() - buf := make([]byte, fileInfo.Size()) - - _, err = file.Read(buf) - if err != nil { - panic(err) - } - - block, _ := pem.Decode(buf) - - pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes) - if err != nil { - panic(err) - } - pubKey := pubInterface.(*rsa.PublicKey) - - cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, data) - if err != nil { - panic(err) - } - return cipherText -} - -// RsaDecrypt decrypt data with ras algorithm -func RsaDecrypt(data []byte, privateKeyFileName string) []byte { - file, err := os.Open(privateKeyFileName) - if err != nil { - panic(err) - } - fileInfo, err := file.Stat() - if err != nil { - panic(err) - } - buf := make([]byte, fileInfo.Size()) - defer file.Close() - - _, err = file.Read(buf) - if err != nil { - panic(err) - } - - block, _ := pem.Decode(buf) - - priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - panic(err) - } - - plainText, err := rsa.DecryptPKCS1v15(rand.Reader, priKey, data) - if err != nil { - panic(err) - } - return plainText -} diff --git a/cryptor/rsa_test.go b/cryptor/rsa_test.go deleted file mode 100644 index e7a6b52..0000000 --- a/cryptor/rsa_test.go +++ /dev/null @@ -1,20 +0,0 @@ -package cryptor - -import ( - "testing" - - "github.com/duke-git/lancet/v2/internal" -) - -func TestRsaEncrypt(t *testing.T) { - err := GenerateRsaKey(4096, "rsa_private.pem", "rsa_public.pem") - if err != nil { - t.FailNow() - } - data := []byte("hello world") - encrypted := RsaEncrypt(data, "rsa_public.pem") - decrypted := RsaDecrypt(encrypted, "rsa_private.pem") - - assert := internal.NewAssert(t, "TestRsaEncrypt") - assert.Equal(string(data), string(decrypted)) -} diff --git a/docs/cryptor.md b/docs/cryptor.md index 6c37035..b56da45 100644 --- a/docs/cryptor.md +++ b/docs/cryptor.md @@ -5,10 +5,10 @@ Package cryptor contains some functions for data encryption and decryption. Supp ## Source: -- [https://github.com/duke-git/lancet/blob/main/cryptor/aes.go](https://github.com/duke-git/lancet/blob/main/cryptor/aes.go) -- [https://github.com/duke-git/lancet/blob/main/cryptor/des.go](https://github.com/duke-git/lancet/blob/main/cryptor/des.go) - [https://github.com/duke-git/lancet/blob/main/cryptor/basic.go](https://github.com/duke-git/lancet/blob/main/cryptor/basic.go) -- [https://github.com/duke-git/lancet/blob/main/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/main/cryptor/rsa.go) +- [https://github.com/duke-git/lancet/blob/main/cryptor/encrypt.go](https://github.com/duke-git/lancet/blob/main/cryptor/encrypt.go) + +
diff --git a/docs/cryptor_zh-CN.md b/docs/cryptor_zh-CN.md index 7c65898..23c84b3 100644 --- a/docs/cryptor_zh-CN.md +++ b/docs/cryptor_zh-CN.md @@ -5,10 +5,8 @@ cryptor加密包支持数据加密和解密,获取md5,hash值。支持base64 ## 源码: -- [https://github.com/duke-git/lancet/blob/main/cryptor/aes.go](https://github.com/duke-git/lancet/blob/main/cryptor/aes.go) -- [https://github.com/duke-git/lancet/blob/main/cryptor/des.go](https://github.com/duke-git/lancet/blob/main/cryptor/des.go) - [https://github.com/duke-git/lancet/blob/main/cryptor/basic.go](https://github.com/duke-git/lancet/blob/main/cryptor/basic.go) -- [https://github.com/duke-git/lancet/blob/main/cryptor/rsa.go](https://github.com/duke-git/lancet/blob/main/cryptor/rsa.go) +- [https://github.com/duke-git/lancet/blob/main/cryptor/encrypt.go](https://github.com/duke-git/lancet/blob/main/cryptor/encrypt.go)