Rustam Ibragimov
Rustam Ibragimov

Reputation: 2707

Load encrypted PKCS1 private key from file

I have a PKCS1 private key in a file and I load it using

b, err := ioutil.ReadFile(path)
if err != nil {
    return nil, err
}

Then, I try to convert it into private key object

block, _ := pem.Decode(b)
der, err := x509.DecryptPEMBlock(block, []byte("qwerty"))
if err != nil {
    return nil, err
}

bytes := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: der})

return x509.ParsePKCS1PrivateKey(bytes)

But this code throws exception in DecryptPEMBlock

x509: no DEK-Info header in block

I didn't find any documentation about this in golang

Upvotes: 3

Views: 3547

Answers (2)

Aravind
Aravind

Reputation: 389

Go does not have package to decode PKCS files it seems

Checkout this link for more details PKCS

I cant find a package to decode PKCS1 keys

Use this package to decode the PKCS8 files, there are some packages to decode PKCS8, PKCS10, PKCS12 but not for PKCS1

Upvotes: 0

Rustam Ibragimov
Rustam Ibragimov

Reputation: 2707

I made a mistake with my private key file and here is a working code

func GetPrivateKey(path string) (*rsa.PrivateKey, error) {
    b, err := ioutil.ReadFile(path)
    if err != nil {
        return nil, err
    }

    block, _ := pem.Decode(b)
    der, err := x509.DecryptPEMBlock(block, []byte(*PrivateKeyPassword))
    if err != nil {
        return nil, err
    }

    return x509.ParsePKCS1PrivateKey(der)
}

P.S. Go does have a package to decrypt PKCS1 private keys, but does not have for PKCS8.

Upvotes: 3

Related Questions