|
| 1 | +/* |
| 2 | + * Copyright 2021 The Dapr Authors |
| 3 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + * you may not use this file except in compliance with the License. |
| 5 | + * You may obtain a copy of the License at |
| 6 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | + * Unless required by applicable law or agreed to in writing, software |
| 8 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | + * See the License for the specific language governing permissions and |
| 11 | +limitations under the License. |
| 12 | +*/ |
| 13 | + |
| 14 | +package io.dapr.examples.crypto; |
| 15 | + |
| 16 | +import io.dapr.client.DaprClientBuilder; |
| 17 | +import io.dapr.client.DaprPreviewClient; |
| 18 | +import io.dapr.client.domain.DecryptRequestAlpha1; |
| 19 | +import io.dapr.client.domain.EncryptRequestAlpha1; |
| 20 | +import io.dapr.config.Properties; |
| 21 | +import io.dapr.config.Property; |
| 22 | +import reactor.core.publisher.Flux; |
| 23 | + |
| 24 | +import java.io.IOException; |
| 25 | +import java.nio.charset.StandardCharsets; |
| 26 | +import java.nio.file.Files; |
| 27 | +import java.nio.file.Path; |
| 28 | +import java.nio.file.Paths; |
| 29 | +import java.security.KeyPair; |
| 30 | +import java.security.KeyPairGenerator; |
| 31 | +import java.security.NoSuchAlgorithmException; |
| 32 | +import java.util.Base64; |
| 33 | +import java.util.Map; |
| 34 | + |
| 35 | +/** |
| 36 | + * CryptoExample demonstrates using the Dapr Cryptography building block |
| 37 | + * to encrypt and decrypt data using a cryptography component. |
| 38 | + * |
| 39 | + * <p>This example shows: |
| 40 | + * <ul> |
| 41 | + * <li>Encrypting plaintext data with a specified key and algorithm</li> |
| 42 | + * <li>Decrypting ciphertext data back to plaintext</li> |
| 43 | + * <li>Automatic key generation if keys don't exist</li> |
| 44 | + * </ul> |
| 45 | + * |
| 46 | + * <p>Prerequisites: |
| 47 | + * <ul> |
| 48 | + * <li>Dapr installed and initialized</li> |
| 49 | + * <li>A cryptography component configured (e.g., local storage crypto)</li> |
| 50 | + * </ul> |
| 51 | + */ |
| 52 | +public class CryptoExample { |
| 53 | + |
| 54 | + private static final String CRYPTO_COMPONENT_NAME = "localstoragecrypto"; |
| 55 | + private static final String KEY_NAME = "rsa-private-key"; |
| 56 | + private static final String KEY_WRAP_ALGORITHM = "RSA"; |
| 57 | + private static final String KEYS_DIR = "components/crypto/keys"; |
| 58 | + |
| 59 | + /** |
| 60 | + * The main method demonstrating encryption and decryption with Dapr. |
| 61 | + * |
| 62 | + * @param args Command line arguments (unused). |
| 63 | + */ |
| 64 | + public static void main(String[] args) throws Exception { |
| 65 | + // Generate keys if they don't exist |
| 66 | + generateKeysIfNeeded(); |
| 67 | + |
| 68 | + Map<Property<?>, String> overrides = Map.of( |
| 69 | + Properties.HTTP_PORT, "3500", |
| 70 | + Properties.GRPC_PORT, "50001" |
| 71 | + ); |
| 72 | + |
| 73 | + try (DaprPreviewClient client = new DaprClientBuilder().withPropertyOverrides(overrides).buildPreviewClient()) { |
| 74 | + |
| 75 | + String originalMessage = "This is a secret message"; |
| 76 | + byte[] plainText = originalMessage.getBytes(StandardCharsets.UTF_8); |
| 77 | + |
| 78 | + System.out.println("=== Dapr Cryptography Example ==="); |
| 79 | + System.out.println("Original message: " + originalMessage); |
| 80 | + System.out.println(); |
| 81 | + |
| 82 | + // Encrypt the message |
| 83 | + System.out.println("Encrypting message..."); |
| 84 | + EncryptRequestAlpha1 encryptRequest = new EncryptRequestAlpha1( |
| 85 | + CRYPTO_COMPONENT_NAME, |
| 86 | + Flux.just(plainText), |
| 87 | + KEY_NAME, |
| 88 | + KEY_WRAP_ALGORITHM |
| 89 | + ); |
| 90 | + |
| 91 | + byte[] encryptedData = client.encrypt(encryptRequest) |
| 92 | + .collectList() |
| 93 | + .map(CryptoExample::combineChunks) |
| 94 | + .block(); |
| 95 | + |
| 96 | + System.out.println("Encryption successful!"); |
| 97 | + System.out.println("Encrypted data length: " + encryptedData.length + " bytes"); |
| 98 | + System.out.println(); |
| 99 | + |
| 100 | + // Decrypt the message |
| 101 | + System.out.println("Decrypting message..."); |
| 102 | + DecryptRequestAlpha1 decryptRequest = new DecryptRequestAlpha1( |
| 103 | + CRYPTO_COMPONENT_NAME, |
| 104 | + Flux.just(encryptedData) |
| 105 | + ); |
| 106 | + |
| 107 | + byte[] decryptedData = client.decrypt(decryptRequest) |
| 108 | + .collectList() |
| 109 | + .map(CryptoExample::combineChunks) |
| 110 | + .block(); |
| 111 | + |
| 112 | + String decryptedMessage = new String(decryptedData, StandardCharsets.UTF_8); |
| 113 | + System.out.println("Decryption successful!"); |
| 114 | + System.out.println("Decrypted message: " + decryptedMessage); |
| 115 | + System.out.println(); |
| 116 | + |
| 117 | + if (originalMessage.equals(decryptedMessage)) { |
| 118 | + System.out.println("SUCCESS: The decrypted message matches the original."); |
| 119 | + } else { |
| 120 | + System.out.println("ERROR: The decrypted message does not match the original."); |
| 121 | + } |
| 122 | + |
| 123 | + } catch (Exception e) { |
| 124 | + System.err.println("Error during crypto operations: " + e.getMessage()); |
| 125 | + throw new RuntimeException(e); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + /** |
| 130 | + * Generates RSA key pair if the key file doesn't exist. |
| 131 | + */ |
| 132 | + private static void generateKeysIfNeeded() throws NoSuchAlgorithmException, IOException { |
| 133 | + Path keysDir = Paths.get(KEYS_DIR); |
| 134 | + Path keyFile = keysDir.resolve(KEY_NAME + ".pem"); |
| 135 | + |
| 136 | + if (Files.exists(keyFile)) { |
| 137 | + System.out.println("Using existing key: " + keyFile.toAbsolutePath()); |
| 138 | + return; |
| 139 | + } |
| 140 | + |
| 141 | + System.out.println("Generating RSA key pair..."); |
| 142 | + Files.createDirectories(keysDir); |
| 143 | + |
| 144 | + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); |
| 145 | + keyGen.initialize(4096); |
| 146 | + KeyPair keyPair = keyGen.generateKeyPair(); |
| 147 | + |
| 148 | + String privateKeyPem = "-----BEGIN PRIVATE KEY-----\n" |
| 149 | + + Base64.getMimeEncoder(64, "\n".getBytes()).encodeToString(keyPair.getPrivate().getEncoded()) |
| 150 | + + "\n-----END PRIVATE KEY-----\n"; |
| 151 | + |
| 152 | + String publicKeyPem = "-----BEGIN PUBLIC KEY-----\n" |
| 153 | + + Base64.getMimeEncoder(64, "\n".getBytes()).encodeToString(keyPair.getPublic().getEncoded()) |
| 154 | + + "\n-----END PUBLIC KEY-----\n"; |
| 155 | + |
| 156 | + Files.writeString(keyFile, privateKeyPem + publicKeyPem); |
| 157 | + System.out.println("Key generated: " + keyFile.toAbsolutePath()); |
| 158 | + } |
| 159 | + |
| 160 | + /** |
| 161 | + * Combines byte array chunks into a single byte array. |
| 162 | + */ |
| 163 | + private static byte[] combineChunks(java.util.List<byte[]> chunks) { |
| 164 | + int totalSize = chunks.stream().mapToInt(chunk -> chunk.length).sum(); |
| 165 | + byte[] result = new byte[totalSize]; |
| 166 | + int pos = 0; |
| 167 | + for (byte[] chunk : chunks) { |
| 168 | + System.arraycopy(chunk, 0, result, pos, chunk.length); |
| 169 | + pos += chunk.length; |
| 170 | + } |
| 171 | + return result; |
| 172 | + } |
| 173 | +} |
0 commit comments