private static void VerifyImportedKey(CngKey key) { Assert.Equal(new CngAlgorithm("DSA"), key.Algorithm); Assert.Equal(CngAlgorithmGroup.Dsa, key.AlgorithmGroup); Assert.Equal(CngExportPolicies.None, key.ExportPolicy); Assert.Equal(true, key.IsEphemeral); Assert.Equal(false, key.IsMachineKey); Assert.Equal(null, key.KeyName); Assert.Equal(CngKeyUsages.AllUsages, key.KeyUsage); Assert.Equal(IntPtr.Zero, key.ParentWindowHandle); Assert.Equal(CngProvider.MicrosoftSoftwareKeyStorageProvider, key.Provider); CngUIPolicy policy = key.UIPolicy; Assert.Equal(null, policy.CreationTitle); Assert.Equal(null, policy.Description); Assert.Equal(null, policy.FriendlyName); Assert.Equal(null, policy.UseContext); Assert.Equal(CngUIProtectionLevels.None, policy.ProtectionLevel); Assert.Equal(null, key.UniqueName); }
/// <exception cref="ArgumentNullException">key.</exception> /// <exception cref="ArgumentOutOfRangeException">key.Algorithm.</exception> public MoleECDsaCng(CngKey key) { if (key == null) { throw new ArgumentNullException(nameof(key)) { Source = GetType().AssemblyQualifiedName } } ; if ( !new[] { CngAlgorithm.ECDsaP256, CngAlgorithm.ECDsaP384, CngAlgorithm.ECDsaP521 }.Any( algorithm => algorithm == key.Algorithm)) { throw new ArgumentOutOfRangeException(nameof(key.Algorithm)) { Source = GetType().AssemblyQualifiedName } } ; EcDsaCng = new ECDsaCng(key); }
public static Int32 GetKeyLength(this PublicKey publicKey) { if (publicKey == null) { throw new ArgumentNullException(nameof(publicKey)); } switch (publicKey.Oid.Value) { case AlgorithmOid.RSA: case AlgorithmOid.DSA: return(publicKey.Key.KeySize); case AlgorithmOid.ECC: var cryptBlob = publicKey.GetCryptBlob(); using (CngKey cngKey = CngKey.Import(cryptBlob, CngKeyBlobFormat.EccPublicBlob)) { return(cngKey.KeySize); } default: return(0); } }
public static unsafe byte[] SignHash(CngKey key, byte[] hash, AsymmetricPaddingMode paddingMode, void *pPaddingInfo, int estimatedSize) { #if DEBUG estimatedSize = 2; // Make sure the NTE_BUFFER_TOO_SMALL scenario gets exercised. #endif SafeNCryptKeyHandle keyHandle = key.Handle; byte[] signature = new byte[estimatedSize]; int numBytesNeeded; ErrorCode errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out numBytesNeeded, paddingMode); if (errorCode == ErrorCode.NTE_BUFFER_TOO_SMALL) { signature = new byte[numBytesNeeded]; errorCode = Interop.NCrypt.NCryptSignHash(keyHandle, pPaddingInfo, hash, hash.Length, signature, signature.Length, out numBytesNeeded, paddingMode); } if (errorCode != ErrorCode.ERROR_SUCCESS) { throw errorCode.ToCryptographicException(); } Array.Resize(ref signature, numBytesNeeded); return(signature); }
public static string CreateNewToken() { const string iss = "62QM29578N"; // your accounts team ID found in the dev portal const string aud = "https://appleid.apple.com"; const string sub = "com.scottbrady91.authdemo.service"; // same as client_id const string privateKey = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgnbfHJQO9feC7yKOenScNctvHUP+Hp3AdOKnjUC3Ee9GgCgYIKoZIzj0DAQehRANCAATMgckuqQ1MhKALhLT/CA9lZrLA+VqTW/iIJ9GKimtC2GP02hCc5Vac8WuN6YjynF3JPWKTYjg2zqex5Sdn9Wj+"; var cngKey = CngKey.Import(Convert.FromBase64String(privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob); var handler = new JwtSecurityTokenHandler(); var token = handler.CreateJwtSecurityToken( issuer: iss, audience: aud, subject: new ClaimsIdentity(new List <Claim> { new Claim("sub", sub) }), expires: DateTime.UtcNow.AddMinutes(5), // expiry can be a maximum of 6 months => generate one per request, or one and then re-use until expiration issuedAt: DateTime.UtcNow, notBefore: DateTime.UtcNow, signingCredentials: new SigningCredentials(new ECDsaSecurityKey(new ECDsaCng(cngKey)), SecurityAlgorithms.EcdsaSha256)); return(handler.WriteToken(token)); }
private string GenerateToken() { try { //https://github.com/dvsekhvalnov/jose-jwt var unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var payload = new Dictionary <string, object>() { { "iat", unixTimestamp }, { "token", ClientToken } }; var secretKeyFile = Convert.FromBase64String(PrivateKey); //Note: the next line of code fails with "CryptographicException: The system cannot find the file specified." //if the IIS APP POOL Load user profile is NOT true var secretKey = CngKey.Import(secretKeyFile, CngKeyBlobFormat.Pkcs8PrivateBlob); return(JWT.Encode(payload, secretKey, JwsAlgorithm.ES256)); } catch (Exception ex) { HandleInnerException(ex, "GenerateToken()"); return(null); } }
/// <summary> /// 根据传入的公钥与签名,对可签名对象的签名进行验证 /// </summary> /// <param name="signable">要验证的数据</param> /// <param name="pubkey">公钥</param> /// <param name="signature">签名</param> /// <returns>返回验证结果</returns> public static bool VerifySignature(this ISignable signable, Cryptography.ECC.ECPoint pubkey, byte[] signature) { byte[] pubk = pubkey.EncodePoint(false).Skip(1).ToArray(); #if NET461 const int ECDSA_PUBLIC_P256_MAGIC = 0x31534345; pubk = BitConverter.GetBytes(ECDSA_PUBLIC_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubk).ToArray(); using (CngKey key = CngKey.Import(pubk, CngKeyBlobFormat.EccPublicBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) #else using (var ecdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, Q = new ECPoint { X = pubk.Take(32).ToArray(), Y = pubk.Skip(32).ToArray() } })) #endif { return(ecdsa.VerifyHash(signable.GetHashForSigning(), signature)); } }
/// <summary> /// Validates if a signiture is legitimate. /// publicID is the Id of the wallet making the transaction. /// datahash is the hash of transaction /// datasig is the hash created by the private key and datahash /// The datasig can be validated with the above parameters. /// </summary> /// <param name="publicID"></param> /// <param name="datahash"></param> /// <param name="datasig"></param> /// <returns></returns> public static bool ValidateSignature(String publicID, String datahash, String datasig) { // Handle "Rewards" if (publicID.Equals("Mine Rewards")) { publicID = "QfF3+9GgTxyGLvb+ScOAI6nJxBh8IyZbeD0r6BJBMyabZmyuP82yrSLKMq/F05OG0VZ4gg63uHFZUKzCu3wZuA=="; } if (publicID.Length != 88 || datasig.Equals("null")) { return(false); } CngKey key = createKey(publicID); if (key == null) { return(false); } ECDsaCng dsa = new ECDsaCng(key); return(dsa.VerifyData(Convert.FromBase64String(datahash), Convert.FromBase64String(datasig))); }
/// <summary> /// 根据传入的公私钥,对可签名的对象进行签名 /// </summary> /// <param name="signable">要签名的数据</param> /// <param name="prikey">私钥</param> /// <param name="pubkey">公钥</param> /// <returns>返回签名后的结果</returns> internal static byte[] Sign(this ISignable signable, byte[] prikey, byte[] pubkey) { #if NET461 const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345; prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray(); using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) #else using (var ecdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = prikey, Q = new ECPoint { X = pubkey.Take(32).ToArray(), Y = pubkey.Skip(32).ToArray() } })) #endif { return(ecdsa.SignHash(signable.GetHashForSigning())); } }
protected override void Read(BinaryReader reader) { base.Read(reader); _parentID = reader.ReadInt32(); _name = reader.ReadSrfsString(); KeyThumbprint encryptionKeyThumbprint = reader.ReadKeyThumbprint(); if (!encryptionKeyThumbprint.Equals(_decryptionKey.Thumbprint)) { throw new System.IO.IOException(); } CngKey publicSourceKey = reader.ReadPublicKey().Key; reader.ReadBytes(PaddingLength); byte[] encryptedData = reader.ReadBytes(_plainTextData.Length); using (ECDiffieHellmanCng destinationKey = new ECDiffieHellmanCng(_decryptionKey.Key)) { _plainTextData = Decrypt(destinationKey, publicSourceKey, encryptedData, 0, encryptedData.Length); } }
private ICertificatePal CopyWithEphemeralKey(CngKey cngKey) { Debug.Assert(string.IsNullOrEmpty(cngKey.KeyName)); SafeNCryptKeyHandle handle = cngKey.Handle; // Make a new pal from bytes. CertificatePal pal = (CertificatePal)FromBlob(RawData, SafePasswordHandle.InvalidHandle, X509KeyStorageFlags.PersistKeySet); if (!Interop.crypt32.CertSetCertificateContextProperty( pal._certContext, CertContextPropId.CERT_NCRYPT_KEY_HANDLE_PROP_ID, CertSetPropertyFlags.CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, handle)) { pal.Dispose(); throw Marshal.GetLastWin32Error().ToCryptographicException(); } // The value was transferred to the certificate. handle.SetHandleAsInvalid(); return(pal); }
public static byte[] Encrypt(byte[] plainText, CngKey key, CngAlgorithm hash) { var paddingInfo = new BCrypt.BCRYPT_OAEP_PADDING_INFO(hash.Algorithm); uint cipherTextByteSize; uint status = NCrypt.NCryptEncrypt(key.Handle, plainText, plainText.Length, ref paddingInfo, null, 0, out cipherTextByteSize, BCrypt.BCRYPT_PAD_OAEP); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.Encrypt() (ciphertext buffer size) failed with status code:{0}", status)); } var cipherText = new byte[cipherTextByteSize]; status = NCrypt.NCryptEncrypt(key.Handle, plainText, plainText.Length, ref paddingInfo, cipherText, cipherTextByteSize, out cipherTextByteSize, BCrypt.BCRYPT_PAD_OAEP); if (status != BCrypt.ERROR_SUCCESS) { throw new CryptographicException(string.Format("NCrypt.Encrypt() failed with status code:{0}", status)); } return(cipherText); }
public byte[] Sign(byte[] message, byte[] prikey, byte[] pubkey) { #if NET461 const int ECDSA_PRIVATE_P256_MAGIC = 0x32534345; prikey = BitConverter.GetBytes(ECDSA_PRIVATE_P256_MAGIC).Concat(BitConverter.GetBytes(32)).Concat(pubkey).Concat(prikey).ToArray(); using (CngKey key = CngKey.Import(prikey, CngKeyBlobFormat.EccPrivateBlob)) using (ECDsaCng ecdsa = new ECDsaCng(key)) #else using (var ecdsa = ECDsa.Create(new ECParameters { Curve = ECCurve.NamedCurves.nistP256, D = prikey, Q = new ECPoint { X = pubkey.Take(32).ToArray(), Y = pubkey.Skip(32).ToArray() } })) #endif { return(ecdsa.SignData(message, HashAlgorithmName.SHA256)); } }
[PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public static void CollectionPerphemeralImport_HasKeyName() { using (var importedCollection = Cert.Import(TestData.PfxData, TestData.PfxDataPassword, X509KeyStorageFlags.DefaultKeySet)) { X509Certificate2 cert = importedCollection.Collection[0]; using (RSA rsa = cert.GetRSAPrivateKey()) { Assert.NotNull(rsa); // While RSACng is not a guaranteed answer, it's currently the answer and we'd have to // rewrite the rest of this test if it changed. RSACng rsaCng = rsa as RSACng; Assert.NotNull(rsaCng); CngKey key = rsaCng.Key; Assert.NotNull(key); Assert.False(key.IsEphemeral, "key.IsEphemeral"); Assert.NotNull(key.KeyName); } } }
public static RSACng GetOrCreateRSACng(string rsaKeyName) { Guard.AgainstNullOrEmpty(rsaKeyName, nameof(rsaKeyName)); CngKey cngKey; if (CngKey.Exists(rsaKeyName)) { cngKey = CngKey.Open(rsaKeyName); } else { var cngLengthProperty = new CngProperty( _lengthPropertyName, BitConverter.GetBytes(KeySize), CngPropertyOptions.None); var cngKeyCreationParameters = new CngKeyCreationParameters { KeyUsage = CngKeyUsages.AllUsages, ExportPolicy = CngExportPolicies.AllowPlaintextExport | CngExportPolicies.AllowExport | CngExportPolicies.AllowArchiving | CngExportPolicies.AllowPlaintextArchiving }; cngKeyCreationParameters.Parameters.Add(cngLengthProperty); cngKey = CngKey.Create(CngAlgorithm.Rsa, rsaKeyName, cngKeyCreationParameters); } return(new RSACng(cngKey) { KeySize = KeySize }); }
/// <summary> /// 加密 /// </summary> /// <param name="message"></param> /// <returns></returns> private async Task <byte[]> AliceSendsDataAsync(string message) { Console.WriteLine("Alice sends message:" + message); byte[] rawData = Encoding.UTF8.GetBytes(message); byte[] encryptedData = null; //创建ECDiffieHellmanCng对象,并使用Alice的密钥对初始化它 using (ECDiffieHellmanCng aliceAlgorithm = new ECDiffieHellmanCng(_aliceKey)) using (CngKey bobPubKey = CngKey.Import(_bobPubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { //使用Alice的密钥对和Bob的公钥创建一个对称密钥,返回的对称密钥使用对称算法AES加密数据 byte[] symmKey = aliceAlgorithm.DeriveKeyMaterial(bobPubKey); Console.WriteLine("Alice creates thsi symmetric key with Bobs public key Information:" + Convert.ToBase64String(symmKey)); // using (AesCryptoServiceProvider aes = new AesCryptoServiceProvider()) { aes.Key = symmKey; aes.GenerateIV(); using (ICryptoTransform encryptor = aes.CreateEncryptor()) using (MemoryStream ms = new MemoryStream()) { using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) { await ms.WriteAsync(aes.IV, 0, aes.IV.Length); cs.Write(rawData, 0, rawData.Length); } encryptedData = ms.ToArray(); } //在访问内存流中的加密数据之前,必须关闭加密流,否则加密数据就会丢失最后的位 aes.Clear(); } } Console.WriteLine("Alice:message is encrypted:" + Convert.ToBase64String(encryptedData)); Console.WriteLine(); return(encryptedData); }
private void Decrypt() { if (string.IsNullOrEmpty(OtherEncryptedDataTextBox.Text)) { OtherDecryptedTextBox.Text = ""; return; } OtherDecryptedTextBox.Text = "Decrypting..."; try { var keyBlob = System.Convert.FromBase64String(PrivateKeyTextBox.Text); var privateKey = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob); var ecdh = new System.Security.Cryptography.ECDiffieHellmanCng(privateKey); // Other key var otherPartyKeyBlob = System.Convert.FromBase64String(OtherPublicKeyTextBox.Text); var otherPartyPublicKey = CngKey.Import(otherPartyKeyBlob, CngKeyBlobFormat.EccPublicBlob); // Decrypt the passed byte array and specify OAEP padding. var symetricKey = ecdh.DeriveKeyMaterial(otherPartyPublicKey); var symetricKeyBase64 = ToBase64(symetricKey); var encryptedBytes = System.Convert.FromBase64String(OtherEncryptedDataTextBox.Text); var decryptedBytes = Decrypt(symetricKey, encryptedBytes); // Remove random prefix. decryptedBytes = RemoveRandom(decryptedBytes); var decryptedData = System.Text.Encoding.UTF8.GetString(decryptedBytes); OtherDecryptedTextBox.Foreground = System.Windows.SystemColors.ControlTextBrush; OtherDecryptedTextBox.Text = decryptedData; } catch (Exception ex) { OtherDecryptedTextBox.Foreground = new SolidColorBrush(System.Windows.Media.Colors.DarkRed); OtherDecryptedTextBox.Text = ex.Message; } }
/// <summary>创建ECDsa对象,支持Base64密钥和Pem密钥</summary> /// <param name="key"></param> /// <param name="privateKey"></param> /// <returns></returns> public static ECDsaCng Create(String key, Boolean?privateKey = null) { key = key?.Trim(); if (key.IsNullOrEmpty()) { return(null); } if (key.StartsWith("-----") && key.EndsWith("-----")) { var ek = ReadPem(key); #if __CORE__ // netcore下优先使用ExportParameters,CngKey.Import有兼容问题 var ec = new ECDsaCng(); ec.ImportParameters(ek.ExportParameters()); return(ec); #else var buf = ek.ToArray(); var ckey = CngKey.Import(buf, ek.D == null ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob); return(new ECDsaCng(ckey)); #endif } else { var buf = key.ToBase64(); var ckey = privateKey != null? CngKey.Import(buf, !privateKey.Value?CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob) : CngKey.Import(buf, buf.Length < 100 ? CngKeyBlobFormat.EccPublicBlob : CngKeyBlobFormat.EccPrivateBlob); return(new ECDsaCng(ckey)); } }
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"); CheckPEMWriter(cert); } // now sign a cert with supplied private key using (var appCert = CertificateBuilder.Create("CN=App Cert") .SetIssuer(issuer) .CreateForRSA(generator)) { Assert.NotNull(appCert); Assert.AreEqual(issuer.SubjectName.Name, appCert.IssuerName.Name); Assert.AreEqual(issuer.SubjectName.RawData, appCert.IssuerName.RawData); WriteCertificate(appCert, "Signed RSA app cert"); CheckPEMWriter(appCert); } } }
public void Invoke() { int blockSize = 512; Options options = Options.None; if (doNotVerifyHashes) { options |= Options.DoNotVerifyClusterHashes; } if (doNotVerifySignatures) { options |= Options.DoNotVerifyClusterSignatures; } Configuration.Options = options; CngKey encryptionKey = CryptoSettingsOptions.GetEncryptionKey(); CngKey decryptionKey = CryptoSettingsOptions.GetDecryptionKey(); CngKey signingKey = CryptoSettingsOptions.GetSigningKey(); Configuration.CryptoSettings = new CryptoSettings(decryptionKey, signingKey, encryptionKey); long size = new FileInfo(FilePath).Length; using (MemoryIO io = new MemoryIO((int)size, blockSize)) using (FileStream fio = new FileStream(FilePath, FileMode.Open)) { fio.Read(io.Bytes, 0, (int)io.SizeBytes); using (var fs = FileSystem.Mount(io)) { SRFSDokan d = new SRFSDokan(fs); d.Mount("S:\\"); } fio.Position = 0; fio.Write(io.Bytes, 0, (int)io.SizeBytes); } }
public override byte[] DecryptValue(byte[] rgb) { if (rgb == null) { throw new ArgumentNullException("rgb"); } // Keep a local copy of the key to prevent races with the key container that the key references // and the key container permission we're going to demand. CngKey key = Key; // Make sure we have permission to use the private key to decrypt data KeyContainerPermission kcp = BuildKeyContainerPermission(key, KeyContainerPermissionFlags.Decrypt); if (kcp != null) { kcp.Demand(); } new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Assert(); SafeNCryptKeyHandle keyHandle = key.Handle; CodeAccessPermission.RevertAssert(); switch (EncryptionPaddingMode) { case AsymmetricPaddingMode.Pkcs1: return(NCryptNative.DecryptDataPkcs1(keyHandle, rgb)); case AsymmetricPaddingMode.Oaep: return(NCryptNative.DecryptDataOaep(keyHandle, rgb, EncryptionHashAlgorithm.Algorithm)); default: throw new InvalidOperationException(Properties.Resources.UnsupportedPaddingMode); } ; }
private void Listen() { if (Proxy == null) { Proxy = new Publisher(PrivateSpace, Space, ConcealedSpace); } Proxy.Running = true; while (true) { var request = Space.Get("Request", typeof(HubRequestType), typeof(string), typeof(string)); var identifier = request.Get <string>(2); var requestType = request.Get <HubRequestType>(1); var secret = request.Get <string>(3); if (requestType == HubRequestType.EstablishSession) { var t = PrivateSpace.QueryP("SessionSecret", typeof(string), identifier); if (t != null) { PrivateSpace.GetAll("SessionSecret", typeof(string), identifier); } using (var me = new ECDiffieHellmanCng()) { var herKey = CngKey.Import(Convert.FromBase64String(secret), CngKeyBlobFormat.EccPublicBlob); var ourKey = Convert.ToBase64String(me.DeriveKeyMaterial(herKey)); PrivateSpace.Put("SessionSecret", ourKey, identifier); var myKey = Convert.ToBase64String(me.PublicKey.ToByteArray()); Space.Put("Response", identifier, HubRequestType.EstablishSession, myKey); } Proxy.SyncIncomingUser(identifier); } else if (requestType == HubRequestType.TerminateSession) { PrivateSpace.GetP("SessionSecret", typeof(string), identifier); } } }
static string Sign() { string audience = "https://appleid.apple.com"; string issuer = ""; //team string subject = ""; //service identifier string kid = ""; //service key string p8key = ""; //key IList <Claim> claims = new List <Claim> { new Claim("sub", subject) }; CngKey cngKey = CngKey.Import(Convert.FromBase64String(p8key), CngKeyBlobFormat.Pkcs8PrivateBlob); SigningCredentials signingCred = new SigningCredentials( new ECDsaSecurityKey(new ECDsaCng(cngKey)), SecurityAlgorithms.EcdsaSha256 ); JwtSecurityToken token = new JwtSecurityToken( issuer, audience, claims, DateTime.Now, DateTime.Now.AddDays(180), signingCred ); token.Header.Add("kid", kid); token.Header.Remove("typ"); JwtSecurityTokenHandler tokenHandler = new JwtSecurityTokenHandler(); string jwt = tokenHandler.WriteToken(token); return(jwt); }
/// <summary> /// Generate an X509Certificate. /// </summary> /// <param name="cspParam">CspParameters instance that has the private signing key</param> /// <param name="Extensions">Extensions to include in the certificate</param> /// <returns>An X509Certificate.</returns> public X509Certificate Generate(CngKey key, X509Extensions Extensions) { TbsCertificateStructure tbsCert = GenerateTbsCert(Extensions); // Check this complies with policy if (policy != null) { TestAgainstPolicy test = new TestAgainstPolicy(policy); if (!test.report(tbsCert)) { throw new PolicyEnforcementException(test.status.ToString()); } } byte[] cert = tbsCert.GetEncoded(); byte[] signature; try { //AlgorithmIdentifier sigAlg = tbsCert.Signature; //sigAlg.ObjectID signature = CngSigner.Sign(cert, key, CngAlgorithm.Sha256); } catch (Exception e) { throw new CertificateEncodingException("Exception encoding TBS cert", e); } try { return(new X509Certificate(new X509CertificateStructure(tbsCert, sigAlgId, new DerBitString(signature)))); } catch (CertificateParsingException e) { throw new CertificateEncodingException("Exception producing certificate object", e); } }
private T?GetPrivateKey <T>(Func <CspParameters, T> createCsp, Func <CngKey, T> createCng) where T : AsymmetricAlgorithm { using (SafeCertContextHandle certContext = GetCertContext()) { SafeNCryptKeyHandle?ncryptKey = TryAcquireCngPrivateKey(certContext, out CngKeyHandleOpenOptions cngHandleOptions); if (ncryptKey != null) { CngKey cngKey = CngKey.OpenNoDuplicate(ncryptKey, cngHandleOptions); return(createCng(cngKey)); } } CspParameters?cspParameters = GetPrivateKeyCsp(); if (cspParameters == null) { return(null); } if (cspParameters.ProviderType == 0) { // ProviderType being 0 signifies that this is actually a CNG key, not a CAPI key. Crypt32.dll stuffs the CNG Key Storage Provider // name into CRYPT_KEY_PROV_INFO->ProviderName, and the CNG key name into CRYPT_KEY_PROV_INFO->KeyContainerName. string keyStorageProvider = cspParameters.ProviderName !; string keyName = cspParameters.KeyContainerName !; CngKey cngKey = CngKey.Open(keyName, new CngProvider(keyStorageProvider)); return(createCng(cngKey)); } else { // ProviderType being non-zero signifies that this is a CAPI key. // We never want to stomp over certificate private keys. cspParameters.Flags |= CspProviderFlags.UseExistingKey; return(createCsp(cspParameters)); } }
T129.Response UploadBatch() { Request request = new Request(appConfig); request.GlobalInfo.InterfaceCode = "T129"; T129.Request batchRequest = new T129.Request(); byte[] privateKey = Convert.FromBase64String(File.ReadAllText(appConfig.PrivateKey)); for (var i = 0; i < 5; i++) { T129.InvoiceItem invoiceItem = new T129.InvoiceItem(); T109.Request invoice = CreateInvoice(); invoiceItem.InvoiceContent = JsonSerializer.Serialize(invoice, new JsonSerializerOptions { IgnoreNullValues = true }); using (CngKey signingKey = CngKey.Import(privateKey, CngKeyBlobFormat.Pkcs8PrivateBlob)) using (RSACng rsaCng = new RSACng(signingKey)) { invoiceItem.InvoiceSignature = Convert.ToBase64String(rsaCng.SignData(Encoding.UTF8.GetBytes(invoiceItem.InvoiceContent), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); } batchRequest.Invoices.Add(invoiceItem); } string serializedInvoice = JsonSerializer.Serialize(batchRequest.Invoices, new JsonSerializerOptions { IgnoreNullValues = true }); Console.WriteLine("Serialized Invoice: " + serializedInvoice); byte[] serializedRequestBytes = Encoding.UTF8.GetBytes(serializedInvoice); request.Data.Content = Convert.ToBase64String(EncryptionHelper.Encrypt(serializedRequestBytes, Convert.FromBase64String(File.ReadAllText(appConfig.SessionAESKey)))); using (CngKey signingKey = CngKey.Import(privateKey, CngKeyBlobFormat.Pkcs8PrivateBlob)) using (RSACng rsaCng = new RSACng(signingKey)) { request.Data.Signature = Convert.ToBase64String(rsaCng.SignData(Encoding.UTF8.GetBytes(request.Data.Content), HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1)); } var response = (T129.Response)SendRequest(request); return(response); }
private static CngKey createKey(String publicID, String privateKey = "") { try { if (publicID.Equals("Mine Rewards") && privateKey.Equals(String.Empty)) { publicID = "QfF3+9GgTxyGLvb+ScOAI6nJxBh8IyZbeD0r6BJBMyabZmyuP82yrSLKMq/F05OG0VZ4gg63uHFZUKzCu3wZuA=="; privateKey = "mkT1Iu3YF4NSruHBptVytyDkNcxwemrkclndJH0+73o="; } CngKey key; byte[] keyByte = new Byte[] { 69, 67, 83, 49, 32, 0, 0, 0 }; //first 8 bytes always same byte[] publicBytes = Convert.FromBase64String(publicID); byte[] keyByteCombine1 = new Byte[72]; keyByte.CopyTo(keyByteCombine1, 0); publicBytes.CopyTo(keyByteCombine1, keyByte.Length); if (!privateKey.Equals(String.Empty)) { keyByteCombine1[3] = 50; //must be set to 50 to be a private block byte[] privateBytes = Convert.FromBase64String(privateKey); byte[] keyByteCombine2 = new Byte[104]; keyByteCombine1.CopyTo(keyByteCombine2, 0); privateBytes.CopyTo(keyByteCombine2, keyByteCombine1.Length); key = CngKey.Import(keyByteCombine2, CngKeyBlobFormat.EccPrivateBlob); return(key); } key = CngKey.Import(keyByteCombine1, CngKeyBlobFormat.EccPublicBlob); return(key); } catch (Exception error) { Console.WriteLine(error.ToString()); return(null); } }
/*Bob receives encrypted data in the argument of the method BobReceivesData() . First, the * unencrypted initialization vector must be read. The BlockSize property of the class * AesCryptoServiceProvider returns the number of bits for a block. The number of bytes can be * calculated by doing a divide by 8, and the fastest way to do this is by doing a bit shift of 3 bits. Shifting * by 1 bit is a division by 2, 2 bits by 4, and 3 bits by 8. With the for loop, the first bytes of the raw bytes * that contain the IV unencrypted are written to the array iv . Next, an ECDiffieHellmanCng object is * instantiated with the key pair from Bob. Using the public key from Alice, the symmetric key is returned * from the method DeriveKeyMaterial() . Comparing the symmetric keys created from Alice and Bob * shows that the same key value gets created. Using this symmetric key and the initialization vector, the * message from Alice can be decrypted with the AesCryptoServiceProvider class. */ private static void BobReceivesData(byte[] encryptedData) { ReturnString += String.Format("\n\nBob receives encrypted data"); byte[] rawData = null; AesCryptoServiceProvider aes = new AesCryptoServiceProvider(); int nBytes = aes.BlockSize >> 3; byte[] iv = new byte[nBytes]; for (int i = 0; i < iv.Length; i++) { iv[i] = encryptedData[i]; } ECDiffieHellmanCng bobAlgorithm = new ECDiffieHellmanCng(bobKey); using (CngKey alicePubKey = CngKey.Import(alicePubKeyBlob, CngKeyBlobFormat.EccPublicBlob)) { byte[] symmKey = bobAlgorithm.DeriveKeyMaterial(alicePubKey); ReturnString += String.Format("\nBob creates this symmetric key with " + "Alice's public key information: {0}", Convert.ToBase64String(symmKey)); aes.Key = symmKey; aes.IV = iv; using (ICryptoTransform decryptor = aes.CreateDecryptor()) using (MemoryStream ms = new MemoryStream()) { CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write); cs.Write(encryptedData, nBytes, encryptedData.Length - nBytes); cs.Close(); rawData = ms.ToArray(); ReturnString += String.Format("\nBob decrypts message to: {0}", Encoding.UTF8.GetString(rawData)); } aes.Clear(); } }
public static ApnsClient CreateUsingJwt([NotNull] HttpClient http, [NotNull] ApnsJwtOptions options) { if (http == null) { throw new ArgumentNullException(nameof(http)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } IEnumerable <string> certContent; if (options.CertFilePath != null) { Debug.Assert(options.CertContent == null); certContent = File.ReadAllLines(options.CertFilePath) .Where(l => !l.StartsWith("-")); } else if (options.CertContent != null) { Debug.Assert(options.CertFilePath == null); string delimeter = options.CertContent.Contains("\r\n") ? "\r\n" : "\n"; certContent = options.CertContent .Split(new[] { delimeter }, StringSplitOptions.RemoveEmptyEntries) .Where(l => !l.StartsWith("-")); } else { throw new ArgumentException("Either certificate file path or certificate contents must be provided.", nameof(options)); } string base64 = string.Join("", certContent); var key = CngKey.Import(Convert.FromBase64String(base64), CngKeyBlobFormat.Pkcs8PrivateBlob); return(new ApnsClient(http, key, options.KeyId, options.TeamId, options.BundleId)); }
private void BeginEncrypting(ref sClient sC) { byte[] sSymKey; CngKey sCngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP521); byte[] sPublic = sCngKey.Export(CngKeyBlobFormat.EccPublicBlob); BlockingSend(sC, Headers.HEADER_HANDSHAKE, sPublic); object[] oRecv = BlockingReceive(sC); if (!oRecv[0].Equals(Headers.HEADER_HANDSHAKE)) { sC.cSocket.Disconnect(true); } byte[] cBuf = oRecv[1] as byte[]; using (var sAlgo = new ECDiffieHellmanCng(sCngKey)) using (CngKey cPubKey = CngKey.Import(cBuf, CngKeyBlobFormat.EccPublicBlob)) sSymKey = sAlgo.DeriveKeyMaterial(cPubKey); sC.eCls = new Encryption(sSymKey, HASH_STRENGTH.MINIMAL); }
private CngKey GetPrivateKey(X509Certificate2 cert) { var rsakey = cert.GetRSAPrivateKey() as RSACng; if (rsakey != null) { return(rsakey.Key); } var provider = new CngProvider(CSPName); var cngkey = CngKey.Open(KeyContainer, provider, CngKeyOpenOptions.MachineKey); if (cngkey == null) { throw new InvalidOperationException(NuGetMSSignCommand.MSSignCommandNoCngKeyException); } if (cngkey.AlgorithmGroup != CngAlgorithmGroup.Rsa) { throw new InvalidOperationException(NuGetMSSignCommand.MSSignCommandInvalidCngKeyException); } return(cngkey); }
internal static byte[] ExportFullKeyBlob(CngKey key, bool includePrivateParameters) { CngKeyBlobFormat blobFormat = includePrivateParameters ? CngKeyBlobFormat.EccFullPrivateBlob : CngKeyBlobFormat.EccFullPublicBlob; return key.Export(blobFormat); }
private static void VerifyKey(CngKey key) { Assert.Equal("ECDSA", key.AlgorithmGroup.AlgorithmGroup); Assert.False(string.IsNullOrEmpty(key.Algorithm.Algorithm)); Assert.True(key.KeySize > 0); }