实现方法
不废话,直接拿去用吧
func EncodeByPublickKey(plainText []byte, publicKeyBase64 string) (string, error) {
// Base64 decode.
publicKeyBinary, err := base64.StdEncoding.DecodeString(publicKeyBase64)
if err != nil {
return "", err
}
// rsa.PublicKey is a big.Int (N: modulus) and an integer (E: exponent).
var pubKey rsa.PublicKey
if rest, err := asn1.Unmarshal(publicKeyBinary, &pubKey); err != nil {
return "", err
} else if len(rest) != 0 {
return "", fmt.Errorf("rest is not nil")
}
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, &pubKey, plainText)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(cipherText), nil
}
// 或者
func EncodeByPublickKeyX(plainText []byte, publicKeyBase64 string) (string, error) {
// Base64 decode.
publicKeyBinary, err := base64.StdEncoding.DecodeString(publicKeyBase64)
if err != nil {
return "", err
}
rsaPk, err := x509.ParsePKIXPublicKey(publicKeyBinary)
if err != nil {
return "", err
}
var pubKey *rsa.PublicKey = rsaPk.(*rsa.PublicKey)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, pubKey, plainText)
if err != nil {
return "", err
}
return base64.StdEncoding.EncodeToString(cipherText), nil
}
测试函数
注意参数 没有加-----BEGIN RSA PUBLIC KEY-----
和-----END RSA PUBLIC KEY-----
func TestTiremalDectict(t *testing.T) {
// EncodeByPublickKey()
// publicKeyBase64 := "MIGJAoGBAJJYXgBem1scLKPEjwKrW8+ci3B/YNN3aY2DJ3lc5e2wNc0SmFikDpow1TdYcKl2wdrXX7sMRsyjTk15IECMezyHzaJGQ9TinnkQixJ+YnlNdLC04TNWOg13plyahIXBforYAjYl2wVIA8Yma2bEQFhmAFkEX1A/Q1dIKy6EfQ+xAgMBAAE="
// EncodeByPublickKeyX()
publicKeyBase64 := `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmxkVEQai9aHv4snvAvehFifr0YD6h3OZVil0NFLcvSLJQTH6Oj0d4D1NjJClHYRxVBwOxu70ozoIGLAr18JaJaEYzzEgdGMb1f9xjviShOON2iJdYAgS7Skq8hgDWZnlFCQyt0ZnCGf+gfG4J7dxWb41fezeap824sZMlKVxFU7SCq0rcgNt3B7oaZs7yx1csdHzYT27iA0yu983m/qi4nLweQOdrl3LlTJzoVh+xa9o3LlvO5IGevOEIhFDS8AXjALpkIgbo/CEY6maZkLIKmP/6JemWMfjAcpY7Tx7gtiQ/DvrABMFwVoBIy9MzASaZVhx37kr8o/cJHUsV13JkwIDAQAB`
textEncryptBase64, err := EncodeByPublickKeyX([]byte("123456"), publicKeyBase64)
if err != nil {
fmt.Println(err)
}
fmt.Println(textEncryptBase64)
}
你导入过程中遇到的error
asn1: structure error: tags don't match (16 vs {class:0 tag:29 length:69 isCompound:false}) {optional:false explicit:false application:false private:false defaultValue:<nil> tag:<nil> stringType:0 timeType:0 set:false omitEmpty:false} publicKeyInfo @2
上面这个错误出现 则使用 EncodeByPublickKeyX 这个函数
Could not parse DER encoded public key (encryption key)
.加载公钥Block为空
这个尝试看下RSA.PublickKey 格式是否是我们想要的
Could not parse DER encoded public key (encryption key)
crypto/rsa: message too long for RSA public key size
你要加密的内容有点长了