golang 通过已知的priKey 对字符串做 RSA加密
要使用已知的私钥对字符串进行RSA加密,需要进行以下步骤:
- 将私钥加载到RSA密钥对结构中。私钥可以是PEM格式或DER格式。如果是PEM格式,可以使用
ParsePKCS1PrivateKey或ParsePKCS8PrivateKey函数来加载私钥。如果是DER格式,可以使用x509.ParsePKCS1PrivateKey或x509.ParsePKCS8PrivateKey函数来加载私钥。
// 示例代码加载PEM格式的私钥
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io/ioutil"
)
func loadPrivateKeyFromPEM(pemFilePath string) (*rsa.PrivateKey, error) {
pemData, err := ioutil.ReadFile(pemFilePath)
if err != nil {
return nil, err
}
block, _ := pem.Decode(pemData)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
}
- 使用加载的私钥创建RSA加密器。
func createRSACipher(privateKey *rsa.PrivateKey) (*rsa.Encrypter, error) {
publicKey := &privateKey.PublicKey
cipher, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, []byte{})
if err != nil {
return nil, err
}
return cipher, nil
}
- 使用RSA加密器对字符串进行加密。
func encryptString(cipher *rsa.Encrypter, plaintext string) ([]byte, error) {
ciphertext, err := cipher.Encrypt([]byte(plaintext), nil)
if err != nil {
return nil, err
}
return ciphertext, nil
}
完整的示例代码如下:
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
)
func loadPrivateKeyFromPEM(pemFilePath string) (*rsa.PrivateKey, error) {
pemData, err := ioutil.ReadFile(pemFilePath)
if err != nil {
return nil, err
}
block, _ := pem.Decode(pemData)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return privateKey, nil
}
func createRSACipher(privateKey *rsa.PrivateKey) (*rsa.Encrypter, error) {
publicKey := &privateKey.PublicKey
cipher, err := rsa.EncryptOAEP(sha256.New(), rand.Reader, publicKey, []byte{})
if err != nil {
return nil, err
}
return cipher, nil
}
func encryptString(cipher *rsa.Encrypter, plaintext string) ([]byte, error) {
ciphertext, err := cipher.Encrypt([]byte(plaintext), nil)
if err != nil {
return nil, err
}
return ciphertext, nil
}
func main() {
privateKey, err := loadPrivateKeyFromPEM("private_key.pem")
if err != nil {
fmt.Printf("Failed to load private key: %v\n", err)
return
}
cipher, err := createRSACipher(privateKey)
if err != nil {
fmt.Printf("Failed to create RSA cipher: %v\n", err)
return
}
plaintext := "Hello, RSA encryption!"
ciphertext, err := encryptString(cipher, plaintext)
if err != nil {
fmt.Printf("Failed to encrypt string: %v\n", err)
return
}
fmt.Printf("Ciphertext: %x\n", ciphertext)
}
请注意,上述代码仅为示例,实际使用时需要根据私钥的格式和加密算法进行相应的调整
原文地址: http://www.cveoy.top/t/topic/iYNG 著作权归作者所有。请勿转载和采集!