RSA加密/解密

1、生成 RSA 私钥(传统格式)

openssl genrsa -out rsa_private_key.pem 1024

【可选】将传统格式的私钥转换成 PKCS#8 格式的(Java需要使用的私钥需要经过PKCS#8编码,PHP程序不需要,可以直接略过)

openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt

2、生成 RSA 公钥

openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem

3、加密

func RsaEncrypt(origData []byte, publicKey string) ([]byte, error) {
	block, _ := pem.Decode([]byte(publicKey))
	if block == nil {
		return nil, errors.New("public key error")
	}
	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}

func RsaEncryptStr(decrypted string, publicKey string)(string, error){
    origData, err := RsaDecrypt(decrypted, publicKey)
	if err != nil {
		return "", err
	}
	data, err := base64.StdEncoding.DecodeString(origData)
	if err != nil {
		return "", err
	}
	return string(data),nil
}

4、解密

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
)

func RsaDecrypt(ciphertext []byte, privateKey string) ([]byte, error) {
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

func RsaDecryptStr(decrypted string, privateKey string)(string, error){
	data, err := base64.StdEncoding.DecodeString(decrypted)
	if err != nil {
		return "", err
	}
	origData, err := RsaDecrypt(data, privateKey)
	if err != nil {
		return "", err
	}
	return string(origData),nil
}
上一篇:Git


下一篇:解决Linux系统下程序找不到动态库的方法