Last active
December 12, 2024 07:52
-
-
Save unclebean/0f2a57c5dca1bd5cbd153d92d872241e to your computer and use it in GitHub Desktop.
certificate
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.io.FileOutputStream; | |
| import java.io.InputStream; | |
| import java.security.KeyFactory; | |
| import java.security.KeyStore; | |
| import java.security.PrivateKey; | |
| import java.security.cert.Certificate; | |
| import java.security.cert.CertificateFactory; | |
| import java.security.spec.PKCS8EncodedKeySpec; | |
| import java.util.Base64; | |
| public class KeyStoreExample { | |
| public static void main(String[] args) throws Exception { | |
| // Paths to your private key and certificate | |
| String privateKeyPem = "-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----"; | |
| String certificatePem = "-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----"; | |
| // Convert PEM Private Key to PrivateKey object | |
| String privateKeyContent = privateKeyPem | |
| .replace("-----BEGIN PRIVATE KEY-----", "") | |
| .replace("-----END PRIVATE KEY-----", "") | |
| .replaceAll("\\s", ""); | |
| byte[] privateKeyBytes = Base64.getDecoder().decode(privateKeyContent); | |
| PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes); | |
| PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec); | |
| // Convert PEM Certificate to Certificate object | |
| CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); | |
| InputStream certInputStream = new java.io.ByteArrayInputStream(certificatePem.getBytes()); | |
| Certificate certificate = certFactory.generateCertificate(certInputStream); | |
| // Create a KeyStore instance | |
| KeyStore keyStore = KeyStore.getInstance("JKS"); | |
| keyStore.load(null, null); // Initialize empty KeyStore | |
| // Add private key and certificate to KeyStore | |
| String alias = "mykey"; | |
| char[] password = "changeit".toCharArray(); | |
| keyStore.setKeyEntry(alias, privateKey, password, new Certificate[]{certificate}); | |
| // Save KeyStore to a file (optional) | |
| try (FileOutputStream fos = new FileOutputStream("keystore.jks")) { | |
| keyStore.store(fos, password); | |
| } | |
| System.out.println("KeyStore created and saved as keystore.jks"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| server: | |
| port: 8443 | |
| ssl: | |
| key-store-type: PEM | |
| key-store: /etc/ssl/certs/tls.key | |
| key-store-certificate-chain: /etc/ssl/certs/tls.crt |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import org.springframework.context.annotation.Bean; | |
| import org.springframework.context.annotation.Configuration; | |
| import javax.net.ssl.KeyManagerFactory; | |
| import javax.net.ssl.SSLContext; | |
| import javax.net.ssl.TrustManagerFactory; | |
| import java.io.FileInputStream; | |
| import java.nio.file.Files; | |
| import java.nio.file.Paths; | |
| import java.security.KeyFactory; | |
| import java.security.KeyStore; | |
| import java.security.PrivateKey; | |
| import java.security.cert.Certificate; | |
| import java.security.cert.CertificateFactory; | |
| import java.security.cert.X509Certificate; | |
| import java.security.spec.PKCS8EncodedKeySpec; | |
| @Configuration | |
| public class SSLContextConfig { | |
| @Bean | |
| public SSLContext customSSLContext() throws Exception { | |
| // Load the private key | |
| byte[] keyBytes = Files.readAllBytes(Paths.get("src/main/resources/certs/tls.key")); | |
| PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes); | |
| KeyFactory keyFactory = KeyFactory.getInstance("RSA"); | |
| PrivateKey privateKey = keyFactory.generatePrivate(keySpec); | |
| // Load the certificate | |
| CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); | |
| X509Certificate certificate = (X509Certificate) certFactory.generateCertificate( | |
| new FileInputStream("src/main/resources/certs/tls.crt")); | |
| // Optional: Load CA certificate | |
| X509Certificate caCertificate = (X509Certificate) certFactory.generateCertificate( | |
| new FileInputStream("src/main/resources/certs/ca.crt")); | |
| // Create a KeyStore with the private key and certificate | |
| KeyStore keyStore = KeyStore.getInstance("PKCS12"); | |
| keyStore.load(null, null); // Initialize an empty KeyStore | |
| keyStore.setKeyEntry("alias", privateKey, null, new Certificate[]{certificate}); | |
| // Add CA certificate to the trust store | |
| KeyStore trustStore = KeyStore.getInstance("PKCS12"); | |
| trustStore.load(null, null); | |
| trustStore.setCertificateEntry("caAlias", caCertificate); | |
| // Initialize KeyManagerFactory | |
| KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); | |
| kmf.init(keyStore, null); | |
| // Initialize TrustManagerFactory | |
| TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); | |
| tmf.init(trustStore); | |
| // Create SSLContext | |
| SSLContext sslContext = SSLContext.getInstance("TLS"); | |
| sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); | |
| return sslContext; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import configureMockStore from 'redux-mock-store'; | |
| import setupStore from './path/to/setupStore'; | |
| // Step 1: Configure the mock store | |
| const mockStore = configureMockStore([]); | |
| let store: any; | |
| // Step 2: Mock `setupStore` globally | |
| jest.mock('./path/to/setupStore', () => ({ | |
| __esModule: true, | |
| default: jest.fn(), // Mock function placeholder | |
| })); | |
| beforeEach(() => { | |
| // Step 3: Initialize the store before each test | |
| store = mockStore({ | |
| // Define your initial state here | |
| key: 'value', | |
| }); | |
| // Link the mocked `setupStore` to return the re-initialized `store` | |
| (setupStore as jest.Mock).mockReturnValue(store); | |
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @GetMapping("/user-roles") | |
| public Map<String, Object> getUserRoles(Authentication authentication) { | |
| // Extract JWT token from the SecurityContext | |
| Jwt jwt = (Jwt) authentication.getPrincipal(); | |
| String accessToken = jwt.getTokenValue(); | |
| // Use the token to call Microsoft Graph API | |
| String graphUrl = "https://graph.microsoft.com/v1.0/me/memberOf"; | |
| RestTemplate restTemplate = new RestTemplate(); | |
| HttpHeaders headers = new HttpHeaders(); | |
| headers.set("Authorization", "Bearer " + accessToken); | |
| HttpEntity<Void> request = new HttpEntity<>(headers); | |
| ResponseEntity<Map> response = restTemplate.exchange(graphUrl, HttpMethod.GET, request, Map.class); | |
| return response.getBody(); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.azure.identity.ManagedIdentityCredentialBuilder; | |
| import com.azure.core.credential.TokenCredential; | |
| import com.azure.core.management.AzureEnvironment; | |
| import com.azure.core.util.logging.ClientLogger; | |
| import com.azure.identity.ClientSecretCredentialBuilder; | |
| import com.azure.messaging.eventhubs.EventHubProducerClient; | |
| import com.azure.messaging.eventhubs.EventHubsClientBuilder; | |
| public class EventHubConnectionService { | |
| private static final String EVENT_HUBS_NAMESPACE = "<Your Event Hubs Namespace>.servicebus.windows.net"; | |
| private static final String EVENT_HUB_NAME = "<Your Event Hub Name>"; | |
| private EventHubProducerClient eventHubProducerClient; | |
| public EventHubConnectionService() { | |
| // Create TokenCredential using Managed Identity | |
| TokenCredential credential = new ManagedIdentityCredentialBuilder() | |
| .clientId("<Your UAMI Client ID>") // Omit this line for system-assigned managed identity | |
| .build(); | |
| // Create the producer client using the TokenCredential | |
| eventHubProducerClient = new EventHubsClientBuilder() | |
| .fullyQualifiedNamespace(EVENT_HUBS_NAMESPACE) | |
| .credential(credential) | |
| .buildProducerClient(); | |
| } | |
| public void sendMessage(String message) { | |
| eventHubProducerClient.sendBatch( | |
| eventHubProducerClient.createBatch().addEventData(new EventData(message)) | |
| ); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import com.azure.core.credential.TokenCredential; | |
| import com.azure.identity.ManagedIdentityCredentialBuilder; | |
| import com.azure.messaging.eventhubs.EventData; | |
| import com.azure.messaging.eventhubs.EventHubProducerClient; | |
| import com.azure.messaging.eventhubs.EventHubsClientBuilder; | |
| public class EventHubProducerService { | |
| private final EventHubProducerClient producerClient; | |
| public EventHubProducerService(String fullyQualifiedNamespace, String eventHubName, String clientId) { | |
| // Create TokenCredential using Managed Identity | |
| TokenCredential credential = new ManagedIdentityCredentialBuilder() | |
| .clientId(clientId) // Use the UAMI Client ID; omit for system-assigned identity | |
| .build(); | |
| // Initialize EventHubProducerClient | |
| this.producerClient = new EventHubsClientBuilder() | |
| .fullyQualifiedNamespace(fullyQualifiedNamespace) // e.g., "<namespace>.servicebus.windows.net" | |
| .credential(eventHubName, credential) // Event Hub name and TokenCredential | |
| .buildProducerClient(); | |
| } | |
| public void sendMessage(String message) { | |
| // Create an EventData object and send it | |
| producerClient.send(producerClient.createBatch().add(new EventData(message))); | |
| System.out.println("Message sent: " + message); | |
| } | |
| public void close() { | |
| producerClient.close(); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <dependency> | |
| <groupId>com.azure</groupId> | |
| <artifactId>azure-messaging-eventhubs</artifactId> | |
| <version>5.15.0</version> <!-- Use the latest version --> | |
| </dependency> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public void sendMessage(String message) { | |
| // Create a batch | |
| EventDataBatch batch = producerClient.createBatch(); | |
| // Add the message to the batch | |
| if (!batch.tryAdd(new EventData(message))) { | |
| throw new IllegalStateException("Message is too large to fit in a batch"); | |
| } | |
| // Send the batch | |
| producerClient.send(batch); | |
| System.out.println("Message sent: " + message); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| apiVersion: apps/v1 | |
| kind: Deployment | |
| metadata: | |
| name: spring-boot-app | |
| namespace: your-namespace | |
| spec: | |
| template: | |
| spec: | |
| containers: | |
| - name: spring-boot-app | |
| image: your-spring-boot-image | |
| ports: | |
| - containerPort: 8443 | |
| volumeMounts: | |
| - name: tls-secret | |
| mountPath: /etc/ssl/certs | |
| readOnly: true | |
| volumes: | |
| - name: tls-secret | |
| secret: | |
| secretName: spring-boot-app-tls |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| __mocks__/msal.js | |
| export const mockMsalInstance = { | |
| loginRedirect: jest.fn(), | |
| loginPopup: jest.fn(), | |
| acquireTokenSilent: jest.fn().mockResolvedValue({ | |
| accessToken: "mockAccessToken", | |
| }), | |
| acquireTokenPopup: jest.fn().mockResolvedValue({ | |
| accessToken: "mockAccessToken", | |
| }), | |
| logout: jest.fn(), | |
| getAllAccounts: jest.fn().mockReturnValue([ | |
| { username: "mockUser", homeAccountId: "mockHomeAccountId" }, | |
| ]), | |
| }; | |
| // __mocks__/setupStore.js | |
| import { configureStore } from "@reduxjs/toolkit"; | |
| import rootReducer from "../path-to-your-root-reducer"; // Update the path | |
| export const mockState = { | |
| auth: { isAuthenticated: true, user: { name: "Mock User" } }, | |
| // Add other slices of state as needed | |
| }; | |
| export const mockStore = configureStore({ | |
| reducer: rootReducer, | |
| preloadedState: mockState, | |
| }); | |
| const setupStore = jest.fn(() => mockStore); | |
| export default setupStore; | |
| jest.mock("./path-to-setupStore", () => setupStore); // Mock the setupStore function | |
| jest.mock("@azure/msal-browser", () => ({ | |
| PublicClientApplication: require("./__mocks__/msal").PublicClientApplication, | |
| })); | |
| jest.mock("@azure/msal-react", () => ({ | |
| MsalProvider: ({ children }) => <div>{children}</div>, | |
| useMsal: jest.fn(() => ({ | |
| instance: require("./__mocks__/msal").mockMsalInstance, | |
| })), | |
| useIsAuthenticated: jest.fn(() => true), | |
| })); | |
| render( | |
| <MsalProvider instance={mockMsalInstance}> | |
| <MyComponent /> | |
| </MsalProvider> | |
| ); | |
| export const PublicClientApplication = jest.fn(() => mockMsalInstance); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| WITH updated AS ( | |
| UPDATE target_table | |
| SET name = source.name, | |
| age = source.age | |
| FROM source_table AS source | |
| WHERE target_table.id = source.id | |
| RETURNING target_table.id | |
| ) | |
| INSERT INTO target_table (id, name, age) | |
| SELECT source.id, source.name, source.age | |
| FROM source_table AS source | |
| WHERE NOT EXISTS ( | |
| SELECT 1 FROM updated WHERE updated.id = source.id | |
| ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Retrieve and decode tls.crt | |
| $tlsCrtBase64 = kubectl get secret <secret-name> -n <namespace> -o jsonpath="{.data.tls\.crt}" | |
| $tlsCrt = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($tlsCrtBase64)) | |
| Set-Content -Path tls.crt -Value $tlsCrt | |
| # Retrieve and decode tls.key | |
| $tlsKeyBase64 = kubectl get secret <secret-name> -n <namespace> -o jsonpath="{.data.tls\.key}" | |
| $tlsKey = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($tlsKeyBase64)) | |
| Set-Content -Path tls.key -Value $tlsKey |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| az login | |
| az account set --subscription "<SUBSCRIPTION_ID_OR_NAME>" | |
| az aks get-credentials --resource-group <RESOURCE_GROUP_NAME> --name <AKS_CLUSTER_NAME> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment