Search code examples
securitygocryptographyrsapem

Is it safe storing an encrypted PEM block?


I have some experience using Go, but now I don't really understand the complexity in security of what I am doing, so I need to ask.

I am creating an RSA private key, converting to PEM and then encryping it with a passphrase.

So, how secure is to store it in a public place?

I'm not looking for answers like "it's ok, just change the passphrase over time", I really want to know which mechanism of cypher Golang is using to do it and if is safe to leave the encrypted PEM in, for example, a public blockchain and why I can do it or why I cannot.

I'm leaving here the code I am using right now:

func New(passphrase string)(*pem.Block, error){
    pk, err := createPrivateKey(2048)
    if err != nil {
        return false, err
    }
    pem := getPemFromPK(pk)
    block, err := EncryptPEMBlock(pem,passphrase)
    if err != nil {
        return false, err
    }

    return block,nil
}

func createPrivateKey(bits int) (*rsa.PrivateKey, error){
    pk, err := rsa.GenerateKey(rand.Reader, bits)
    if err != nil {
        return nil, err
    }
    return pk,nil
}

func getPemFromPK(pk *rsa.PrivateKey) (*pem.Block){
    block := &pem.Block{
        Type:  "RSA PRIVATE KEY",
        Bytes: x509.MarshalPKCS1PrivateKey(pk),
    }
    return block
}

func EncryptPEMBlock(block *pem.Block, passphrase string) (*pem.Block, error){
    block, err := x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(passphrase), x509.PEMCipherAES256)
    if err != nil {
        return nil, err
    }
    return block,nil
}

Thank you very much.

Edit:

As an answer here and other forums, it is not recommended to publish in public any type of private key, even if encrypted.

This topic is answered.


Solution

  • You are making a mistake in your thinking about what a private key is and what a passphrase is. The passphrase is used to encrypt and unencrypt your private key - if you are storing a key file which needs a passphrase to be used, then that file contains your encrypted key.

    If you store the "private key" as you say, it sounds like you wish to publicly store the unencrypted key. However, even if you publish an encrypted private key on a public online repository, there's many ways to crack a passphrase. If the passphrase is short or unsecure in other ways, the attacker now has your private key. If they target you and gain access to a machine of yours that has used this key in an application (i.e. bash), then they can just access bash history log to find the passphrase.

    Sometimes actually, it's trivial to keylog someone in a targeted attack.

    There are many many things that can go wrong if you store an unencrypted private key online.