package crypter import ( "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "errors" "log" "os" ) func RSA_Decode(encryptedData string, privateKey string) (string, error) { // 解码PEM格式的私钥 block, _ := pem.Decode([]byte(privateKey)) if block == nil { // fmt.Println("Failed to decode PEM private key") return "", errors.New("私钥解码失败") } // 解析RSA私钥 privKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { log.Println("Failed to parse RSA private key", err) return "", errors.New("私钥解析失败") } // 解密Base64编码的数据 encryptedBytes, _ := base64.StdEncoding.DecodeString(encryptedData) // 使用RSA私钥进行解密 decryptedBytes, err := rsa.DecryptPKCS1v15(rand.Reader, privKey, encryptedBytes) if err != nil { // fmt.Println("Failed to decrypt data") return "", errors.New("解密失败") } // 将解密后的字节转换为字符串 return string(decryptedBytes), nil } func RSA_Encode(public_key string, msg string) (string, error) { // publicKeyFile, err := ioutil.ReadFile(public_key) // if err != nil { // log.Println("Failed to read public key file:", err) // return "", errors.New("没有公钥") // } block, _ := pem.Decode([]byte(public_key)) if block == nil { log.Println("Failed to decode public key PEM.") return "", errors.New("公钥解码失败") } publicKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { log.Println("Failed to parse public key:", err) return "", errors.New("公钥解析失败") } rsaPublicKey, ok := publicKey.(*rsa.PublicKey) if !ok { log.Println("Failed to get RSA public key.") return "", errors.New("公钥错误") } plainText := []byte(msg) cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, plainText) if err != nil { log.Println("Failed to encrypt data:", err) return "", errors.New("加密失败") } return string(cipherText), nil } func Create(private_pem_file, public_pem_file string) { // 生成 RSA 密钥对 privateKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { log.Println("无法生成私钥:", err) return } // 将私钥保存到文件 privateKeyFile, err := os.Create(private_pem_file) if err != nil { log.Println("无法创建私钥文件:", err) return } defer privateKeyFile.Close() privateKeyBlock := &pem.Block{ Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey), } err = pem.Encode(privateKeyFile, privateKeyBlock) if err != nil { log.Println("无法写入私钥文件:", err) return } log.Println("私钥已保存到", private_pem_file) // 生成公钥 publicKey := &privateKey.PublicKey // 将公钥保存到文件 publicKeyFile, err := os.Create(public_pem_file) if err != nil { log.Println("无法创建公钥文件:", err) return } defer publicKeyFile.Close() publicKeyBytes, err := x509.MarshalPKIXPublicKey(publicKey) if err != nil { log.Println("无法编码公钥:", err) return } publicKeyBlock := &pem.Block{ Type: "PUBLIC KEY", Bytes: publicKeyBytes, } err = pem.Encode(publicKeyFile, publicKeyBlock) if err != nil { log.Println("无法写入公钥文件:", err) return } log.Println("公钥已保存到", public_pem_file) }