Ejemplo n.º 1
0
        public static void TestNegativeVerify384()
        {
            CngKey key = TestData.s_ECDsa384Key;
            ECDsaCng e = new ECDsaCng(key);

            byte[] tamperedSig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8"
                                + "f366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray();
            bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
            Assert.False(verified);
        }
Ejemplo n.º 2
0
        public static void TestNegativeVerify256()
        {
            CngKey key = TestData.s_ECDsa256Key;
            ECDsaCng e = new ECDsaCng(key);

            byte[] tamperedSig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429"
                                + "e8713dad9a67eb0a5c355e9e23dc").HexToByteArray();
            bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
            Assert.False(verified);
        }
Ejemplo n.º 3
0
        public static void TestCreateByKeySizeNistP256()
        {
            using (ECDsaCng cng = new ECDsaCng(256))
            {
                CngKey key1 = cng.Key;
                Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);

                // The three legacy nist curves are not treated as generic named curves
                Assert.Equal(CngAlgorithm.ECDsaP256, key1.Algorithm);

                Assert.Equal(256, key1.KeySize);
                VerifyKey(key1);
            }
        }
Ejemplo n.º 4
0
        private static ECDsa DecodeECDsaPublicKey(CertificatePal certificatePal)
        {
            ECDsa ecdsa;

            using (SafeBCryptKeyHandle bCryptKeyHandle = ImportPublicKeyInfo(certificatePal.CertContext))
            {
                CngKeyBlobFormat blobFormat;
                byte[]           keyBlob;
#if NETNATIVE
                blobFormat = CngKeyBlobFormat.EccPublicBlob;
                keyBlob    = ExportKeyBlob(bCryptKeyHandle, blobFormat);
                using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
                {
                    ecdsa = new ECDsaCng(cngKey);
                }
#else
                string curveName = GetCurveName(bCryptKeyHandle);

                if (curveName == null)
                {
                    if (HasExplicitParameters(bCryptKeyHandle))
                    {
                        blobFormat = CngKeyBlobFormat.EccFullPublicBlob;
                    }
                    else
                    {
                        blobFormat = CngKeyBlobFormat.EccPublicBlob;
                    }

                    keyBlob = ExportKeyBlob(bCryptKeyHandle, blobFormat);
                    using (CngKey cngKey = CngKey.Import(keyBlob, blobFormat))
                    {
                        ecdsa = new ECDsaCng(cngKey);
                    }
                }
                else
                {
                    blobFormat = CngKeyBlobFormat.EccPublicBlob;
                    keyBlob    = ExportKeyBlob(bCryptKeyHandle, blobFormat);
                    ECParameters ecparams = new ECParameters();
                    ExportNamedCurveParameters(ref ecparams, keyBlob, false);
                    ecparams.Curve = ECCurve.CreateFromFriendlyName(curveName);
                    ecdsa          = new ECDsaCng();
                    ecdsa.ImportParameters(ecparams);
                }
#endif
            }

            return(ecdsa);
        }
Ejemplo n.º 5
0
        /// <exception cref="ArgumentOutOfRangeException">keySize.</exception>
        public MoleECDsaCng(int keySize)
        {
            var eccTemp = new ECDsaCng();

            if (!eccTemp.LegalKeySizes.Any(sizes => keySize <= sizes.MaxSize && keySize >= sizes.MinSize && keySize != sizes.SkipSize))
            {
                throw new ArgumentOutOfRangeException(nameof(keySize))
                      {
                          Source = GetType().AssemblyQualifiedName
                      }
            }
            ;

            EcDsaCng = new ECDsaCng(keySize);
        }
Ejemplo n.º 6
0
        public static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)
        {
            // 验证签名
            bool result = false;

            using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
            {
                using (var signingAlg = new ECDsaCng(key))
                {
                    result = signingAlg.VerifyData(data, signature);
                    signingAlg.Clear();
                }
            }
            return(result);
        }
        public bool Verify()
        {
            using (CngKey privateCngKey = CngKey.Import(PublicKey, CngKeyBlobFormat.EccPublicBlob))
                using (ECDsaCng dsa = new ECDsaCng(privateCngKey))
                {
                    byte[] documentBytes     = Document;
                    byte[] previousSignature = PreviousSignedTransaction.Signature;
                    byte[] hash = documentBytes
                                  .Concat(previousSignature)
                                  .ToArray();

                    dsa.HashAlgorithm = CngAlgorithm.Sha256;
                    return(dsa.VerifyData(hash, Signature) && PreviousSignedTransaction.Verify());
                }
        }
Ejemplo n.º 8
0
 public static (string, string) Encrypt(string message)
 {
     //ECDsaCng ecdsa = new ECDsaCng(): 임의의 키 쌍을 이용하여 초기화
     //ECDsaCng ecdsa = new ECDsaCng(CngKey): 해당 키를 사용하여 초기화
     byte[] keyByte;
     byte[] signature;
     using (ECDsaCng ecdsa = new ECDsaCng()) //키는 랜덤 생성
     {
         //ecdsa.HashAlgorithm = CngAlgorithm.Sha256;
         keyByte = ecdsa.Key.Export(CngKeyBlobFormat.EccPublicBlob); //공개키를 가져옴
         byte[] data = Encoding.UTF8.GetBytes(message);              //메세지를 바이트 배열로 변환
         signature = ecdsa.SignData(data);                           //메시지 서명
     }
     return(Convert.ToBase64String(signature), Convert.ToBase64String(keyByte));
 }
Ejemplo n.º 9
0
 static public bool verify(string msg, byte[] signature, byte[] publicKey)
 {
     try
     {
         using (ECDsaCng algo = new ECDsaCng(CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob)))
         {
             return(algo.VerifyData(Encoding.ASCII.GetBytes(msg), signature, HashAlgorithmName.SHA512));
         }
     }
     catch (System.Security.Cryptography.CryptographicException e)
     {
         System.Console.WriteLine("Cryptographic exception catched: " + e.Message);
         return(false);
     }
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Is the signed hash belong to the hash and public key
        /// </summary>
        /// <param name="hash">transfer info hash</param>
        /// <param name="publicKey">public key</param>
        /// <returns>true if the signed hash belong to the hash and public key</returns>
        public bool IsValidSignedHash(byte[] hash, byte[] publicKey)
        {
            bool ret;

            using (var dsa = new ECDsaCng(CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob)))
            {
                dsa.HashAlgorithm = Global.HashAlgorithm;

                //// verifying hashed message
                ////bReturn = dsa.VerifyHash(dataHash, SignedMsg);
                ret = dsa.VerifyHash(hash, this.sgndData);
            }

            return(ret);
        }
        //验证签名
        private static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)
        {
            bool retValue = false;

            //使用 CngKey.Import 导入CngKey对象,的到公钥
            using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
                //将公钥传入ECDsaCng得到解密签名算法
                using (var signinAlg = new ECDsaCng(key))
                {
                    //然后使用signinAlg.VerifyData来验证签名
                    retValue = signinAlg.VerifyData(data, signature, HashAlgorithmName.SHA512);
                    signinAlg.Clear();
                }
            return(retValue);
        }
Ejemplo n.º 12
0
        public override byte[] SignData(byte[] buffer, HashAlgorithm hashAlgorithm, CertificatePrivateKey privateKey)
        {
            if (!(privateKey.Algorithm is ECDsaCng))
            {
                throw new Exception("ECDSA signature requires ECDSA private key");
            }

            ECDsaCng ecdsaKey = (ECDsaCng)privateKey.Algorithm;

            ecdsaKey.HashAlgorithm = GetCngAlgorithm(hashAlgorithm);

            byte[] signature = ecdsaKey.SignData(buffer);
            signature = DEREncodeSignature(signature);
            return(signature);
        }
Ejemplo n.º 13
0
        /// <summary>Constructor</summary>
        /// <param name="eaa">EnumDigitalSignAlgorithm</param>
        public DigitalSignECDsaCng(EnumDigitalSignAlgorithm eaa)
        {
            AsymmetricAlgorithm aa = null;
            HashAlgorithm       ha = null;

            AsymmetricAlgorithmCmnFunc.CreateDigitalSignSP(eaa, out aa, out ha);

            ECDsaCng ecdsa = (ECDsaCng)aa;

            this._privateKey = ecdsa.Key;
            this._publicKey  = this._privateKey.Export(CngKeyBlobFormat.EccPublicBlob);

            this.AsymmetricAlgorithm = aa;
            this.HashAlgorithm       = ha;
        }
Ejemplo n.º 14
0
        public static String CreateSignature(String publicID, String privateKey, String datahash) //need to have checks that publicID and privatekey are correct before using this method
        {
            CngKey key = createKey(publicID, privateKey);

            if (key == null)
            {
                return("null");
            }
            Byte[] datahashByte = Convert.FromBase64String(datahash);

            ECDsaCng dsa = new ECDsaCng(key);

            Byte[] byteSig = dsa.SignData(datahashByte);
            return(Convert.ToBase64String(byteSig));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Used to create a CngKey that can be used to verify JWT content.
        /// </summary>
        /// <param name="clientPubKeyString"></param>
        /// <returns></returns>
        public static CngKey ImportECDsaCngKeyFromString(string clientPubKeyString)
        {
            byte[] clientPublicKeyBlob = Base64Url.Decode(clientPubKeyString);
            byte[] key = clientPublicKeyBlob.Skip(23).ToArray();

            var keyType   = new byte[] { 0x45, 0x43, 0x53, 0x33 };
            var keyLength = new byte[] { 0x30, 0x00, 0x00, 0x00 };

            var keyImport = keyType.Concat(keyLength).Concat(key.Skip(1)).ToArray();

            var cngKey = CngKey.Import(keyImport, CngKeyBlobFormat.EccPublicBlob);
            var crypto = new ECDsaCng(cngKey);

            return(crypto.Key);
        }
Ejemplo n.º 16
0
        private string Verify(string path)
        {
            using (ECDsaCng ecdsa = new ECDsaCng(publicKey))
            {
                using (var file = MemoryMappedFile.CreateFromFile(path))
                {
                    if (!ecdsa.VerifyData(file.CreateViewStream(), signature, HashAlgorithmName.SHA256))
                    {
                        throw new Exception("File failed to verify.");
                    }
                }
            }

            return(path);
        }
        static string GenerateClientSecretJWT(DateTimeOffset requestTime, string keyId, string teamId, string p8FileContents)
        {
            var headers = new Dictionary <string, object>
            {
                //{ "alg", "ES256" },
                { "kid", keyId }
            };

            var payload = new Dictionary <string, object>
            {
                { "iss", teamId },
                { "iat", requestTime.ToUnixTimeSeconds() }
            };
            var cngKey = CngKey.Import(Convert.FromBase64String(p8FileContents), CngKeyBlobFormat.Pkcs8PrivateBlob);

            return(Jose.JWT.Encode(payload, cngKey, Jose.JwsAlgorithm.ES256, headers));


            var secretKey = CleanP8Key(p8FileContents);

            // Get our headers/payloads into a json string
            var headerStr  = "{" + string.Join(",", headers.Select(kvp => $"\"{kvp.Key}\":\"{kvp.Value.ToString()}\"")) + "}";
            var payloadStr = "{";

            foreach (var kvp in payload)
            {
                if (kvp.Value is int || kvp.Value is long || kvp.Value is double)
                {
                    payloadStr += $"\"{kvp.Key}\":{kvp.Value.ToString()},";
                }
                else
                {
                    payloadStr += $"\"{kvp.Key}\":\"{kvp.Value.ToString()}\",";
                }
            }
            payloadStr = payloadStr.TrimEnd(',') + "}";

            // Load the key text
            var key = CngKey.Import(Convert.FromBase64String(secretKey), CngKeyBlobFormat.Pkcs8PrivateBlob);

            using (var dsa = new ECDsaCng(key))
            {
                var jwtHeader  = Base64UrlEncode(Encoding.UTF8.GetBytes(headerStr));
                var jwtPayload = Base64UrlEncode(Encoding.UTF8.GetBytes(payloadStr));
                var signature  = dsa.SignData(Encoding.UTF8.GetBytes($"{jwtHeader}.{jwtPayload}"), HashAlgorithmName.SHA256);
                return($"{jwtHeader}.{jwtPayload}.{Base64UrlEncode(signature)}");
            }
        }
Ejemplo n.º 18
0
        public byte[] Sign(byte[] data)
        {
            /* Import the signing key */
            CngKey signingKey = CngKey.Import(this.signingKeyData.ToArray(), CngKeyBlobFormat.EccPrivateBlob);

            ECDsaCng dsa = new ECDsaCng(signingKey); //dsa = Digital Signature Algorithm

            /* Get the signature of the data using the imported key */
            byte[] signature = dsa.SignData(data);

            // Verify for test purposes
            // bool verified = veriftSignature(data, signature);

            /* Return the signature */
            return(signature);
        }
Ejemplo n.º 19
0
    public static void Main(string[] args)
    {
        // The JSON document to be signed
        Dictionary <String, Object> document = new Dictionary <String, Object>();

        document["now"]         = "2015-01-17T10:20:03Z";
        document["intProperty"] = 612;

        // Use a P-521 ECDSA key for signing
        using (ECDsaCng ecKey = new ECDsaCng(521))
        {
            string json = createJcs(ecKey, document);
            Console.WriteLine("Signed JSON Document:\n" + json);
            Console.WriteLine("\nVerified=" + validateJcs(new JavaScriptSerializer().Deserialize <Dictionary <String, Object> >(json)));
        }
    }
Ejemplo n.º 20
0
        private string CreateJwtToken()
        {
            var header  = JsonHelper.Serialize(new { alg = "ES256", kid = p8privateKeyId });          //The encryption algorithm (alg), A 10-character key identifier (kid) key
            var payload = JsonHelper.Serialize(new { iss = teamId, iat = ToEpoch(DateTime.UtcNow) }); //The issuer(iss) registered claim key, whose value is your 10 - character Team ID, The issued at (iat) registered claim key
            var key     = CngKey.Import(Convert.FromBase64String(p8privateKey), CngKeyBlobFormat.Pkcs8PrivateBlob);

            using (var dsa = new ECDsaCng(key))
            {
                dsa.HashAlgorithm = CngAlgorithm.Sha256;
                var headerBase64    = Convert.ToBase64String(Encoding.UTF8.GetBytes(header));
                var payloadBase64   = Convert.ToBase64String(Encoding.UTF8.GetBytes(payload));
                var unsignedJwtData = $"{headerBase64}.{payloadBase64}";
                var signature       = dsa.SignData(Encoding.UTF8.GetBytes(unsignedJwtData));
                return($"{unsignedJwtData}.{Convert.ToBase64String(signature)}");
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Verifies that a digital signature is valid by determining the hash value
 /// in the signature using the provided public key and comparing it to the hash
 /// value of the provided data.
 /// </summary>
 /// <param name="data">The data that was signed.</param>
 /// <param name="signature">The signature data to be verified.</param>
 /// <param name="key">Cryptography Next Generation (CNG) objects key.</param>
 /// <returns>True if the signature is valid; otherwise, false.</returns>
 public bool VerifyData(Stream data, byte[] signature, CngKey key)
 {
     // Create an ECDSA.
     using (ECDsaCng dsa = new ECDsaCng(key))
     {
         // Verify the data.
         if (dsa.VerifyData(data, signature))
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
 }
Ejemplo n.º 22
0
        public JsonWebKeySignBuilder SetAlg(ECDsaCng ec, string algName)
        {
            _jsonWebKey.Alg = algName;
            _jsonWebKey.Kty = KeyTypes.EC;
            foreach (var kvp in ec.ExtractPublicKey())
            {
                _jsonWebKey.Content.Add(kvp.Key, kvp.Value);
            }

            foreach (var kvp in ec.ExtractPrivateKey())
            {
                _jsonWebKey.Content.Add(kvp.Key, kvp.Value);
            }

            return(this);
        }
Ejemplo n.º 23
0
        private ECDsaCng CreateCng()
        {
            var cng = new ECDsaCng(this.key);

            // .NET Core 2.1 / UAP has a bug where it throws NullReferenceException from SignHash because it didn't set this property.
            if (cng.HashAlgorithm is null)
            {
                if (CngAsymmetricKeyAlgorithmProvider.GetHashCngAlgorithm(this.algorithm) is { } algorithm)
                {
                    cng.HashAlgorithm = algorithm;
                }
                else
                {
                    throw new NotSupportedException("Hash algorithm " + this.algorithm + " could not be obtained.");
                }
            }
Ejemplo n.º 24
0
        public bool VerifySignature(string password, byte[] signature, byte[] salt)
        {
            bool retValue = false;

            using (CngKey key = CngKey.Import(salt, CngKeyBlobFormat.GenericPublicBlob))
                using (var signingAlg = new ECDsaCng(key))
                {
                    //#if NET46
                    retValue = signingAlg.VerifyData(Encoding.UTF8.GetBytes(password), signature);
                    signingAlg.Clear();
                    //#else
                    //    retValue = signingAlg.VerifyData(data, signature, HashAlgorithmName.SHA512);
                    //#endif
                }
            return(retValue);
        }
Ejemplo n.º 25
0
    public static void Main(string[] args)
    {
        Bob bob = new Bob();

        using (ECDsaCng dsa = new ECDsaCng())
        {
            dsa.HashAlgorithm = CngAlgorithm.Sha256;
            bob.key           = dsa.Key.Export(CngKeyBlobFormat.EccPublicBlob);

            byte[] data = new byte[] { 21, 5, 8, 12, 207 };

            byte[] signature = dsa.SignData(data);

            bob.Receive(data, signature);
        }
    }
        public void CompliantConstructors()
        {
            var ec1 = new ECDiffieHellmanCng(); // Compliant - default EC key size is 521
            var ec2 = new ECDsaCng();           // Compliant - default EC key size is 521
            var ec3 = new ECDsaOpenSsl();       // Compliant - default EC key size is 521

            // Valid key sizes are 256, 384, and 521 bits.
            var ec4 = new ECDiffieHellmanCng(256);
            var ec5 = new ECDsaCng(384);
            var ec6 = new ECDsaOpenSsl(521);
            var ec7 = new ECDsaOpenSsl((IntPtr)128);

            var ec8  = new ECDiffieHellmanCng(ECCurve.NamedCurves.brainpoolP384r1);
            var ec9  = new ECDsaCng(ECCurve.NamedCurves.brainpoolP384t1);
            var ec10 = new ECDsaOpenSsl(ECCurve.NamedCurves.brainpoolP512r1);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// 创建签名
        /// </summary>
        /// <param name="data"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        private byte[] CreateSignature(byte[] data, CngKey key)
        {
            byte[] signature;
            //使用ECDsaCng创建签名,ECDsaCng的构造函数接收包含公钥和私钥的CngKey类对象
            using (ECDsaCng signingAlg = new ECDsaCng(key))
            {
#if NET46
                signature = signingAlg.SignData(data);
                signingAlg.Clear();
#else
                //对数据进行签名(加密)
                signature = signingAlg.SignData(data, HashAlgorithmName.SHA512);
#endif
            }
            return(signature);
        }
        /// <summary>
        /// 要验证签名是否真的来自于Alice,Bob使用Alice的公钥检查签名。包含公钥blob的字节数组可以用静态方法Import()导入CngKey对象。
        /// 然后使用ECDsaCng类,调用VerifyData()方法来验证签名。
        /// </summary>
        /// <param name="aliceData"></param>
        /// <param name="aliceSignature"></param>
        /// <param name="_alicePublicKeyBob"></param>
        /// <returns></returns>
        private static bool VerifySignature(byte[] data, byte[] signature, byte[] pubKey)
        {
            bool retValue = false;

            using (CngKey key = CngKey.Import(pubKey, CngKeyBlobFormat.GenericPublicBlob))
                using (var signingAlg = new ECDsaCng(key))
                {
#if NET46
                    retValue = signingAlg.VerifyData(data, signature);
                    signingAlg.Clear();
#else
                    retValue = signingAlg.VerifyData(data, signature, HashAlgorithmName.SHA512);
#endif
                }
            return(retValue);
        }
Ejemplo n.º 29
0
        public static void TestCreateKeyFromCngAlgorithmNistP256()
        {
            CngAlgorithm alg = CngAlgorithm.ECDsaP256;

            using (CngKey key = CngKey.Create(alg))
            {
                VerifyKey(key);
                using (ECDsaCng e = new ECDsaCng(key))
                {
                    Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup);
                    Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm);
                    VerifyKey(e.Key);
                    e.Exercise();
                }
            }
        }
        public void CompliantGenerateKey()
        {
            var ec1 = new ECDiffieHellmanCng();

            ec1.GenerateKey(ECCurve.NamedCurves.brainpoolP224r1);
            ec1.GenerateKey(ECCurve.NamedCurves.nistP256);

            var ec2 = new ECDsaCng();

            ec2.GenerateKey(ECCurve.NamedCurves.brainpoolP256r1);
            ec2.GenerateKey(ECCurve.NamedCurves.nistP384);

            var ec3 = new ECDsaOpenSsl();

            ec3.GenerateKey(ECCurve.NamedCurves.brainpoolP384t1);
            ec3.GenerateKey(ECCurve.NamedCurves.nistP521);
        }
        public void CompliantKeySizeSet()
        {
            var ec1 = new ECDiffieHellmanCng();

            ec1.KeySize = 512;
            ec1.KeySize = 128; // OK - because this is not a valid key size for this object

            var ec2 = new ECDsaCng();

            ec2.KeySize = 512;
            ec2.KeySize = 64; // OK - because this is not a valid key size for this object

            var ec3 = new ECDsaOpenSsl();

            ec3.KeySize = 512;
            ec3.KeySize = 12; // OK - because this is not a valid key size for this object
        }
Ejemplo n.º 32
0
        internal static bool ValidateBareCertificateWithBcrypt(X509Certificate2 certificate)
        {
            var deviceInfo = ExtensionDecoder.Decode(certificate);

            // check we have a good extension
            if (deviceInfo == null)
            {
                Helpers.Notify("Certificate does not have well-formed RIoT extension", true);
                return(false);
            }
            var devIdPubKeyDEREncoded = deviceInfo.EncodedDeviceIDKey;

            if (devIdPubKeyDEREncoded.Length != 65)
            {
                Helpers.Notify("Public key in extension has incorrect length", true);
                return(false);
            }

            // We need to convert to the Windows key format before we can import
            // #define BCRYPT_ECDSA_PUBLIC_P256_MAGIC  0x31534345  // ECS1
            // https://msdn.microsoft.com/en-us/library/windows/desktop/aa375520(v=vs.85).aspx
            byte[] windowsEncodedKey = new byte[32 * 2 + 4 + 4];
            // todo - endianess
            byte[] magic = BitConverter.GetBytes((uint)0x31534345);
            byte[] len   = BitConverter.GetBytes((uint)32);

            Array.Copy(magic, 0, windowsEncodedKey, 0, 4);
            Array.Copy(len, 0, windowsEncodedKey, 4, 4);
            Array.Copy(devIdPubKeyDEREncoded, 1, windowsEncodedKey, 8, 32);
            Array.Copy(devIdPubKeyDEREncoded, 32 + 1, windowsEncodedKey, 8 + 32, 32);

            var devIdPubKey = CngKey.Import(windowsEncodedKey, CngKeyBlobFormat.EccPublicBlob);

            ECDsaCng verifier = new ECDsaCng(devIdPubKey);

            ECDsaCng testSigner = new ECDsaCng(256);
            var      sig        = testSigner.SignData(new byte[] { 1, 2, 3, 4 });
            bool     okx        = testSigner.VerifyData(new byte[] { 1, 2, 3, 4 }, sig);

            var  bits    = ExtensionDecoder.Decompose(certificate);
            var  tbsHash = Helpers.HashData(bits.Tbs, 0, bits.Tbs.Length);
            bool ok      = verifier.VerifyHash(tbsHash, bits.Signature);


            return(true);
        }
Ejemplo n.º 33
0
        public static void TestHashRoundTrip(CurveDef curveDef)
        {
            // This test is in the cng only tests because OpenSsl does not provide the hash algorithm
            using (var cng = new ECDsaCng(curveDef.Curve))
            {
                ECParameters param = cng.ExportExplicitParameters(false);

                // Add some dummy values and import
                Assert.True(param.Curve.IsExplicit);
                var curve = param.Curve;
                curve.Hash = HashAlgorithmName.SHA1;
                curve.Seed = new byte[1] { 0xFF }; // Hash should have a seed
                param.Curve = curve;
                cng.ImportParameters(param);

                // Export to see if the hash is there
                ECParameters param2 = cng.ExportExplicitParameters(false);
                Assert.Equal(HashAlgorithmName.SHA1.Name.ToUpper(), param2.Curve.Hash.Value.Name.ToUpper());
                Assert.Equal(0xFF, param2.Curve.Seed[0]);
            }
        }
Ejemplo n.º 34
0
        public static void TestKeyPropertyFromNamedCurve(CurveDef curveDef)
        {
            ECDsaCng e = new ECDsaCng(curveDef.Curve);
            CngKey key1 = e.Key;
            VerifyKey(key1);
            e.Exercise();

            CngKey key2 = e.Key;
            Assert.Same(key1, key2);
        }
Ejemplo n.º 35
0
        public static void TestCreateKeyFromCngAlgorithmNistP256()
        {
            CngAlgorithm alg = CngAlgorithm.ECDsaP256;

            using (CngKey key = CngKey.Create(alg))
            {
                VerifyKey(key);
                using (ECDsaCng e = new ECDsaCng(key))
                {
                    Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup);
                    Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm);
                    VerifyKey(e.Key);
                    e.Exercise();
                }
            }
        }
Ejemplo n.º 36
0
 public static void TestPositive256WithBlob()
 {
     CngKey key = TestData.s_ECDsa256Key;
     ECDsaCng e = new ECDsaCng(key);
     Verify256(e, true);
 }
Ejemplo n.º 37
0
        public static void TestCreateByNameNistP521()
        {
            using (ECDsaCng cng = new ECDsaCng(ECCurve.NamedCurves.nistP521))
            {
                CngKey key1 = cng.Key;
                Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup);

                // The three legacy nist curves are not treated as generic named curves
                Assert.Equal(CngAlgorithm.ECDsaP521, key1.Algorithm);

                Assert.Equal(521, key1.KeySize);
                VerifyKey(key1);
            }
        }
Ejemplo n.º 38
0
        public static void TestVerify521_EcdhKey()
        {
            byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone();

            // Rewrite the dwMagic value to be ECDH
            // ECDSA prefix: 45 43 53 36
            // ECDH prefix : 45 43 4b 36
            keyBlob[2] = 0x4b;

            using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob))
            {
                // Preconditions:
                Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup);
                Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm);

                using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key))
                using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521))
                {
                    byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512);
                    byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512);

                    Assert.True(
                        ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512),
                        "ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)");

                    Assert.True(
                        ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512),
                        "ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)");
                }
            }
        }
Ejemplo n.º 39
-1
        public static void TestNegativeVerify521()
        {
            CngKey key = TestData.s_ECDsa521Key;
            ECDsaCng e = new ECDsaCng(key);

            byte[] tamperedSig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845"
                                + "a6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7"
                                + "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray();
            bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig);
            Assert.False(verified);
        }