1)创建私钥:
openssl genrsa -out private.pem 1024 //密钥长度,1024觉得不够安全的话可以用2048,但是代价也相应增大
2)创建公钥:
openssl rsa -in private.pem -pubout -out public.pem
publicKey <--- public.pem
privateKey <--- private.pem
// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
block, _ := pem.Decode(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 RsaDecrypt(ciphertext []byte) ([]byte, error) {
block, _ := pem.Decode(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)
}
本文介绍如何使用OpenSSL工具生成RSA密钥对,并提供Go语言实现的加密与解密示例代码。首先通过命令行创建私钥和公钥,接着展示如何利用公钥进行数据加密及如何使用私钥完成解密过程。
2131

被折叠的 条评论
为什么被折叠?



