Skip to content

Commit

Permalink
u
Browse files Browse the repository at this point in the history
  • Loading branch information
mooncake9527 committed Sep 14, 2024
1 parent 57c67f1 commit 2efbcf9
Show file tree
Hide file tree
Showing 23 changed files with 473 additions and 1,247 deletions.
121 changes: 121 additions & 0 deletions encoding/encrypt/aes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package encryptUtil

import (
"crypto/aes"
"crypto/cipher"
"github.com/mooncake9527/x/xerrors/xerror"
)

//func main() {
// key := []byte("myverystrongpasswordo32bitlength") // 32 bytes key for AES-256
// plaintext := []byte("Hello, World!")
//
// block, err := aes.NewCipher(key)
// if err != nil {
// panic(err)
// }
//
// ciphertext := make([]byte, len(plaintext))
// stream := cipher.NewCTR(block, make([]byte, block.BlockSize()))
// stream.XORKeyStream(ciphertext, plaintext)
//
// fmt.Printf("Encrypted: %s\n", base64.StdEncoding.EncodeToString(ciphertext))
//
// decrypted := make([]byte, len(ciphertext))
// stream = cipher.NewCTR(block, make([]byte, block.BlockSize()))
// stream.XORKeyStream(decrypted, ciphertext)
//
// fmt.Printf("Decrypted: %s\n", decrypted)
//}

func AESEncrypt(plaintext []byte, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, xerror.New(err.Error())
}
ciphertext := make([]byte, len(plaintext))
stream := cipher.NewCTR(block, make([]byte, block.BlockSize()))
stream.XORKeyStream(ciphertext, plaintext)
return ciphertext, nil
}

func AESDecrypt(encrypted, key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
return nil, xerror.New(err.Error())
}
decrypted := make([]byte, len(encrypted))
stream := cipher.NewCTR(block, make([]byte, block.BlockSize()))
stream.XORKeyStream(decrypted, encrypted)
return decrypted, nil
}

//
//// ECB PKCS5 加密
//func AESEncrypt(src, key []byte) []byte {
// block, err := aes.NewCipher(key)
// if err != nil {
// fmt.Println("txn put fail: ", err)
// return nil
// }
// ecb := NewECBEncrypter(block)
// content := []byte(src)
// content = PKCS5Padding(content, block.BlockSize())
// des := make([]byte, len(content))
// ecb.CryptBlocks(des, content)
// return des
//}
//
//func AESDecrypt(crypted, key []byte) []byte {
// block, err := aes.NewCipher(key)
// if err != nil {
// fmt.Println("err is:", err)
// }
// ecb := NewECBDecrypter(block)
// origData := make([]byte, len(crypted))
// ecb.CryptBlocks(origData, crypted)
// origData = PKCS5UnPadding(origData)
// fmt.Println("source is :", origData, string(origData))
// return origData
//}
//
//func AESSHA1PRNG(keyBytes []byte, encryptLength int) []byte {
// hashs := SHA1(SHA1(keyBytes))
// maxLen := len(hashs)
// realLen := encryptLength / 8
// if realLen > maxLen {
// return nil
// }
//
// return hashs[0:realLen]
//}
//
//func SHA1(data []byte) []byte {
// h := sha1.New()
// h.Write(data)
// return h.Sum(nil)
//}
//
//func EncryptAES(data, aesKey string) string {
// // w4sB8ExNU7wD1xczU+Y/vg==
// keyAsArray := getKeyByStr(aesKey)
// keyAsArray = AESSHA1PRNG(keyAsArray, 128)
// //encryptedByteArray:=AESEncrypt([]byte("ssss"),keyAsArray[0:len(keyAsArray)/2])
// encryptedByteArray := AESEncrypt([]byte(data), keyAsArray)
// encryptedByteArrayAsStr := base64.StdEncoding.EncodeToString(encryptedByteArray)
// //encryptedByteArrayAsStr=encryptedByteArrayAsStr[0:len(encryptedByteArrayAsStr)-3]
// fmt.Println(encryptedByteArrayAsStr)
// return encryptedByteArrayAsStr
//}
//
//func DecryptAES(data, aesKey string) string {
// keyAsArray := getKeyByStr(aesKey)
// keyAsArray = AESSHA1PRNG(keyAsArray, 128)
// encryptedByteArray, _ := base64.StdEncoding.DecodeString(data)
// fmt.Println(encryptedByteArray)
// //fmt.Println(string(encryptedByteArray))
// content := AESDecrypt(encryptedByteArray, keyAsArray)
// encryptedByteArrayAsStr := string(content)
// fmt.Println(encryptedByteArrayAsStr)
// return encryptedByteArrayAsStr
//}
31 changes: 31 additions & 0 deletions encoding/encrypt/aes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package encryptUtil

import (
"encoding/base64"
"testing"
)

func TestAESEncrypt(t *testing.T) {
message := []byte("hello world")
key := []byte("myverystrongpasswordo32bitlength")

encryptedMessage, err := AESEncrypt(message, key)
if err != nil {
t.Error(err)
}
encryptedMessageString := base64.StdEncoding.EncodeToString(encryptedMessage)

//////////

encryptedMessageBytes, err := base64.StdEncoding.DecodeString(encryptedMessageString)
if err != nil {
t.Error(err)
}
decryptedMessage, err := AESDecrypt(encryptedMessageBytes, key)
if err != nil {
t.Error(err)
}
if string(decryptedMessage) != string(message) {
t.Error("decrypted message is not equal to original message")
}
}
112 changes: 112 additions & 0 deletions encoding/encrypt/rsa.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package encryptUtil

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"github.com/mooncake9527/x/xerrors/xerror"
)

func ParsePublicKey(publicKeyStr string) (*rsa.PublicKey, error) {
publicKeyBlock, _ := pem.Decode([]byte(publicKeyStr))
if publicKeyBlock == nil || publicKeyBlock.Type != "PUBLIC KEY" {
return nil, xerror.New("无效的公钥")
}
publicKey, err := x509.ParsePKIXPublicKey(publicKeyBlock.Bytes)
if err != nil {
return nil, err
}
rsaPublicKey, ok := publicKey.(*rsa.PublicKey)
if !ok {
return nil, xerror.New("无效的RSA公钥")
}
return rsaPublicKey, nil
}

// 将字符串转换为RSA私钥
func ParsePrivateKey(privateKeyStr string) (*rsa.PrivateKey, error) {
privateKeyBlock, _ := pem.Decode([]byte(privateKeyStr))
if privateKeyBlock == nil || privateKeyBlock.Type != "RSA PRIVATE KEY" {
return nil, xerror.New("无效的私钥")
}
privateKey, err := x509.ParsePKCS1PrivateKey(privateKeyBlock.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
}

func RSAEncrypt(message, pubKey string) (string, error) {
publicKey, err := ParsePublicKey(pubKey)
if err != nil {
return "", xerror.New(err.Error())
}
encryptedMessage, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(message))
if err != nil {
return "", xerror.New(err.Error())
}

return base64.StdEncoding.EncodeToString(encryptedMessage), nil
}

func RSADecrypt(encryptedMsg, priKey string) (string, error) {
privateKey, err := ParsePrivateKey(priKey)
if err != nil {
return "", xerror.New(err.Error())
}
cipherText, err := base64.StdEncoding.DecodeString(encryptedMsg)
if err != nil {
return "", xerror.New(err.Error())
}
decryptedMessage, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
if err != nil {
return "", xerror.New(err.Error())
}
return string(decryptedMessage[:]), nil

}

func GenerateRsaKey(len int) (string, string, error) {
if len == 0 {
len = 2048
}
key, err := rsa.GenerateKey(rand.Reader, len)
if err != nil {
return "", "", xerror.Newf("无法生成RSA密钥对:%s", err.Error())
}
publicKeyStr, err := PublicKeyToString(&key.PublicKey)
if err != nil {
return "", "", err
}
privateKeyStr, err := PrivateKeyToString(key)
if err != nil {
return "", "", err
}
return publicKeyStr, privateKeyStr, nil

}

func PrivateKeyToString(privateKey *rsa.PrivateKey) (string, error) {
privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
privateKeyBlock := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: privateKeyBytes,
}
privateKeyStr := string(pem.EncodeToMemory(privateKeyBlock))
return privateKeyStr, nil
}

func PublicKeyToString(publicKey *rsa.PublicKey) (string, error) {
publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return "", xerror.New(err.Error())
}
publicKeyBlock := &pem.Block{
Type: "PUBLIC KEY",
Bytes: publicKeyBytes,
}
publicKeyStr := string(pem.EncodeToMemory(publicKeyBlock))
return publicKeyStr, nil
}
Loading

0 comments on commit 2efbcf9

Please sign in to comment.