我正在使用golang加密库。
func encrypt(publicKey *rsa.PublicKey, message string) []byte {
msg := []byte(message)
println(message, msg)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, msg)
if err != nil {
println("Error:", err.Error())
}
return cipherText
}
我遇到以下错误
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40e86d6]
。
如何处理?如何使用PKCS1加密?
控制台:-
Verifying local data [20/32]0xc0000d37b0
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40e8456]
goroutine 1 [running]:
crypto/rsa.checkPub(...)
/usr/local/Cellar/go/1.12.5/libexec/src/crypto/rsa/rsa.go:75
crypto/rsa.EncryptPKCS1v15(0x4334500, 0xc0000a0060, 0x0, 0xc0000d37b0, 0x14, 0x20, 0x402ddb2, 0x2, 0x42df45d, 0x1c, ...)
/usr/local/Cellar/go/1.12.5/libexec/src/crypto/rsa/pkcs1v15.go:42 +0x56
main.encrypt(0x0, 0x42dcb46, 0x14, 0x0, 0x0, 0x0)
/Users/weri/goModules/src/EastWinds/CoreUtils.go:195 +0x129
main.main()
/Users/weri/goModules/src/EastWinds/main.go:26 +0x11e
publicKey的代码:-
func importPublicKey(publicKeyString string) *rsa.PublicKey {
block, _ := pem.Decode([]byte(publicKeyString))
if block == nil {
return nil
}
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
println("Error: ", err.Error())
return nil
}
switch pub := pub.(type) {
case *rsa.PublicKey:
println(pub.N)
return pub
default:
break // fall through
}
return nil
}
publicKey:-
----- BEGIN RSA公钥----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1Ibsf4IGAs1ymoew4hR MQUJwIGotca3kiHOeZzuzosuw58z8FFEDQt + PcxjTsx3mvo0uK04oL5CGorQZrTl jJroZj5B2IwmHu2l1wpoKjaPbQDWu8RoIKlObaq9ENcqmH2 / yvxUIBcJ0M9e5Tky UslTmqUdZCSDljPO + u30HkBVRqs5Z / bE82BfYMKJ3oDBdWMfiM2nyxGb9ynlml5B dC3USyVIr9NE7NEW5y78ru2F1 / zmnPdfnOp4FgsgwLrinML7LZ + TUKT2zfwsVhJK IKl6WFwDQUspi1Oo5km3AsvGtGqBynCyWtj3ZPHMlCQplEusDmF9flyiABgvBrwk 齐达卡 -----结束RSA公钥-----
答案 0 :(得分:3)
在您共享的playground链接中,您的PEM密钥字符串格式不正确,它必须完全像这样:
const pubPEM = `
-----BEGIN RSA PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1Ibsf4IGAs1ymoew4hR
MQUJwIGotca3kiHOeZzuzosuw58z8FFEDQt+PcxjTsx3mvo0uK04oL5CGorQZrTl
jJroZj5B2IwmHu2l1wpoKjaPbQDWu8RoIKlObaq9ENcqmH2/yvxUIBcJ0M9e5Tky
UslTmqUdZCSDljPO+u30HkBVRqs5Z/bE82BfYMKJ3oDBdWMfiM2nyxGb9ynlml5B
dC3USyVIr9NE7NEW5y78ru2F1/zmnPdfnOp4FgsgwLrinML7LZ+TUKT2zfwsVhJK
IKl6WFwDQUspi1Oo5km3AsvGtGqBynCyWtj3ZPHMlCQplEusDmF9flyiABgvBrwk
uQIDAQAB
-----END RSA PUBLIC KEY-----`
如果我从x509.ParsePKIXPublicKey抓取示例并将其传递给正确格式的密钥,则它可以正常工作:https://play.golang.org/p/-wPYh7gxr5P
关于原始代码的其他说明:
nil
,而在block == nil
时会默默地出现pem.Decode
返回的未分析部分为空