Search code examples
c#bouncycastleopenpgp

How does Bouncy Castle API know which key to encrypt with?


I'm curious about the Bouncy Castle API process for handling multiple public keys to encrypt data. For example, if i have 3 different clients that would like me to encrypt data and send to them using their public key for encryption, if i label each clients public key respectively - how does bouncy castle determine that client 1 should be encrypted with public key 1 and not public key 3 (which would be the public key for client 3)?

it would seem from a decrpytion standpoint, that publicKeyEncryptedData has a keyID tag attached with it that can be used to look up the corresponding private key, but i dont understand how it chooses the correct key to encrypt with.


Solution

  • It doesn't. You have to specify all recipients (i.e. certificates to use for encryption). When you are doing encryption using PKCS#7 the process is:

    • Generate random symmetric key (i.e. AES256)
    • encrypt data with symmetric key
    • encrypt symmetric key with public key of the recipient (if X recipients should be able to decrypt then encrypt the symmetric key X-times)
    • put it all together in PKCS#7 (encrypted symmetric key is put in a structure with some identification of the recipient. Usually it is serial number and issuer DN of the certificate which was used for encryption of symmetric key)

    Decryption process is:

    • find recipient able to decrypt the message. PKCS#7 contains serial numbers and issuer DNs of all recipients who should be able to decrypt. Now look in crypto store for a certificate with serial number and issuer DN that has a corresponding private key. It does not matter which private key will be used if you have all recipients private keys in crypto store.
    • use private key to decrypt symmetric key used in the encryption process
    • use symmetric key to decrypt data