Search code examples
gopgpopenpgp

How to Encrypt a String to an ASCII armored file in go


I'm at the moment realy struggeling in finding the error in my code - the task is to encrypt a string into a pgp ASCII armored file - a simple thing one could think.

I use the following function, inspired by this gist:

// pgp encryption using the pgp RSA certificate
// massive thx to https://gist.github.com/jyap808/8250124
func encToFile(secretString string, filename string) (string, error) {
  log.Println("Public Keyring: ", publicKeyring)

  encryptionType := "PGP MESSAGE"

  // Read in public key
  keyringFileBuffer, _ := os.Open(publicKeyring)
  defer keyringFileBuffer.Close() 
  entityList, err := openpgp.ReadArmoredKeyRing(keyringFileBuffer) 
  check(err)

  encbuf := bytes.NewBuffer(nil)
  w, err := armor.Encode(encbuf, encryptionType, nil) // the encoder somehow makes this into ASCII armor
  check(err)

  plaintext, err := openpgp.Encrypt(w, entityList, nil, nil, nil)
  check(err)

  message := []byte(secretString)
  _, err = plaintext.Write(message)

  plaintext.Close()
  w.Close()

  // Output encrypted/encoded string
  log.Println("Writing Encrypted Secred to: ", filename)
  // we write the file into a file

  err = ioutil.WriteFile(filename, encbuf.Bytes(), 0644)
  check(err)

  log.Println("File:\n", encbuf.String())


  return encbuf.String(), nil
}

However, the guys on the other end get this error message:

gpg: encrypted with RSA key, ID 5BE299DC
gpg: decryption failed: No secret key

Hints and suggestion would be very welcome!


Solution

  • However, the guys on the other end get this error message:

    gpg: encrypted with RSA key, ID 5BE299DC
    gpg: decryption failed: No secret key
    

    If you encrypted for the right key, I don't think you did anything wrong. Looking at that key on the key servers, you encrypted to the newest (and only) encryption subkey.

    If the "guy on the other end" gets an error message indicating that he would not hold the secret key, then either

    • you use the wrong key for encryption,
    • "the other guy" gave you the wrong key or
    • "the other guy" messed up himself.

    You can verify what's going wrong by passing the encrypted contents to gpg --list-packets or pgpdump, which list the OpenPGP packets contained in the message and are very helpful at debugging OpenPGP issues.