瀏覽代碼

aes、rsa解密

maxiaoshan 2 年之前
父節點
當前提交
d26d426fc2
共有 2 個文件被更改,包括 85 次插入0 次删除
  1. 49 0
      src/spiderutil/aes.go
  2. 36 0
      src/spiderutil/rsa.go

+ 49 - 0
src/spiderutil/aes.go

@@ -0,0 +1,49 @@
+package spiderutil
+
+import (
+	"crypto/aes"
+)
+
+//aes ecb加密
+func AesECBEncrypt(data, key []byte) []byte {
+	cipher, _ := aes.NewCipher(generateKey([]byte(key)))
+	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))
+	// 分组分块加密
+	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
+}
+
+//aes ecb解密
+func AesECBDecrypter(data, key []byte) []byte {
+	cipher, _ := aes.NewCipher(generateKey(key))
+	decrypted := make([]byte, len(data))
+	for bs, be := 0, cipher.BlockSize(); bs < len(data); bs, be = bs+cipher.BlockSize(), be+cipher.BlockSize() {
+		cipher.Decrypt(decrypted[bs:be], data[bs:be])
+	}
+	trim := 0
+	if len(decrypted) > 0 {
+		trim = len(decrypted) - int(decrypted[len(decrypted)-1])
+	}
+
+	return decrypted[:trim]
+}
+
+func generateKey(key []byte) (genKey []byte) {
+	genKey = make([]byte, 16)
+	copy(genKey, key)
+	for i := 16; i < len(key); {
+		for j := 0; j < 16 && i < len(key); j, i = j+1, i+1 {
+			genKey[j] ^= key[i]
+		}
+	}
+	return genKey
+}

+ 36 - 0
src/spiderutil/rsa.go

@@ -0,0 +1,36 @@
+package spiderutil
+
+import (
+	"crypto/rsa"
+	"crypto/x509"
+	"encoding/pem"
+)
+
+//rsa私钥解密
+func DecryptWithPrivateKey(ciphertext, privateKeyStr []byte) []byte {
+	// 将PEM编码的私钥解码为x509格式的数据块
+	block, _ := pem.Decode(privateKeyStr)
+	if block == nil {
+		return nil
+	}
+
+	// 解析DER编码的私钥,得到一个asn1.BitString类型的数据
+	parsedKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
+	if err != nil {
+		return nil
+	}
+
+	// 将解析后的私钥转换为RSA私钥类型
+	privateKey, ok := parsedKey.(*rsa.PrivateKey)
+	if !ok {
+		return nil
+	}
+
+	// 使用RSA私钥解密数据
+	plaintext, err := rsa.DecryptPKCS1v15(nil, privateKey, ciphertext)
+	if err != nil {
+		return nil
+	}
+	// 返回解密后的原始数据
+	return plaintext
+}