End-to-End Encryption

Applications can use Pulsar end-to-end encryption (E2EE) to encrypt messages on the producer side and decrypt messages on the consumer side. You can use the public and private key pair that the application configures to perform encryption and decryption. Only the consumers with a valid key can decrypt the encrypted messages.

How it works in Pulsar

Pulsar uses a dynamically generated symmetric session key to encrypt messages (data). You can use the application-provided ECDSA (Elliptic Curve Digital Signature Algorithm) or RSA (Rivest–Shamir–Adleman) key pair to encrypt the session key (data key), so you do not have to share the secret with everyone.

The following figure illustrates how Pulsar encrypts messages on the producer side and decrypts messages on the consumer side.

Pulsar end-to-end encryption

  1. The producer generates a session key regularly (every 4 hours or after publishing a certain number of messages) to encrypt the message payload using a symmetric algorithm, such as AES, and fetches the asymmetric public key every 4 hours. The ciphertext is packed as the message body.
  2. The producer uses the consumer’s public key to encrypt the session key using an asymmetric algorithm, such as RSA, and adds an alias with the encrypted secret to the message header.
  3. The consumer reads the message header and decrypts the session key using its private key.
  4. The consumer uses the decrypted session key to decrypt the message payload.

End-to-End Encryption - 图2note

  • The consumer’s public key is shared with the producer, but only the consumer has the access to the private key.
  • Pulsar does not store the encryption key anywhere in the Pulsar service. If you lose or delete the private key, your message is irretrievably lost and unrecoverable.

Pulsar isolates the key management and only provides interfaces (CryptoKeyReader) to access public keys. For production systems, it’s highly recommended to extend/implement CryptoKeyReader with cloud key management (KMS or CKM) or PKI (Public Key Infrastructure, such as freeIPA).

If the produced messages are consumed across application boundaries, you need to ensure that consumers in other applications have access to one of the private keys that can decrypt the messages. You can do this in two ways:

  • Access the public key that the consumer application provides and add it to the producer’s keys.
  • Grant access to one of the private keys from the pairs that the producer uses.

Get started

Prerequisites

  • Pulsar Java/Python/C++/Node.js client 2.7.1 or later versions.
  • Pulsar Go client 0.6.0 or later versions.

Configure end-to-end encryption

  1. Create both public and private key pairs.

    • ECDSA (for Java and Go clients)
    • RSA (for Python, C++ and Node.js clients)
    1. openssl ecparam -name secp521r1 -genkey -param_enc explicit -out test_ecdsa_privkey.pem
    2. openssl ec -in test_ecdsa_privkey.pem -pubout -outform pem -out test_ecdsa_pubkey.pem
    1. openssl genrsa -out test_rsa_privkey.pem 2048
    2. openssl rsa -in test_rsa_privkey.pem -pubout -outform pkcs8 -out test_rsa_pubkey.pem
  2. Configure a CryptoKeyReader on producers, consumers or readers.

    • Java
    • Python
    • C++
    • Go
    • Node.js
    1. PulsarClient pulsarClient = PulsarClient.builder().serviceUrl("pulsar://localhost:6650").build();
    2. String topic = "persistent://my-tenant/my-ns/my-topic";
    3. // RawFileKeyReader is just an example implementation that's not provided by Pulsar
    4. CryptoKeyReader keyReader = new RawFileKeyReader("test_ecdsa_pubkey.pem", "test_ecdsa_privkey.pem");
    5. Producer<byte[]> producer = pulsarClient.newProducer()
    6. .topic(topic)
    7. .cryptoKeyReader(keyReader)
    8. .addEncryptionKey("myappkey")
    9. .create();
    10. Consumer<byte[]> consumer = pulsarClient.newConsumer()
    11. .topic(topic)
    12. .subscriptionName("my-subscriber-name")
    13. .cryptoKeyReader(keyReader)
    14. .subscribe();
    15. Reader<byte[]> reader = pulsarClient.newReader()
    16. .topic(topic)
    17. .startMessageId(MessageId.earliest)
    18. .cryptoKeyReader(keyReader)
    19. .create();
    1. from pulsar import Client, CryptoKeyReader
    2. client = Client('pulsar://localhost:6650')
    3. topic = 'my-topic'
    4. # CryptoKeyReader is a built-in implementation that reads public key and private key from files
    5. key_reader = CryptoKeyReader('test_rsa_pubkey.pem', 'test_rsa_privkey.pem')
    6. producer = client.create_producer(
    7. topic=topic,
    8. encryption_key='myappkey',
    9. crypto_key_reader=key_reader
    10. )
    11. consumer = client.subscribe(
    12. topic=topic,
    13. subscription_name='my-subscriber-name',
    14. crypto_key_reader=key_reader
    15. )
    16. reader = client.create_reader(
    17. topic=topic,
    18. start_message_id=MessageId.earliest,
    19. crypto_key_reader=key_reader
    20. )
    21. client.close()
    1. Client client("pulsar://localhost:6650");
    2. std::string topic = "persistent://my-tenant/my-ns/my-topic";
    3. // DefaultCryptoKeyReader is a built-in implementation that reads public key and private key from files
    4. auto keyReader = std::make_shared<DefaultCryptoKeyReader>("test_rsa_pubkey.pem", "test_rsa_privkey.pem");
    5. Producer producer;
    6. ProducerConfiguration producerConf;
    7. producerConf.setCryptoKeyReader(keyReader);
    8. producerConf.addEncryptionKey("myappkey");
    9. client.createProducer(topic, producerConf, producer);
    10. Consumer consumer;
    11. ConsumerConfiguration consumerConf;
    12. consumerConf.setCryptoKeyReader(keyReader);
    13. client.subscribe(topic, "my-subscriber-name", consumerConf, consumer);
    14. Reader reader;
    15. ReaderConfiguration readerConf;
    16. readerConf.setCryptoKeyReader(keyReader);
    17. client.createReader(topic, MessageId::earliest(), readerConf, reader);
    1. client, err := pulsar.NewClient(pulsar.ClientOptions{
    2. URL: "pulsar://localhost:6650",
    3. })
    4. if err != nil {
    5. log.Fatal(err)
    6. }
    7. defer client.Close()
    8. topic := "persistent://my-tenant/my-ns/my-topic"
    9. keyReader := crypto.NewFileKeyReader("test_ecdsa_pubkey.pem", "test_ecdsa_privkey.pem")
    10. producer, err := client.CreateProducer(pulsar.ProducerOptions{
    11. Topic: topic,
    12. Encryption: &pulsar.ProducerEncryptionInfo{
    13. KeyReader: keyReader,
    14. Keys: []string{"myappkey"},
    15. },
    16. })
    17. if err != nil {
    18. log.Fatal(err)
    19. }
    20. defer producer.Close()
    21. consumer, err := client.Subscribe(pulsar.ConsumerOptions{
    22. Topic: topic,
    23. SubscriptionName: "my-subscriber-name",
    24. Decryption: &pulsar.MessageDecryptionInfo{
    25. KeyReader: keyReader,
    26. },
    27. })
    28. if err != nil {
    29. log.Fatal(err)
    30. }
    31. defer consumer.Close()
    32. reader, err := client.CreateReader(pulsar.ReaderOptions{
    33. Topic: topic,
    34. Decryption: &pulsar.MessageDecryptionInfo{
    35. KeyReader: keyReader,
    36. },
    37. })
    38. if err != nil {
    39. log.Fatal(err)
    40. }
    41. defer reader.Close()
    1. const Pulsar = require('pulsar-client');
    2. const topic = 'persistent://my-tenant/my-ns/my-topic';
    3. (async () => {
    4. // Create a client
    5. const client = new Pulsar.Client({
    6. serviceUrl: 'pulsar://localhost:6650',
    7. operationTimeoutSeconds: 30,
    8. });
    9. // Create a producer
    10. const producer = await client.createProducer({
    11. topic: topic,
    12. sendTimeoutMs: 30000,
    13. batchingEnabled: true,
    14. publicKeyPath: "test_rsa_pubkey.pem",
    15. encryptionKey: "encryption-key"
    16. });
    17. // Create a consumer
    18. const consumer = await client.subscribe({
    19. topic: topic,
    20. subscription: 'my-subscriber-name',
    21. subscriptionType: 'Shared',
    22. ackTimeoutMs: 10000,
    23. privateKeyPath: "test_rsa_privkey.pem"
    24. });
    25. await consumer.close();
    26. await producer.close();
    27. await client.close();
    28. })();
  3. Optional: customize the CryptoKeyReader implementation.

    • Java
    • Python
    • C++
    • Go
    • Node.js
    1. class RawFileKeyReader implements CryptoKeyReader {
    2. String publicKeyFile = "";
    3. String privateKeyFile = "";
    4. RawFileKeyReader(String pubKeyFile, String privKeyFile) {
    5. publicKeyFile = pubKeyFile;
    6. privateKeyFile = privKeyFile;
    7. }
    8. @Override
    9. public EncryptionKeyInfo getPublicKey(String keyName, Map<String, String> keyMeta) {
    10. EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
    11. try {
    12. keyInfo.setKey(Files.readAllBytes(Paths.get(publicKeyFile)));
    13. } catch (IOException e) {
    14. System.out.println("ERROR: Failed to read public key from file " + publicKeyFile);
    15. e.printStackTrace();
    16. }
    17. return keyInfo;
    18. }
    19. @Override
    20. public EncryptionKeyInfo getPrivateKey(String keyName, Map<String, String> keyMeta) {
    21. EncryptionKeyInfo keyInfo = new EncryptionKeyInfo();
    22. try {
    23. keyInfo.setKey(Files.readAllBytes(Paths.get(privateKeyFile)));
    24. } catch (IOException e) {
    25. System.out.println("ERROR: Failed to read private key from file " + privateKeyFile);
    26. e.printStackTrace();
    27. }
    28. return keyInfo;
    29. }
    30. }

    Currently, customizing the CryptoKeyReader implementation is not supported in Python. However, you can use the default implementation by specifying the path of the private key and public keys.

    1. class CustomCryptoKeyReader : public CryptoKeyReader {
    2. public:
    3. Result getPublicKey(const std::string& keyName, std::map<std::string, std::string>& metadata,
    4. EncryptionKeyInfo& encKeyInfo) const override {
    5. // TODO
    6. return ResultOk;
    7. }
    8. Result getPrivateKey(const std::string& keyName, std::map<std::string, std::string>& metadata,
    9. EncryptionKeyInfo& encKeyInfo) const override {
    10. // TODO
    11. return ResultOk;
    12. }
    13. };
    1. type CustomKeyReader struct {
    2. publicKeyPath string
    3. privateKeyPath string
    4. }
    5. func (c *CustomKeyReader) PublicKey(keyName string, keyMeta map[string]string) (*EncryptionKeyInfo, error) {
    6. keyInfo := &EncryptionKeyInfo{}
    7. // TODO
    8. return keyInfo, nil
    9. }
    10. // PrivateKey read private key from the given path
    11. func (c *CustomKeyReader) PrivateKey(keyName string, keyMeta map[string]string) (*EncryptionKeyInfo, error) {
    12. keyInfo := &EncryptionKeyInfo{}
    13. // TODO
    14. return keyInfo, nil
    15. }

    Currently, customizing the CryptoKeyReader implementation is not supported in Node.js client. However, you can use the default implementation by specifying the path of the private key and public keys.

Encrypt a message with multiple keys

End-to-End Encryption - 图3note

This is only available for Java clients.

You can encrypt a message with more than one key. Producers add all such keys to the config and consumers can decrypt the message as long as they have access to at least one of the keys. Any one of the keys used for encrypting the message is sufficient to decrypt the message.

For example, encrypt the messages using 2 keys (myapp.messagekey1 and myapp.messagekey2):

  1. PulsarClient.newProducer().addEncryptionKey("myapp.messagekey1").addEncryptionKey("myapp.messagekey2");

Troubleshoot

  • Producer/Consumer loses access to the key
    • Producer action fails to indicate the cause of the failure. Application has the option to proceed with sending unencrypted messages in such cases. Call PulsarClient.newProducer().cryptoFailureAction(ProducerCryptoFailureAction) to control the producer behavior. The default behavior is to fail the request.
    • If consumption fails due to decryption failure or missing keys in the consumer, the application has the option to consume the encrypted message or discard it. Call PulsarClient.newConsumer().cryptoFailureAction(ConsumerCryptoFailureAction) to control the consumer behavior. The default behavior is to fail the request. Application is never able to decrypt the messages if the private key is permanently lost.
  • Batch messaging
    • If decryption fails and the message contains batch messages, client is not able to retrieve individual messages in the batch, hence message consumption fails even if cryptoFailureAction() is set to ConsumerCryptoFailureAction.CONSUME.
  • If decryption fails, the message consumption stops and the application notices backlog growth in addition to decryption failure messages in the client log. If the application does not have access to the private key to decrypt the message, the only option is to skip or discard backlogged messages.