public async Task <byte[]> WrapKeyAsync(byte[] key, CancellationToken token) { if (key == null) { throw new ArgumentNullException(nameof(key)); } //if (algorithm == null) //{ // throw new ArgumentNullException(nameof(algorithm)); //} this.EnsureUsable(); if (this.PublicKey == null) { throw new InvalidOperationException("There is no PublicKey"); } if (this.NotAfter < DateTime.UtcNow) { throw new EncryptionException($"Operation is not allowed on expired key; Key '{this.Actor}/{this.KeyId}'."); } var fOAEP = true; // changed to more modern standard 2017/05/08 var rsa = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(_x5092); var encrypted = await Task.FromResult(rsa.Encrypt(key, fOAEP)); return(encrypted); //var encryptedAsString = Encoding.UTF8.GetString(encrypted); //return new Tuple<byte[], string>(encrypted, encryptedAsString); }
/// <summary> /// Edits the specified object's value using the editor style indicated by the <see cref="M:System.Drawing.Design.UITypeEditor.GetEditStyle"></see> method. /// </summary> /// <param name="context">An <see cref="T:System.ComponentModel.ITypeDescriptorContext"></see> that can be used to gain additional context information.</param> /// <param name="provider">An <see cref="T:System.IServiceProvider"></see> that this editor can use to obtain services.</param> /// <param name="value">The object to edit.</param> /// <returns> /// The new value of the object. If the value of the object has not changed, this should return the same object it was passed. /// </returns> public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value) { IUIService svc = (IUIService)provider.GetService(typeof(IUIService)); IDictionaryService dictService = (IDictionaryService)provider.GetService(typeof(IDictionaryService)); StoreName storeName = (StoreName)dictService.GetValue(storeNameArgument); StoreLocation storeLocation = (StoreLocation)dictService.GetValue(storeLocationArgument); X509FindType findType = (X509FindType)dictService.GetValue(findTypeArgument); using (X509CertificatePicker certPicker = new X509CertificatePicker(storeName, storeLocation)) { X509Certificate2 selectedCert = certPicker.PickCertificate( svc != null ? svc.GetDialogOwnerWindow().Handle : IntPtr.Zero); if (selectedCert != null) { return(X509CertificateHelper.GetFindValue(findType, selectedCert)); } else { return(null); } } }
public static async Task GetBytes() { var fileContents = await File.ReadAllTextAsync("./Security/Cryptography/4096b-rsa-example-cert.pem"); var certificate = X509CertificateHelper.GetCertificate(fileContents); Assert.NotNull(certificate); // openssl x509 -noout -fingerprint -sha1 -inform pem -in 4096b-rsa-example-cert.pem Assert.Equal("2013BADFCD6BDD058E39B98D6B1177E870603B93", certificate.Thumbprint); }
private void LoadCertificate() { filteredCert = X509CertificateHelper.GetRSKCertificate(thumbPrint, StoreLocation.LocalMachine); if (filteredCert == null) { System.Console.WriteLine($"Unable to find the RSK certificate by Thumbprint: " + $"{thumbPrint}"); } else { MessageBox.Show("Certificate loaded successfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
protected async Task CreateAzureResourcesAsync( CancellationToken cancellationToken = default ) { // Create Virtual Network NetworkSecurityGroupInner networkSecurityGroup; //RouteTableInner routeTable; VirtualNetworkInner virtualNetwork; SubnetInner virtualNetworkAksSubnet; //PublicIPAddressInner publicIPAddress; //NetworkInterfaceInner networkInterface; networkSecurityGroup = await _networkManagementClient .CreateNetworkSecurityGroupAsync( _resourceGroup, _networkSecurityGroupName, _defaultTagsDict, cancellationToken ); //routeTable = _networkManagementClient // .CreateRouteTableAsync( // _resourceGroup, // _routTableName, // networkInterfacePrivateIPAddress, // _defaultTagsDict, // cancellationToken // ).Result; virtualNetwork = await _networkManagementClient .CreateVirtualNetworkAsync( _resourceGroup, networkSecurityGroup, _virtualNetworkName, null, _defaultTagsDict, cancellationToken ); virtualNetworkAksSubnet = _networkManagementClient.GetAksSubnet(virtualNetwork); //publicIPAddress = _networkManagementClient // .CreatePublicIPAddressAsync( // _resourceGroup, // _publicIPAddressName, // _domainNameLabel, // _defaultTagsDict, // cancellationToken // ) // .Result; //networkInterface = _networkManagementClient // .CreateNetworkInterfaceAsync( // _resourceGroup, // networkSecurityGroup, // virtualNetworkAksSubnet, // _networkInterfaceName, // networkInterfacePrivateIPAddress, // _defaultTagsDict, // cancellationToken // ) // .Result; // Create Azure KeyVault VaultInner keyVault; var keyVaultParameters = _keyVaultManagementClient .GetCreationParameters( _authConf.TenantId, _resourceGroup, _applicationsManager.GetServiceApplicationSP(), _owner ); keyVault = await _keyVaultManagementClient .CreateAsync( _resourceGroup, _keyVaultName, keyVaultParameters, cancellationToken ); // Add certificates to KeyVault var keyVaultAuthenticationCallback = new IIoTKeyVaultClient.AuthenticationCallback( async(authority, resource, scope) => { // Fetch AccessToken from cache. var authenticationResult = await _authenticationManager .AcquireKeyVaultAuthenticationResultAsync(cancellationToken); return(authenticationResult.AccessToken); } ); using (var iiotKeyVaultClient = new IIoTKeyVaultClient(keyVaultAuthenticationCallback, keyVault)) { await iiotKeyVaultClient.CreateCertificateAsync( IIoTKeyVaultClient.WEB_APP_CERT_NAME, kWEB_APP_CN, _defaultTagsDict, cancellationToken ); _webAppX509Certificate = await iiotKeyVaultClient.GetSecretAsync( IIoTKeyVaultClient.WEB_APP_CERT_NAME, cancellationToken ); await iiotKeyVaultClient.CreateCertificateAsync( IIoTKeyVaultClient.AKS_CLUSTER_CERT_NAME, kAKS_CLUSTER_CN, _defaultTagsDict, cancellationToken ); _aksClusterX509Certificate = await iiotKeyVaultClient.GetCertificateAsync( IIoTKeyVaultClient.AKS_CLUSTER_CERT_NAME, cancellationToken ); } // Create Operational Insights workspace. var operationalInsightsWorkspaceCreationTask = _operationalInsightsManagementClient .CreateOperationalInsightsWorkspaceAsync( _resourceGroup, _operationalInsightsWorkspaceName, _defaultTagsDict, cancellationToken ); // Create Application Insights components. var applicationInsightsComponentCreationTask = _applicationInsightsManagementClient .CreateApplicationInsightsComponentAsync( _resourceGroup, _applicationInsightsName, _defaultTagsDict, cancellationToken ); // Create AKS cluster var operationalInsightsWorkspace = operationalInsightsWorkspaceCreationTask.Result; var clusterDefinition = _aksManagementClient.GetClusterDefinition( _resourceGroup, _applicationsManager.GetAKSApplication(), _applicationsManager.GetAKSApplicationRbacSecret(), _aksClusterName, _aksClusterX509Certificate, virtualNetworkAksSubnet, operationalInsightsWorkspace, _defaultTagsDict ); var aksClusterCreationTask = _aksManagementClient .CreateClusterAsync( _resourceGroup, _aksClusterName, clusterDefinition, cancellationToken ); // Create Storage Account StorageAccountInner storageAccount; string storageAccountConectionString; storageAccount = await _storageManagementClient .CreateStorageAccountAsync( _resourceGroup, _storageAccountName, _defaultTagsDict, cancellationToken ); storageAccountConectionString = await _storageManagementClient .GetStorageAccountConectionStringAsync( _resourceGroup, storageAccount, cancellationToken ); await _storageManagementClient .CreateBlobContainerAsync( _resourceGroup, storageAccount, StorageMgmtClient.STORAGE_ACCOUNT_IOT_HUB_CONTAINER_NAME, PublicAccess.None, _defaultTagsDict, cancellationToken ); // Create IoT Hub IotHubDescription iotHub; iotHub = await _iotHubManagementClient .CreateIotHubAsync( _resourceGroup, _iotHubName, IotHubMgmtClient.IOT_HUB_EVENT_HUB_PARTITIONS_COUNT, storageAccountConectionString, StorageMgmtClient.STORAGE_ACCOUNT_IOT_HUB_CONTAINER_NAME, _defaultTagsDict, cancellationToken ); await _iotHubManagementClient .CreateEventHubConsumerGroupAsync( _resourceGroup, iotHub, IotHubMgmtClient.IOT_HUB_EVENT_HUB_ONBOARDING_ENDPOINT_NAME, IotHubMgmtClient.IOT_HUB_EVENT_HUB_ONBOARDING_CONSUMER_GROUP_NAME, cancellationToken ); // Create CosmosDB account var cosmosDBAccountCreationTask = _cosmosDBManagementClient .CreateDatabaseAccountAsync( _resourceGroup, _cosmosDBAccountName, _defaultTagsDict, cancellationToken ); // Create Service Bus Namespace var serviceBusNamespaceCreationTask = _serviceBusManagementClient .CreateServiceBusNamespaceAsync( _resourceGroup, _serviceBusNamespaceName, _defaultTagsDict, cancellationToken ); // Create Azure Event Hub Namespace and Azure Event Hub EHNamespaceInner eventHubNamespace; EventhubInner eventHub; // Create Azure Event Hub Namespace eventHubNamespace = await _eventHubManagementClient .CreateEventHubNamespaceAsync( _resourceGroup, _eventHubNamespaceName, _defaultTagsDict, cancellationToken ); // Create Azure Event Hub eventHub = await _eventHubManagementClient .CreateEventHubAsync( _resourceGroup, eventHubNamespace, _eventHubName, _defaultTagsDict, cancellationToken ); // Create AppService Plan to host the Application Gateway Web App var appServicePlan = await _webSiteManagementClient .CreateAppServicePlanAsync( _resourceGroup, _appServicePlanName, _defaultTagsDict, cancellationToken ); // This will point to PublicIP address of Ingress. var emptyRemoteEndpoint = ""; var webSiteCreationTask = _webSiteManagementClient .CreateSiteAsync( _resourceGroup, appServicePlan, _azureWebsiteName, emptyRemoteEndpoint, _webAppX509Certificate, _defaultTagsDict, cancellationToken ); // SignalR var signalRCreationTask = _signalRManagementClient .CreateAsync( _resourceGroup, _signalRName, _defaultTagsDict, cancellationToken ); // Collect all necessary environment variables for IIoT services. var iotHubOwnerConnectionString = await _iotHubManagementClient .GetIotHubConnectionStringAsync( _resourceGroup, iotHub, IotHubMgmtClient.IOT_HUB_OWNER_KEY_NAME, cancellationToken ); var cosmosDBAccount = cosmosDBAccountCreationTask.Result; var cosmosDBAccountConnectionString = await _cosmosDBManagementClient .GetCosmosDBAccountConnectionStringAsync( _resourceGroup, cosmosDBAccount, cancellationToken ); var eventHubNamespaceConnectionString = await _eventHubManagementClient .GetEventHubNamespaceConnectionStringAsync( _resourceGroup, eventHubNamespace, cancellationToken ); var serviceBusNamespace = serviceBusNamespaceCreationTask.Result; var serviceBusNamespaceConnectionString = await _serviceBusManagementClient .GetServiceBusNamespaceConnectionStringAsync( _resourceGroup, serviceBusNamespace, cancellationToken ); var storageAccountKey = await _storageManagementClient .GetStorageAccountKeyAsync( _resourceGroup, storageAccount, cancellationToken ); var signalR = signalRCreationTask.Result; var signalRConnectionString = await _signalRManagementClient .GetConnectionStringAsync( _resourceGroup, signalR, cancellationToken ); var applicationInsightsComponent = applicationInsightsComponentCreationTask.Result; var webSite = webSiteCreationTask.Result; var iiotEnvironment = new IIoTEnvironment( _authConf.AzureEnvironment, _authConf.TenantId, iotHub, iotHubOwnerConnectionString, IotHubMgmtClient.IOT_HUB_EVENT_HUB_ONBOARDING_CONSUMER_GROUP_NAME, IotHubMgmtClient.IOT_HUB_EVENT_HUB_PARTITIONS_COUNT, cosmosDBAccountConnectionString, storageAccount, storageAccountKey, eventHub, eventHubNamespaceConnectionString, serviceBusNamespaceConnectionString, signalRConnectionString, keyVault, operationalInsightsWorkspace, applicationInsightsComponent, webSite, _applicationsManager.GetServiceApplication(), _applicationsManager.GetClientApplication() ); // Deploy IIoT services to AKS cluster // Generate default SSL certificate for NGINX Ingress var webAppPemCertificate = X509CertificateHelper.GetPemCertificate(_webAppX509Certificate); //var webAppPemPublicKey = X509CertificateHelper.GetPemPublicKey(webAppX509Certificate); var webAppPemPrivateKey = X509CertificateHelper.GetPemPrivateKey(_webAppX509Certificate); // Get KubeConfig var aksCluster = aksClusterCreationTask.Result; var aksKubeConfig = await _aksManagementClient .GetClusterAdminCredentialsAsync( _resourceGroup, aksCluster.Name, cancellationToken ); var iiotK8SClient = new IIoTK8SClient(aksKubeConfig); // industrial-iot namespace iiotK8SClient.CreateIIoTNamespaceAsync(cancellationToken).Wait(); iiotK8SClient.SetupIIoTServiceAccountAsync(cancellationToken).Wait(); iiotK8SClient.CreateIIoTEnvSecretAsync(iiotEnvironment.Dict, cancellationToken).Wait(); iiotK8SClient.DeployIIoTServicesAsync(cancellationToken).Wait(); // We will add default SSL certificate for Ingress // NGINX controler to industrial-iot namespace iiotK8SClient .CreateNGINXDefaultSSLCertificateSecretAsync( webAppPemCertificate, webAppPemPrivateKey, cancellationToken ) .Wait(); // ingress-nginx namespace iiotK8SClient.CreateNGINXNamespaceAsync(cancellationToken).Wait(); iiotK8SClient.SetupNGINXServiceAccountAsync(cancellationToken).Wait(); iiotK8SClient.DeployNGINXIngressControllerAsync(cancellationToken).Wait(); // After we have NGINX Ingress controller we can create Ingress // for our Industrial IoT services and wait for IP address of // its LoadBalancer. var iiotIngress = await iiotK8SClient.CreateIIoTIngressAsync(cancellationToken); var iiotIngressIPAddresses = await iiotK8SClient.WaitForIngressIPAsync(iiotIngress, cancellationToken); var iiotIngressIPAdress = iiotIngressIPAddresses.FirstOrDefault().Ip; // Update remote endpoint and certificate thumbprint application settings // of App Servise. var iiotIngressRemoteEndpoint = $"https://{iiotIngressIPAdress}"; await _webSiteManagementClient .UpdateSiteApplicationSettingsAsync( _resourceGroup, webSite, iiotIngressRemoteEndpoint, _webAppX509Certificate, cancellationToken ); // Deploy reverse proxy to App Service. It will consume values of remote // endpoint and certificate thumbprint application settings of App Service. var proxySiteSourceControl = await _webSiteManagementClient .DeployProxyAsync( _resourceGroup, webSite, _defaultTagsDict, cancellationToken ); // After we have deployed proxy to App Service, we will update // client application to have redirect URIs for App Service. // This will be performed in UpdateClientApplicationRedirectUrisAsync() call. _applicationURL = webSite.DefaultHostName; // Check if we want to save environment to .env file try { if (_configurationProvider.IfSaveEnvFile()) { iiotEnvironment.WriteToFile(ENV_FILE_PATH); } } catch (Exception) { Log.Warning("Skipping environment file generation."); } }
//public async Task<bool> CheckNameAvailabilityAsync( // string aksClusterName, // CancellationToken cancellationToken = default //) { // throw new NotImplementedException(); //} public ManagedClusterInner GetClusterDefinition( IResourceGroup resourceGroup, Application aksApplication, string aksApplicationRbacSecret, string aksClusterName, X509Certificate2 sshCertificate, SubnetInner virtualNetworkSubnet, Workspace operationalInsightsWorkspace, IDictionary <string, string> tags = null ) { tags ??= new Dictionary <string, string>(); var aksDnsPrefix = aksClusterName + "-dns"; var aksClusterX509CertificateOpenSshPublicKey = X509CertificateHelper.GetOpenSSHPublicKey(sshCertificate); var managedClusterDefinition = new ManagedClusterInner( //nodeResourceGroup: aksResourceGroupName // This is not propagated yet. ) { Location = resourceGroup.RegionName, Tags = tags, //ProvisioningState = null, KubernetesVersion = KUBERNETES_VERSION, DnsPrefix = aksDnsPrefix, //Fqdn = null, AgentPoolProfiles = new List <ManagedClusterAgentPoolProfile> { new ManagedClusterAgentPoolProfile { Name = "agentpool", Count = 2, VmSize = ContainerServiceVMSizeTypes.StandardDS2V2, OsDiskSizeGB = 100, OsType = OSType.Linux, VnetSubnetID = virtualNetworkSubnet.Id } }, LinuxProfile = new ContainerServiceLinuxProfile { AdminUsername = "******", Ssh = new ContainerServiceSshConfiguration { PublicKeys = new List <ContainerServiceSshPublicKey> { new ContainerServiceSshPublicKey { KeyData = aksClusterX509CertificateOpenSshPublicKey } } } }, ServicePrincipalProfile = new ManagedClusterServicePrincipalProfile { ClientId = aksApplication.AppId, Secret = aksApplicationRbacSecret }, AddonProfiles = new Dictionary <string, ManagedClusterAddonProfile> { { "omsagent", new ManagedClusterAddonProfile { Enabled = true, Config = new Dictionary <string, string> { { "logAnalyticsWorkspaceResourceID", operationalInsightsWorkspace.Id } } } }, { "httpApplicationRouting", new ManagedClusterAddonProfile { Enabled = false } } }, //NodeResourceGroup = aksResourceGroupName, // This is not propagated yet. EnableRBAC = true, NetworkProfile = new ContainerServiceNetworkProfile { NetworkPlugin = NetworkPlugin.Azure, //PodCidr = "10.244.0.0/16", ServiceCidr = NETWORK_PROFILE_SERVICE_CIDR, DnsServiceIP = NETWORK_PROFILE_DNS_SERVICE_IP, DockerBridgeCidr = NETWORK_PROFILE_DOCKER_BRIDGE_CIDR } }; managedClusterDefinition.Validate(); return(managedClusterDefinition); }
public string PublicKeyToPEM() { this.EnsureUsable(); return(X509CertificateHelper.ExportToPEM(_x5092)); }
public void TestAes1000WithCertificate() { var cert2 = LoadCertificate(); //var publicKey = X509CertificateHelper.GetRSACryptoServiceProviderFromPublicKey(cert2); var keyProtector = X509CertificateHelper.GetKeyEncryptionKey(cert2); // generate a protected key var gen = new ProtectedX509Certificate2Generator(); var policy = new CertificatePolicy() { CommonName = "Testing protected certs", AllPurposes = true, ValidForDays = 2 }; var protectedKey = Task.Run(() => gen.IssueNewCertificateAsync(keyProtector, policy)).GetAwaiter().GetResult(); // save the key to test var keyOutputFilePath = (CERT_FOLDER + "temp\\pk-" + protectedKey.KeyId + ".kpk"); var fi = new FileInfo(keyOutputFilePath); if (!fi.Directory.Exists) { fi.Directory.Create(); } var bytes = Task.Run(() => protectedKey.ToByteArrayAsync()).GetAwaiter().GetResult(); File.WriteAllBytes(fi.FullName, bytes); Console.WriteLine(fi.FullName); var list = new List <string>(); var listEnc = new List <AsymmetricallyEncryptedObject>(); using (var privateKey = Task.Run(() => protectedKey.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { //var publicKey = privateKey.PublicKey.Key as RSACryptoServiceProvider; //File.WriteAllText(fi.FullName + "_A.cer", privateKey.PublicKeyToPEM()); int length = 100; var rand = new RandomGenerator(); for (int i = 0; i < length; i++) { var stringToEncrypt = Guid.NewGuid().ToString("N") + ":* d’une secrétairE chargée des affaires des étudiants de la section"; list.Add(stringToEncrypt); var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); var asymObj = asymEnc.EncryptObjectAsync(stringToEncrypt, privateKey).GetAwaiter().GetResult(); listEnc.Add(asymObj); var decrypted = asymEnc.DecryptObjectAsync(asymObj, privateKey).GetAwaiter().GetResult(); Assert.AreEqual(stringToEncrypt, decrypted); } } // lets reload a new private key var fileBytes = File.ReadAllBytes(fi.FullName); var encKey = new AsymmetricallyEncryptedObject(); encKey.LoadFromByteArray(fileBytes); var protectedKey2 = new ProtectedX509Certificate2(protectedKey.KeyId, encKey); using (var privateKey = Task.Run(() => protectedKey2.ToKeyEncyrptionKeyAsync(keyProtector)).GetAwaiter().GetResult()) { var asymEnc = new AsymmetricEncryptor(AsymmetricStrategyOption.Aes256_1000); int i = 0; foreach (var line in list) { var asymObj = listEnc[i]; var decrypted = asymEnc.DecryptObject(asymObj, privateKey); Assert.AreEqual(line, decrypted); i++; } } }
public static void GenerateRootCertificate(string subjectName, DateTime expireOnUtc, out string password, out string pemValue, out byte[] cerData, out byte[] pkcs12Data) { // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); BigInteger serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(certName); gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); gen.SetPublicKey(subjectKeyPair.Public); var certificate = gen.Generate(subjectKeyPair.Private, random); var privateKeyPem = new StringBuilder(); var privateKeyPemWriter = new PemWriter(new StringWriter(privateKeyPem)); privateKeyPemWriter.WriteObject(certificate); privateKeyPemWriter.WriteObject(subjectKeyPair.Private); privateKeyPemWriter.Writer.Flush(); pemValue = privateKeyPem.ToString(); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; // Generating Random Numbers var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx, password); }
/// <summary> /// /// </summary> /// <remarks>Based on <see cref="http://www.fkollmann.de/v2/post/Creating-certificates-using-BouncyCastle.aspx"/></remarks> /// <param name="subjectName"></param> /// <returns></returns> public static void GenerateCertificate(string subjectName, DateTime expireOnUtc, byte[] issuingCertificate, string issuingCertificatePassword, out string password, out byte[] cerData, out byte[] pkcs12Data) { AsymmetricKeyParameter caPrivateKey; var caCert = ReadCertificateFromBytes(issuingCertificate, issuingCertificatePassword, out caPrivateKey); var caAuth = new AuthorityKeyIdentifierStructure(caCert); var authKeyId = new AuthorityKeyIdentifier(caAuth.GetKeyIdentifier()); // Generating Random Numbers var randomGenerator = new CryptoApiRandomGenerator(); var random = new SecureRandom(randomGenerator); var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-()#$%^&@+=!"; var rnd = new Random(); var result = new string( Enumerable.Repeat(chars, 15) .Select(s => s[rnd.Next(s.Length)]) .ToArray()); password = result; var gen = new X509V3CertificateGenerator(); var certName = new X509Name("CN=" + subjectName); var serialNo = BigInteger.ProbablePrime(120, random); gen.SetSerialNumber(serialNo); gen.SetSubjectDN(certName); gen.SetIssuerDN(caCert.IssuerDN); // gen.SetIssuerUniqueID(caCert.IssuerUniqueID.GetBytes()) gen.SetNotAfter(expireOnUtc); gen.SetNotBefore(DateTime.Now.Subtract(new TimeSpan(7, 0, 0, 0))); gen.SetSignatureAlgorithm("SHA256WithRSA"); //("MD5WithRSA"); var kpgen = new RsaKeyPairGenerator(); kpgen.Init(new KeyGenerationParameters(random, 2048)); // new SecureRandom(new CryptoApiRandomGenerator()), 2048)); var subjectKeyPair = kpgen.GenerateKeyPair(); gen.SetPublicKey(subjectKeyPair.Public); //gen.AddExtension( // X509Extensions.ExtendedKeyUsage.Id, // false, // new ExtendedKeyUsage(new KeyPurposeID[] { KeyPurposeID.IdKPClientAuth, KeyPurposeID.IdKPServerAuth, KeyPurposeID.IdKPCodeSigning })); //1.3.6.1.5.5.7.3.1 = server authentication //1.3.6.1.5.5.7.3.2 = client authentication //1.3.6.1.5.5.7.3.3 = code signing var certificate = gen.Generate(caPrivateKey); PrivateKeyInfo info = PrivateKeyInfoFactory.CreatePrivateKeyInfo(subjectKeyPair.Private); // merge into X509Certificate2 var x509 = X509CertificateHelper.GetCertificate(certificate.GetEncoded(), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); var seq = (Asn1Sequence)Asn1Object.FromByteArray(info.PrivateKey.GetDerEncoded()); if (seq.Count != 9) { throw new PemException("Malformed sequence in RSA private key."); } var rsa = new RsaPrivateKeyStructure(seq); RsaPrivateCrtKeyParameters rsaparams = new RsaPrivateCrtKeyParameters( rsa.Modulus, rsa.PublicExponent, rsa.PrivateExponent, rsa.Prime1, rsa.Prime2, rsa.Exponent1, rsa.Exponent2, rsa.Coefficient); RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(rsaparams); CspParameters cspParameters = new CspParameters(); cspParameters.KeyContainerName = Guid.NewGuid().ToString(); // "MyKeyContainer"; RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(2048, cspParameters); rsaKey.ImportParameters(rsaParameters); x509.PrivateKey = rsaKey; cerData = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert); pkcs12Data = x509.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pkcs12, password); }
/// <summary> /// The AES Key/Value with the Private Key for Contract is for demonstration purpose only /// Feel free to use it. /// </summary> /// <param name="args"></param> public static void Main(string[] args) { string key = "aesKey"; string value = "testing"; string rnsResolvedAddress = GetRnsResolvedAddress("ranjancse.rsk", true); string nodeUrl = ConfigurationManager.AppSettings["RskTestnetNodeUrl"]; var privateKey = ConfigurationManager.AppSettings["PrivateKey"]; var fromTransferPrivateKey = ConfigurationManager.AppSettings["FromTransferPrivateKey"]; var account = new Nethereum.Web3.Accounts.Account(privateKey); IGasPriceService gasPriceService = new GasPriceService(nodeUrl); int gasPrice = gasPriceService.GetRskMinGasPrice(); // Load some RBTC LoadSomeRBTC(nodeUrl, fromTransferPrivateKey, account.Address, 0.001m, 0.06m); Stopwatch stopwatch = new Stopwatch(); System.Console.WriteLine("Trying to pull the RSA certificate from the local store using the Thumbprint"); // Get the certificate by Thumbprint string thumbPrint = ConfigurationManager.AppSettings["Thumbprint"].ToUpper(); X509Certificate2 filteredCert = X509CertificateHelper.GetRSKCertificate(thumbPrint, StoreLocation.LocalMachine); if (filteredCert == null) { System.Console.WriteLine($"Unable to find the RSK certificate by Thumbprint: " + $"{thumbPrint}"); System.Console.ReadLine(); return; } // Encrypt Text/Data var encryptedText = RSAEncryptionHelper.Encrypt(value, filteredCert); var url = ConfigurationManager.AppSettings["ContractDeploymentUrl"]; Web3 web3 = new Web3(account, url); // Get the balance stopwatch.Start(); var weiBalance = AccountHelper.GetBalance(web3, account); var etherAmount = Web3.Convert.FromWei(weiBalance.Value); stopwatch.Stop(); System.Console.WriteLine($"Account Balance: {etherAmount}"); System.Console.WriteLine($"Time take to fetch the balance:" + $" {stopwatch.Elapsed.Seconds} seconds"); // Gas estimated, in wei System.Console.WriteLine($"Estimated Gas Price: {gasPrice}"); System.Console.WriteLine("Deploying the Iterable Mapping Library"); stopwatch.Restart(); // Deploy Iterable Mapping Library TransactionReceipt transactionReceiptDeployment; string contractAddress; ContractHandler contractHandler; RSKContractHelper.DeployIterableMappingContract(web3, out transactionReceiptDeployment, out contractAddress, out contractHandler); stopwatch.Stop(); System.Console.WriteLine($"Iterable Mapping Contarct Address: " + $"{contractAddress}"); System.Console.WriteLine($"Time taken to deploy the Iterable mapping:" + $" {stopwatch.Elapsed.Seconds} seconds"); System.Console.WriteLine("Deploying the RSK KMS Contract"); // Deploy the RSK Contract stopwatch.Restart(); contractHandler = RSKContractHelper.DeployRSKKeyManagmentContract(web3, transactionReceiptDeployment, out contractAddress); stopwatch.Stop(); System.Console.WriteLine($"RSK Contract Address {contractAddress}"); System.Console.WriteLine($"Time taken to deploy the RSK Contract: " + $"{stopwatch.Elapsed.Seconds} seconds"); System.Console.WriteLine("Trying to set a value in RSK KMS Contract"); /** Function: setItem**/ var setItemRequest = new SetItemFunction { Key = key, Value = encryptedText, FromAddress = account.Address }; setItemRequest.GasPrice = new BigInteger(gasPrice * 1.1); stopwatch.Restart(); var setItemFunctionTxnReceipt = contractHandler .SendRequestAndWaitForReceiptAsync(setItemRequest) .ConfigureAwait(false) .GetAwaiter() .GetResult(); stopwatch.Stop(); System.Console.WriteLine($"Time taken to set the KMS Key Item: " + $"{stopwatch.Elapsed.Seconds} seconds"); System.Console.WriteLine("Trying to get a value from the RSK KMS Contract"); /** Function: getItem**/ var getItemRequest = new GetItemFunction { Key = key, FromAddress = account.Address }; stopwatch.Restart(); var getItemResponse = contractHandler .QueryAsync <GetItemFunction, string>(getItemRequest) .ConfigureAwait(false) .GetAwaiter() .GetResult(); stopwatch.Stop(); System.Console.WriteLine($"Time taken to get the KMS Key Item: " + $"{stopwatch.Elapsed.Seconds} seconds"); if (!string.IsNullOrEmpty(getItemResponse)) { var decryptedText = RSAEncryptionHelper.Decrypt(getItemResponse, filteredCert); System.Console.WriteLine($"Decrypted Text: {decryptedText}"); } else { System.Console.WriteLine("The KMS Response as empty"); } System.Console.WriteLine("Press any key to exit"); System.Console.ReadLine(); }