public void BeginEncrypting() //Our handshake routine { byte[] bKeyTemp; CngKey cCngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); byte[] cPublic = cCngKey.Export(CngKeyBlobFormat.EccPublicBlob); object[] oRecv = BlockingReceive(); if (!oRecv[0].Equals(Headers.HEADER_HANDSHAKE)) // Sanity check { throw new Exception("Unexpected error"); } byte[] sBuf = oRecv[1] as byte[]; using (var cAlgo = new ECDiffieHellmanCng(cCngKey)) using (CngKey sPubKey = CngKey.Import(sBuf, CngKeyBlobFormat.EccPublicBlob)) bKeyTemp = cAlgo.DeriveKeyMaterial(sPubKey); BlockingSend(Headers.HEADER_HANDSHAKE, cPublic); Log(String.Format("Handshake complete, key length: {0}", bKeyTemp.Length), ConsoleColor.Green); eCls = new Encryption(bKeyTemp, HASH_STRENGTH.MEDIUM); }
/// <summary> /// 使用EC DiffieHellman 521算法创建密钥 /// </summary> private static void CreateKeys() { _aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); _bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); _bobPubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); }
public void When_Private_Key_Cannot_Be_Extracted_Then_Exception_Is_Thrown() { // ARRANGE InitializeFakeObjects(); var keyCreationParameter = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.None }; var cnk = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameter); var isExceptionRaised = false; try { // ACT _cngKeySerializer.SerializeCngKeyWithPrivateKey(cnk); } catch (CryptographicException ex) { isExceptionRaised = true; } // ASSERT Assert.True(isExceptionRaised); }
} // End Function ExportToPEM #if false // http://stackoverflow.com/questions/11244333/how-can-i-use-ecdsa-in-c-sharp-with-a-key-size-of-less-than-the-built-in-minimum public static void ExportEcdsaKey() { byte[] publicKey = null; byte[] privateKey = null; using (ECDsaCng dsa = new ECDsaCng(256)) { dsa.HashAlgorithm = CngAlgorithm.Sha256; // publicKey = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob); // privateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob); } CngKey k = CngKey.Create(CngAlgorithm.ECDsaP256, "myECDH", new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, KeyUsage = CngKeyUsages.AllUsages, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, UIPolicy = new CngUIPolicy(CngUIProtectionLevels.None) }); System.Console.WriteLine(publicKey); System.Console.WriteLine(privateKey); }
public static void CreateEphemeral_WithParameters() { CngAlgorithm alg = CngAlgorithm.ECDiffieHellmanP256; CngKeyCreationParameters p = new CngKeyCreationParameters(); p.ExportPolicy = CngExportPolicies.AllowExport; p.KeyUsage = CngKeyUsages.KeyAgreement; p.UIPolicy = new CngUIPolicy(CngUIProtectionLevels.ForceHighProtection, "MyFriendlyName", "MyDescription", "MyUseContext", "MyCreationTitle"); byte[] myPropValue1 = "23afbc".HexToByteArray(); p.Parameters.Add(new CngProperty("MyProp1", myPropValue1, CngPropertyOptions.CustomProperty)); byte[] myPropValue2 = "8765".HexToByteArray(); p.Parameters.Add(new CngProperty("MyProp2", myPropValue2, CngPropertyOptions.CustomProperty)); using (CngKey key = CngKey.Create(alg, null, p)) { Assert.Equal(CngAlgorithm.ECDiffieHellmanP256, key.Algorithm); Assert.Equal(CngExportPolicies.AllowExport, key.ExportPolicy); Assert.Equal(CngKeyUsages.KeyAgreement, key.KeyUsage); CngUIPolicy uiPolicy = key.UIPolicy; Assert.Equal(CngUIProtectionLevels.ForceHighProtection, uiPolicy.ProtectionLevel); Assert.Equal("MyFriendlyName", uiPolicy.FriendlyName); Assert.Equal("MyDescription", uiPolicy.Description); Assert.Equal("MyUseContext", uiPolicy.UseContext); Assert.Equal("MyCreationTitle", uiPolicy.CreationTitle); byte[] propValue1Actual = key.GetProperty("MyProp1", CngPropertyOptions.CustomProperty).GetValue(); Assert.Equal <byte>(myPropValue1, propValue1Actual); byte[] propValue2Actual = key.GetProperty("MyProp2", CngPropertyOptions.CustomProperty).GetValue(); Assert.Equal <byte>(myPropValue2, propValue2Actual); } }
public UserAccount() { CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters(); keyCreationParameters.ExportPolicy = CngExportPolicies.AllowPlaintextExport; keyCreationParameters.KeyUsage = CngKeyUsages.Signing; CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters); ECDsaCng dsa = new ECDsaCng(key); //dsa = Digital Signature Algorithm byte[] privateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob); ECDSAPrivateKey = BitConverter.ToString(privateKey).Replace("-", String.Empty); //create public key byte[] publicKey = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob); ECSDAPublicKey = BitConverter.ToString(publicKey).Replace("-", String.Empty); //we calculate the hashvalue by slicing the end off of the public key string hashValue = ECDSAOperations.GetHashValue(publicKey); int hashLength = hashValue.Length; UserAddress = "0x" + hashValue.Substring(hashLength - ADDRESS_LENGTH); }
public static PBKeyPair GenerateKeyPair() { var pbKeyPair = new PBKeyPair(); if (CngKey.Exists(KEYNAME)) { CngKey.Open(KEYNAME).Delete(); } var keyPair = CngKey.Create(CngAlgorithm.ECDsaP256, KEYNAME, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyUsage = CngKeyUsages.AllUsages, }); var pub = keyPair.Export(CngKeyBlobFormat.GenericPublicBlob); var prv = keyPair.Export(CngKeyBlobFormat.GenericPrivateBlob); pbKeyPair.PublicKey = new PBPublicKey { PublicKey = ByteString.CopyFrom(pub, HEADER_SIZE, pub.Length - HEADER_SIZE) }; pbKeyPair.PrivateKey = ByteString.CopyFrom(prv, HEADER_SIZE + PUBLIC_KEY_SIZE, prv.Length - HEADER_SIZE - PUBLIC_KEY_SIZE); pbKeyPair.IssuedCerts = 0; return(pbKeyPair); }
public void CreateIssuerRSACngWithSuppliedKeyPair() { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Ignore("Cng provider only available on windows"); } X509Certificate2 issuer = null; CngKey cngKey = CngKey.Create(CngAlgorithm.Rsa); using (RSA rsaKeyPair = new RSACng(cngKey)) { // create cert with supplied keys var generator = X509SignatureGenerator.CreateForRSA(rsaKeyPair, RSASignaturePadding.Pkcs1); using (var cert = CertificateBuilder.Create("CN=Root Cert") .SetCAConstraint(-1) .SetRSAPublicKey(rsaKeyPair) .CreateForRSA(generator)) { Assert.NotNull(cert); issuer = new X509Certificate2(cert.RawData); WriteCertificate(cert, "Default root cert with supplied RSA cert"); } // now sign a cert with supplied private key using (var appCert = CertificateBuilder.Create("CN=App Cert") .SetIssuer(issuer) .CreateForRSA(generator)) { Assert.NotNull(appCert); WriteCertificate(appCert, "Signed RSA app cert"); } } }
public void CreateECDsaCertificate() { byte[] pfx = null; CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters(); keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport; keyCreationParameters.KeyUsage = CngKeyUsages.Signing; using (CngKey key = CngKey.Create(CngAlgorithm.ECDsaP256, null, keyCreationParameters)) { X509CertificateCreationParameters creationParams = new X509CertificateCreationParameters(new X500DistinguishedName("CN=TestECDSACert")); creationParams.SignatureAlgorithm = X509CertificateSignatureAlgorithm.ECDsaSha256; X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams); pfx = cert.Export(X509ContentType.Pfx, "TestPassword"); Assert.IsTrue(cert.HasPrivateKey); Assert.IsTrue(cert.HasCngKey()); } X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword"); Assert.IsTrue(rtCert.HasPrivateKey); Assert.IsTrue(rtCert.HasCngKey()); using (CngKey rtKey = rtCert.GetCngPrivateKey()) { Assert.AreEqual(CngAlgorithmGroup.ECDsa, rtKey.AlgorithmGroup); Assert.AreEqual(256, rtKey.KeySize); } }
private ECDsaCng CreateECDKey(out byte[] PrivateKey, out byte[] PublicKey, string KeyName, string keyAlias) { //генерируем точку (ключ) P var p = new CngKeyCreationParameters { //задаем политику экспорта (может экспортироваться несколько раз) ExportPolicy = CngExportPolicies.AllowPlaintextExport, //параметры (может перезаписываться) KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey, //пользовательский интерфейс (уровень защиты секретный ключ, имя ключа) UIPolicy = new CngUIPolicy(CngUIProtectionLevels.ProtectKey, KeyName, null, null, null) }; //создаем ключ (Алгоритм, в котором будет использоваться ключ; имя ключа и p) var key = CngKey.Create(CngAlgorithm.ECDsaP521, keyAlias, p); using (ECDsaCng dsa = new ECDsaCng(key)) { //используем алгоритм хэша Sha512 dsa.HashAlgorithm = CngAlgorithm.Sha512; //получаем открытые и закрытые ключи PublicKey = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob); PrivateKey = dsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob); return(dsa); } }
/// <summary> /// Import the certificate with private key to the machine MY store while force using Software KSP. /// /// See https://stackoverflow.com/questions/51522330/c-sharp-import-certificate-and-key-pfx-into-cng-ksp /// </summary> private static void ImportPFX2MachineStore(bool useDebugOutput, string pfxPassword, byte[] issuedPkcs12) { using X509Certificate2 issuedCertificateAndPrivate = new X509Certificate2(issuedPkcs12, pfxPassword, X509KeyStorageFlags.Exportable); RSACng keyFromPFx = new RSACng(); keyFromPFx.FromXmlString(issuedCertificateAndPrivate.GetRSAPrivateKey().ToXmlString(true)); var keyData = keyFromPFx.Key.Export(CngKeyBlobFormat.GenericPrivateBlob); var keyParams = new CngKeyCreationParameters { ExportPolicy = useDebugOutput ? CngExportPolicies.AllowPlaintextExport : CngExportPolicies.None, KeyCreationOptions = CngKeyCreationOptions.MachineKey, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider }; keyParams.Parameters.Add(new CngProperty(CngKeyBlobFormat.GenericPrivateBlob.Format, keyData, CngPropertyOptions.None)); CngKey key = CngKey.Create(CngAlgorithm.Rsa, $"KDC-Key-{issuedCertificateAndPrivate.Thumbprint}", keyParams); RSACng rsaCNG = new RSACng(key); X509Certificate2 certWithCNGKey = new X509Certificate2(issuedCertificateAndPrivate.Export(X509ContentType.Cert)); certWithCNGKey = certWithCNGKey.CopyWithPrivateKey(rsaCNG); using X509Store storeLmMy = new X509Store(StoreName.My, StoreLocation.LocalMachine, OpenFlags.ReadWrite | OpenFlags.OpenExistingOnly); storeLmMy.Add(certWithCNGKey); storeLmMy.Close(); }
Task <D2LSecurityToken> IPrivateKeyProvider.GetSigningCredentialsAsync() { var creationParams = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyUsage = CngKeyUsages.Signing }; byte[] privateBlob; using (var cngKey = CngKey.Create(m_algorithm, null, creationParams)) { using (ECDsaCng ecDsa = new ECDsaCng(cngKey)) { privateBlob = ecDsa.Key.Export(CngKeyBlobFormat.EccPrivateBlob); } } D2LSecurityToken result = m_d2lSecurityTokenFactory.Create(() => { using (var cng = CngKey.Import(privateBlob, CngKeyBlobFormat.EccPrivateBlob)) { // ECDsaCng copies the CngKey, hence the using var ecDsa = new ECDsaCng(cng); var key = new EcDsaSecurityKey(ecDsa); return(new Tuple <AsymmetricSecurityKey, IDisposable>(key, ecDsa)); } }); return(Task.FromResult(result)); }
public string Encrypt(string plainTestPassword, string keyName) { CngKey key; if (CngKey.Exists(keyName)) { key = CngKey.Open(keyName); } else { key = CngKey.Create(CngAlgorithm.Rsa, keyName, new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowPlaintextArchiving }); } var cng = new RSACng(key); var encryptedData = cng.Encrypt(Encoding.UTF8.GetBytes(plainTestPassword), RSAEncryptionPadding.Pkcs1); var encodedData = Convert.ToBase64String(encryptedData); return(encodedData); }
public static void CreateKeys() { // 根据算法创建密钥对 aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP256); // 导出密钥对中的公钥 alicePubKeyBlob = aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob); }
/// <summary> /// Create a CNG keypair /// </summary> /// <param name="pkAlgo">Key algorithm (from supported set)</param> /// <param name="name">Key container name</param> /// <returns> /// CNG keypair /// </returns> /// <exception cref="System.NotSupportedException">Creation of key not supported for: + pkAlgo.Algorithm</exception> /// <remarks> /// Keys are exportable /// </remarks> public static CngKey Create(CngAlgorithm pkAlgo, string name) { // Normalise the name string _name = name.Replace(' ', '_'); CngKeyCreationParameters keyParams = new CngKeyCreationParameters(); keyParams.ExportPolicy = CngExportPolicies.AllowPlaintextExport; keyParams.KeyCreationOptions = CngKeyCreationOptions.OverwriteExistingKey; keyParams.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider; // Note that CngAlgorithm is not an enum if (pkAlgo.Algorithm.Contains("ECDSA")) { keyParams.KeyUsage = CngKeyUsages.Signing; } else if (pkAlgo.Algorithm.Contains("ECDH")) { keyParams.KeyUsage = CngKeyUsages.KeyAgreement; } else { throw new NotSupportedException("Creation of key not supported for: " + pkAlgo.Algorithm); } return(CngKey.Create(pkAlgo, _name, keyParams)); }
public void Create2048RsaCertificate() { CngKeyCreationParameters keyCreationParameters = new CngKeyCreationParameters(); keyCreationParameters.ExportPolicy = CngExportPolicies.AllowExport; keyCreationParameters.KeyCreationOptions = CngKeyCreationOptions.None; keyCreationParameters.KeyUsage = CngKeyUsages.AllUsages; keyCreationParameters.Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider; int keySize = 2048; keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(keySize), CngPropertyOptions.None)); byte[] pfx = null; using (CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters)) { X509Certificate2 cert = key.CreateSelfSignedCertificate(new X500DistinguishedName("CN=TestRSAKey")); pfx = cert.Export(X509ContentType.Pfx, "TestPassword"); Assert.IsTrue(cert.HasPrivateKey); Assert.IsTrue(cert.HasCngKey()); } X509Certificate2 rtCert = new X509Certificate2(pfx, "TestPassword"); Assert.IsTrue(rtCert.HasPrivateKey); Assert.IsTrue(rtCert.HasCngKey()); using (CngKey rtKey = rtCert.GetCngPrivateKey()) { Assert.AreEqual(CngAlgorithm2.Rsa, rtKey.Algorithm); Assert.AreEqual(2048, rtKey.KeySize); } }
public static string Encode(string privateKey) { var a = Convert.FromBase64String(privateKey); byte[] keyBytes = Encoding.UTF8.GetBytes(privateKey); var header = new Dictionary <string, object>() { { "kid", "kid" } }; var payload = new Dictionary <string, object>() { { "iss", "teamId" }, { "iat", new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds() }, { "exp", new DateTimeOffset(DateTime.UtcNow.AddMinutes(5)).ToUnixTimeSeconds() }, { "aud", "https://appleid.apple.com" }, { "sub", "client_id" }, }; var key = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob); var privatekey = new ECDsaCng(CngKey.Create(CngAlgorithm.ECDsaP256)); privatekey.SignData(a, 0, a.Length, HashAlgorithmName.SHA256); return(Jose.JWT.Encode(payload, key, JwsAlgorithm.ES256, header)); }
public void CreateKeys() { _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); bobkey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); alicePubKeyBlob = aliceKey.Export(CngKeyBlobFormat.EccPublicBlob); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.EccPublicBlob); }
private static void CreateKeys() { aliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); alicePubKeyBlod = aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); bobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); bobPubKeyBlob = bobKey.Export(CngKeyBlobFormat.GenericPublicBlob); }
/// <summary> /// 使用RSA算法创建密钥 /// </summary> private void InitAliceKeys() { //创建公钥和私钥 _aliceKey = CngKey.Create(CngAlgorithm.Rsa); //公钥只提供给Bob,所以公钥使用Export方法提取 _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); }
/// <summary> /// 为Alice创建新的密钥对。因为这个密钥对存储在一个静态字段中,所以可以从其他方法中访问它。 /// 除了使用CngKey类创建密钥对之外,还可以打开存储在密钥存储器中的己有密钥。 /// 通常Alice在其私有存储器中有一个证书,其中包含了一个密钥对,该存储器可以用CngKey.Open()方法访问。 /// </summary> private static void InitAliceKeys() { // CngKey类的Creat()方法把该算法作为一个参数,为算法定义密钥对。 _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP521); // 通过Export()方法,导出密钥对中的公钥。这个公钥可以提供给Bob,来验证签名。Alice保留其私钥。 _alicePublicKeyBlob = _aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob); }
//创建新的密钥对 private static void InitAliceKeys() { // Encoding.UTF8.GetBytes把CngAlgorithm.ECDsaP521作为参数,为算法定义密钥对 _aliceKeySignature = CngKey.Create(CngAlgorithm.ECDsaP521); // 通过_aliceKeySignature.Export导出密钥中的公钥,这个公钥可以提供给其他人来验证 _alicePubKeyBlob = _aliceKeySignature.Export(CngKeyBlobFormat.GenericPublicBlob); }
public static void VerifyMachineKey( CngAlgorithm algorithm, int plainBytesCount, Func <string, SymmetricAlgorithm> persistedFunc, Func <SymmetricAlgorithm> ephemeralFunc) { string keyName = Guid.NewGuid().ToString(); CngKeyCreationParameters creationParameters = new CngKeyCreationParameters { Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider, ExportPolicy = CngExportPolicies.AllowPlaintextExport, KeyCreationOptions = CngKeyCreationOptions.MachineKey, }; CngKey cngKey = CngKey.Create(algorithm, keyName, creationParameters); try { VerifyPersistedKey( keyName, plainBytesCount, persistedFunc, ephemeralFunc, CipherMode.CBC, PaddingMode.PKCS7); } finally { // Delete also Disposes the key, no using should be added here. cngKey.Delete(); } }
private void Auth() { UserChoose userChoose = new UserChoose(); if (userChoose.ShowDialog() == DialogResult.OK) { if (CngKey.Exists(current_user)) { CngKey ck = CngKey.Open(current_user); ecdsaCng = new ECDsaCng(ck); } else { CngKey ck = CngKey.Create(CngAlgorithm.ECDsaP256, current_user); ecdsaCng = new ECDsaCng(ck); } if (!Directory.Exists(PK_store_path)) { Directory.CreateDirectory(PK_store_path); } if (!Directory.Exists(PK_store_path + "\\" + current_user)) { Directory.CreateDirectory(PK_store_path + "\\" + current_user); } reset_form(); } }
public static X509Certificate2 CreateCertificate(string password, string issuer = "CN=Microsoft Azure Powershell Test", string friendlyName = "PSTest") { var keyCreationParameters = new CngKeyCreationParameters { ExportPolicy = CngExportPolicies.AllowExport, KeyCreationOptions = CngKeyCreationOptions.None, KeyUsage = CngKeyUsages.AllUsages, Provider = CngProvider.MicrosoftSoftwareKeyStorageProvider }; keyCreationParameters.Parameters.Add(new CngProperty("Length", BitConverter.GetBytes(2048), CngPropertyOptions.None)); CngKey key = CngKey.Create(CngAlgorithm2.Rsa, null, keyCreationParameters); var creationParams = new X509CertificateCreationParameters(new X500DistinguishedName(issuer)) { TakeOwnershipOfKey = true }; X509Certificate2 cert = key.CreateSelfSignedCertificate(creationParams); key = null; cert.FriendlyName = friendlyName; byte[] bytes = cert.Export(X509ContentType.Pfx, password); X509Certificate2 returnCert = new X509Certificate2(); returnCert.Import(bytes, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable); return(returnCert); }
//[Fact] - Keeping this test for reference but we don't want to run it as an inner-loop test because // it creates a key on disk. public static void AesRoundTrip256BitsNoneECBUsingStoredKey() { CngAlgorithm algname = new CngAlgorithm("AES"); string keyName = "CoreFxTest-" + Guid.NewGuid(); CngKey _cngKey = CngKey.Create(algname, keyName); try { using (Aes alg = new AesCng(keyName)) { try { alg.Padding = PaddingMode.None; alg.Mode = CipherMode.ECB; int keySize = alg.KeySize; byte[] plainText = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray(); byte[] cipher = alg.Encrypt(plainText); byte[] decrypted = alg.Decrypt(cipher); byte[] expectedDecrypted = "15a818701f0f7c99fe4b1b4b860f131b".HexToByteArray(); Assert.Equal <byte>(expectedDecrypted, decrypted); } catch (Exception e) { Console.WriteLine(e.Message); } } } finally { _cngKey.Delete(); } }
public CngKey GetOrGenerateKey(int keySize, CngAlgorithm algorithm) { // If our key size was changed, we need to generate a new key. if (_lazyKey != null) { if (_lazyKey.KeySize != keySize) { DisposeKey(); } } // If we don't have a key yet, we need to generate one now. if (_lazyKey == null) { CngKeyCreationParameters creationParameters = new CngKeyCreationParameters() { ExportPolicy = CngExportPolicies.AllowPlaintextExport, }; CngProperty keySizeProperty = new CngProperty(KeyPropertyName.Length, BitConverter.GetBytes(keySize), CngPropertyOptions.None); creationParameters.Parameters.Add(keySizeProperty); _lazyKey = CngKey.Create(algorithm, null, creationParameters); } return(_lazyKey); }
private static void InitAliceKeys() { //创建Alice所需密钥,使用RSA算法 _aliceKey = CngKey.Create(CngAlgorithm.Rsa); //创建公钥 _alicePubKeyBlob = _aliceKey.Export(CngKeyBlobFormat.GenericPublicBlob); }
public void TestEcdhKeys() { // To make sure keys are exportable: // http://stackoverflow.com/questions/20505325/how-to-export-private-key-for-ecdiffiehellmancng/20505976#20505976 var ecdhKeyParams = new CngKeyCreationParameters { KeyUsage = CngKeyUsages.AllUsages, ExportPolicy = CngExportPolicies.AllowPlaintextExport }; var ecdhKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, ecdhKeyParams); var ecdh = new ECDiffieHellmanCng(ecdhKey); ecdh.KeySize = 256; //Export the keys var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob); // This returns: // [ { MinSize = 256; MaxSize = 384; SkipSize = 128 } // { MinSize = 521; MaxSize = 521; SkipSize = 0 } ] var keySizes = ecdh.LegalKeySizes; // Example of this: // <ECDHKeyValue xmlns="http://www.w3.org/2001/04/xmldsig-more#"> // <DomainParameters> // <NamedCurve URN="urn:oid:1.3.132.0.35" /> // </DomainParameters> // <PublicKey> // <X Value="6338036285454860977775086861655185721418051140960904673987863656163882965225521398319125216217757952736756437624751684728661860413862054254572205453827782795" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> // <Y Value="2429739115523607678822648112222739155064474393176967830414279652115290771735466025346855521196073509912224542851147234378090051353981358078708633637907317343" xsi:type="PrimeFieldElemType" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" /> // </PublicKey> // </ECDHKeyValue> var pubKeyXml = ecdh.PublicKey.ToXmlString(); }
private static void CreateKeys() { AliceKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); BobKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256); AlicePubKeyBlob = AliceKey.Export(CngKeyBlobFormat.EccPublicBlob); BobPubKeyBlob = BobKey.Export(CngKeyBlobFormat.EccPublicBlob); }