Not able to encrypt using public key in golang

2020-05-10 08:46发布

问题:

I am using golang crypto library.

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
}

I am getting following errors

panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x40e86d6].

How to handle it? How to encrypt using PKCS1?

Console:-

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

code for 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 PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1Ibsf4IGAs1ymoew4hR MQUJwIGotca3kiHOeZzuzosuw58z8FFEDQt+PcxjTsx3mvo0uK04oL5CGorQZrTl jJroZj5B2IwmHu2l1wpoKjaPbQDWu8RoIKlObaq9ENcqmH2/yvxUIBcJ0M9e5Tky UslTmqUdZCSDljPO+u30HkBVRqs5Z/bE82BfYMKJ3oDBdWMfiM2nyxGb9ynlml5B dC3USyVIr9NE7NEW5y78ru2F1/zmnPdfnOp4FgsgwLrinML7LZ+TUKT2zfwsVhJK IKl6WFwDQUspi1Oo5km3AsvGtGqBynCyWtj3ZPHMlCQplEusDmF9flyiABgvBrwk uQIDAQAB -----END RSA PUBLIC KEY-----


回答1:

In the playground link you shared, your PEM key string is not formatted properly, it needs to be exactly like this:

    const pubPEM = `
-----BEGIN RSA PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAz1Ibsf4IGAs1ymoew4hR
MQUJwIGotca3kiHOeZzuzosuw58z8FFEDQt+PcxjTsx3mvo0uK04oL5CGorQZrTl
jJroZj5B2IwmHu2l1wpoKjaPbQDWu8RoIKlObaq9ENcqmH2/yvxUIBcJ0M9e5Tky
UslTmqUdZCSDljPO+u30HkBVRqs5Z/bE82BfYMKJ3oDBdWMfiM2nyxGb9ynlml5B
dC3USyVIr9NE7NEW5y78ru2F1/zmnPdfnOp4FgsgwLrinML7LZ+TUKT2zfwsVhJK
IKl6WFwDQUspi1Oo5km3AsvGtGqBynCyWtj3ZPHMlCQplEusDmF9flyiABgvBrwk
uQIDAQAB
-----END RSA PUBLIC KEY-----`

If I grab the example from x509.ParsePKIXPublicKey and pass it a properly formatted key, it works: https://play.golang.org/p/-wPYh7gxr5P

A few more notes on your original code:

  • you are merely printing errors, they should be returned as well and checked
  • you are not checking whether the returned key is nil which can silently happen when block == nil
  • you should check that the unparsed portion returned by pem.Decode is empty