private 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;
        }
示例#2
0
 static void Main(string[] args)
 {
     if (args.Length == 1)
     {
         // Got Signature (License)? Then Verify it
         byte[] signature = Convert.FromBase64String(args[0]);
         // Public key must be hard-coded!
         const string publicKeyString = "RUNTMSAAAACOUGMbADUgo3dDq42gwv+uCPsI8jjQm61r0CUPVioibLfzskpsGmUAJD29rt3FzS5qb28gS5Ed85jDPwQoesBJ";
         byte[] publicKey = Convert.FromBase64String(publicKeyString);
         CngKey cngKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob);
         ECDsaCng dsa = new ECDsaCng(cngKey);
         dsa.HashAlgorithm = CngAlgorithm.MD5;
         if (dsa.VerifyData(MachineID.ComputeEasyMachineID(), signature))
         {
             Console.WriteLine("License is valid. Thank you!");
         }
         else
         {
             Console.WriteLine("License is invalid!");
         }
         dsa.Clear();
     }
     else
     {
         // No Signature (License). Display InstallationID
         Console.WriteLine("No license found. Contact your software vendor and provide the following code:");
         foreach (byte b in MachineID.ComputeEasyMachineID())
         {
             Console.Write(b);
         }
     }
     Console.WriteLine("Press any key to continue ...");
     Console.ReadKey();
 }
示例#3
0
 public void Receive(byte[] data, byte[] signature)
 {
     using (ECDsaCng ecsdKey = new ECDsaCng(CngKey.Import(key, CngKeyBlobFormat.EccPublicBlob)))
     {
         if (ecsdKey.VerifyData(data, signature))
             Console.WriteLine("Data is good");
         else
             Console.WriteLine("Data is bad");
     }
 }
示例#4
0
        private Boolean isValidSignedMsg(byte[] hash)
        {
            Boolean bReturn;

            using (var dsa = new ECDsaCng(CngKey.Import(PublicKey, CngKeyBlobFormat.EccPublicBlob)))
            {
                dsa.HashAlgorithm = Global.HashAlgorithm;
                bReturn = dsa.VerifyData(hash, SignedMsg);
            }

            return bReturn;
        }
示例#5
0
 public bool Check(string source)
 {
     using (ECDsaCng ecsdKey = new ECDsaCng(CngKey.Import(key, CngKeyBlobFormat.EccPublicBlob)))
     {
         byte[] destData = new byte[source.Length / 2];
         for(int i = 0; i < source.Length / 2; ++i)
         {
             destData[i] = Convert.ToByte(source.Substring(i * 2, 2), 16);
         }
         return ecsdKey.VerifyData(TestDataBytes, destData);
     }
 }
示例#6
0
        internal void ExtractValues(string appParam, byte[] originalChallenge)
        {
            DataContractJsonSerializer jsonSerializerResponse = new DataContractJsonSerializer(typeof(ClientData));
            object objResponse = jsonSerializerResponse.ReadObject(new MemoryStream(Helpers.Base64UrlDecode(clientData)));
            ClientData clientDataObject = objResponse as ClientData;

            if (clientDataObject == null
                || !clientDataObject.origin.Equals(appParam)
                || !clientDataObject.typ.Equals("navigator.id.finishEnrollment")
                || !clientDataObject.challenge.Equals(Helpers.Base64UrlEncode(originalChallenge))
                )
                throw new Exception("clientData does not contain necessary fields");

            byte[] data = Helpers.Base64UrlDecode(registrationData);
            if (data[0] != 0x05)
                throw new Exception("Invalid registration data");

            var keyLen = 65;
            byte[] keyBytes = new byte[keyLen];
            Array.Copy(data, 1, keyBytes, 0, keyLen);
            publicKey = Helpers.Base64UrlEncode(keyBytes);

            int keyHandleLen = data[66];
            byte[] keyHandleBytes = new byte[keyHandleLen];
            Array.Copy(data, 1 + 1 + keyLen, keyHandleBytes, 0, keyHandleLen);
            keyHandle = Helpers.Base64UrlEncode(keyHandleBytes);

            int certLen = data.Length - 1 - 1 - keyLen - keyHandleLen; // temporary!
            byte[] certBytes = new byte[certLen];
            Array.Copy(data, 1 + 1 + keyLen + keyHandleLen, certBytes, 0, certLen);
            X509Certificate certObject = new X509Certificate(certBytes);
            certBytes = certObject.Export(X509ContentType.Cert);
            certLen = certBytes.Length;

            int sigLen = data.Length - 1 - 1 - keyLen - keyHandleLen - certLen;
            byte[] signatureBytes = new byte[sigLen];
            Array.Copy(data, data.Length - sigLen, signatureBytes, 0, sigLen);

            var bytesToVerify = new byte[] { 0x00 }
                .Concat(SHA256.Create().ComputeHash(new UTF8Encoding().GetBytes(appParam)))
                .Concat(SHA256.Create().ComputeHash(Helpers.Base64UrlDecode(clientData)))
                .Concat(keyHandleBytes)
                .Concat(keyBytes)
                .ToArray();

            var ecdsa = new ECDsaCng(CngKey.Import(FixKeyBytes(certObject.GetPublicKey()), CngKeyBlobFormat.EccPublicBlob))
            {
                HashAlgorithm = CngAlgorithm.Sha256
            };
            if (!ecdsa.VerifyData(bytesToVerify, FixSignatureBytes(signatureBytes)))
                throw new Exception("Signature is not valid");
        }
示例#7
0
        /// <summary>
        /// Weryfikacja na podstawie klucza publicznego, podpisu i podpisanych danych
        /// </summary>
        /// <param name="publicKey"></param>
        /// <param name="signature"></param>
        /// <param name="data"></param>
        /// <returns></returns>
 
        public static bool verifyData(byte[] publicKey, byte[] signature, byte[] data)
        {
            try
            {
                ECDsaCng ECDSA = new ECDsaCng(CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob));
                ECDSA.HashAlgorithm = CngAlgorithm.Sha256;
                return ECDSA.VerifyData(data, signature);
            }
            catch(Exception)
            {
                return false;
            }
        }
示例#8
0
        public static bool Verify(string publicKey, string message, string signature)
        {
            bool isValid = false;

            using (CngKey k = CngKey.Import(Convert.FromBase64String(publicKey), CngKeyBlobFormat.EccPublicBlob))
            using (ECDsaCng dsa = new ECDsaCng(k))
            {
                byte[] sigData = Convert.FromBase64String(signature);
                isValid = dsa.VerifyData(Encoding.Unicode.GetBytes(message), sigData);
            }

            return isValid;
        }
示例#9
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;
 }
 /// <summary>
 /// 使用公钥验证签名
 /// </summary>
 public static bool VerifyData(byte[] data, byte[] signature, byte[] publicKey)
 {
     //验证是否签名匹配
     bool verified = false;
     // 导入公钥
     using (CngKey cngKey = CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob))
     {
         // 验证签名
         using (ECDsaCng ecdsa = new ECDsaCng(cngKey))
         {
             verified = ecdsa.VerifyData(data, signature);
             return verified;
         }
     }
 }
示例#11
0
        public bool Verify(byte[] signature, byte[] securedInput, object key)
        {
            var publicKey = Ensure.Type<CngKey>(key, "EcdsaUsingSha alg expects key to be of CngKey type.");

            Ensure.BitSize(publicKey.KeySize, keySize, string.Format("ECDSA algorithm expected key of size {0} bits, but was given {1} bits", keySize, publicKey.KeySize));

            try
            {
                using (var signer = new ECDsaCng(publicKey))
                {
                #if NET40
                    signer.HashAlgorithm = Hash;

                    return signer.VerifyData(securedInput, signature);
                #elif NETSTANDARD1_4
                    return signer.VerifyData(securedInput, signature, Hash);
                #endif
                }
            }
            catch (CryptographicException e)
            {
                return false;
            }
        }
示例#12
0
        private Boolean isValidSignedMsg(Object obj)
        {
            Boolean bReturn;

            var bObj = Global.ConvertObjetToArrayByte(obj);

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

                // verifying hashed message
                //bReturn = dsa.VerifyHash(dataHash, SignedMsg);
                bReturn = dsa.VerifyData(bObj, SignedMsg);
            }

            return bReturn;
        }
示例#13
0
 public static bool Verify(byte[] publicKey, byte[] signature, Stream stream)
 {
     #if Mono
     throw new NotSupportedException();
     #else
     try
     {
         using (ECDsaCng ecdsa = new ECDsaCng())
         {
             ecdsa.FromXmlString(Encoding.ASCII.GetString(publicKey), ECKeyXmlFormat.Rfc4050);
             ecdsa.HashAlgorithm = CngAlgorithm.Sha256;
             return ecdsa.VerifyData(stream, signature);
         }
     }
     catch (Exception)
     {
         return false;
     }
     #endif
 }
示例#14
0
        public bool Verify(MtbContainer mtb)
        {
            var header = mtb.IssuerSignedTicketBundle.Header;
            var signingInput = CreateCoseSigningInput(mtb.IssuerSignedTicketBundle.Header.GetBytes(), mtb.IssuerSignedTicketBundle.TicketBundle.GetBytes());
            var signature = mtb.IssuerSignedTicketBundle.Signature;
            var publicKey = _keyRepository.GetPublicKey(header.alg, header.iid, header.kid);

            if (publicKey != null)
            {
                if (signature.Length > 64)
                {
                    signature = SignatureConverter.FromDerEncoded(signature);
                }

                using (var dsa = new ECDsaCng(publicKey))
                {
                    return dsa.VerifyData(signingInput, signature);
                }
            }

            return false;
        }
示例#15
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)");
                }
            }
        }
        public async Task ECAsymmetricSigningAndEncryption()
        {
            var bob = new ECDsaCng(521);
            var bobPublic = CngKey.Import(bob.Key.Export(CngKeyBlobFormat.EccPublicBlob), CngKeyBlobFormat.EccPublicBlob);
            var alice = new ECDsaCng(521);
            var alicePublic = CngKey.Import(alice.Key.Export(CngKeyBlobFormat.EccPublicBlob), CngKeyBlobFormat.EccPublicBlob);

            // Bob formulates request.
            var bobRequest = new MemoryStream();
            var bobDH = ECDiffieHellman.Create();
            {
                byte[] bobPublicDH = bobDH.PublicKey.ToByteArray();
                byte[] bobSignedDH = bob.SignData(bobPublicDH);
                await bobRequest.WriteSizeAndBufferAsync(bobPublicDH, CancellationToken.None);
                await bobRequest.WriteSizeAndBufferAsync(bobSignedDH, CancellationToken.None);
                bobRequest.Position = 0;
            }

            // Alice reads request.
            var aliceResponse = new MemoryStream();
            byte[] aliceKeyMaterial;
            var aliceDH = new ECDiffieHellmanCng();
            {
                byte[] bobPublicDH = await bobRequest.ReadSizeAndBufferAsync(CancellationToken.None);
                byte[] bobSignedDH = await bobRequest.ReadSizeAndBufferAsync(CancellationToken.None);
                var bobDsa = new ECDsaCng(bobPublic);
                Assert.IsTrue(bobDsa.VerifyData(bobPublicDH, bobSignedDH));
                var bobDHPK = ECDiffieHellmanCngPublicKey.FromByteArray(bobPublicDH, CngKeyBlobFormat.EccPublicBlob);
                aliceKeyMaterial = aliceDH.DeriveKeyMaterial(bobDHPK);

                await aliceResponse.WriteSizeAndBufferAsync(aliceDH.PublicKey.ToByteArray(), CancellationToken.None);
                await aliceResponse.WriteSizeAndBufferAsync(alice.SignData(aliceDH.PublicKey.ToByteArray()), CancellationToken.None);

                // Alice also adds a secret message.
                using (var aes = SymmetricAlgorithm.Create())
                {
                    using (var encryptor = aes.CreateEncryptor(aliceKeyMaterial, new byte[aes.BlockSize / 8]))
                    {
                        var cipherText = new MemoryStream();
                        using (var cryptoStream = new CryptoStream(cipherText, encryptor, CryptoStreamMode.Write))
                        {
                            cryptoStream.Write(new byte[] { 0x1, 0x3, 0x2 }, 0, 3);
                            cryptoStream.FlushFinalBlock();
                            cipherText.Position = 0;
                            await aliceResponse.WriteSizeAndStreamAsync(cipherText, CancellationToken.None);
                        }
                    }
                }

                aliceResponse.Position = 0;
            }

            // Bob reads response
            byte[] bobKeyMaterial;
            {
                byte[] alicePublicDH = await aliceResponse.ReadSizeAndBufferAsync(CancellationToken.None);
                byte[] aliceSignedDH = await aliceResponse.ReadSizeAndBufferAsync(CancellationToken.None);
                var aliceDsa = new ECDsaCng(alicePublic);
                Assert.IsTrue(aliceDsa.VerifyData(alicePublicDH, aliceSignedDH));
                var aliceDHPK = ECDiffieHellmanCngPublicKey.FromByteArray(alicePublicDH, CngKeyBlobFormat.EccPublicBlob);
                bobKeyMaterial = bobDH.DeriveKeyMaterial(aliceDHPK);

                // And Bob reads Alice's secret message.
                using (var aes = SymmetricAlgorithm.Create())
                {
                    using (var decryptor = aes.CreateDecryptor(aliceKeyMaterial, new byte[aes.BlockSize / 8]))
                    {
                        var plaintext = new MemoryStream();
                        var substream = await aliceResponse.ReadSizeAndStreamAsync(CancellationToken.None);
                        using (var cryptoStream = new CryptoStream(substream, decryptor, CryptoStreamMode.Read))
                        {
                            await cryptoStream.CopyToAsync(plaintext);
                            plaintext.Position = 0;
                            byte[] secretMessage = new byte[1024];
                            int readBytes = plaintext.Read(secretMessage, 0, secretMessage.Length);
                        }
                    }
                }
            }

            CollectionAssert.AreEqual(aliceKeyMaterial, bobKeyMaterial);
        }
示例#17
0
    public static bool validateJcs(Dictionary<String,Object> document)
    {
        Dictionary<String,Object> signature = (Dictionary<String,Object>)document[SIGNATURE_JSON];
        Dictionary<String,Object> signatureClone = new Dictionary<String,Object>(signature);
        Dictionary<String,Object> publicKey = (Dictionary<String,Object>)signature[PUBLIC_KEY_JSON];
        if (!signature[ALGORITHM_JSON].Equals(ES256_ALG))
        {
            throw new ArgumentException("\"" + ES256_ALG + "\" expected");
        }
        if (!publicKey[TYPE_JSON].Equals(EC_PUBLIC_KEY))
        {
            throw new ArgumentException("\"" + EC_PUBLIC_KEY + "\" expected");
        }
        if (!publicKey[CURVE_JSON].Equals(P_521_CRV))
        {
            throw new ArgumentException("\"" + P_521_CRV + "\" expected");
        }
        byte[] rawKey = new byte[140]; rawKey[0] = 69; rawKey[1] = 67; rawKey[2] = 83; rawKey[3] = 53; rawKey[4] = 66;
        Buffer.BlockCopy(base64urldecode((string)publicKey[X_JSON]), 0, rawKey, 8, 66);
        Buffer.BlockCopy(base64urldecode((string)publicKey[Y_JSON]), 0, rawKey, 74, 66);

        // Normalization: Remove signature/value from the document
        signature.Remove(VALUE_JSON);

        // Normalization: The rest is what we consider signable
        byte[] data = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(document));

        // However, we don't want signature validation to modify the document!
        document[SIGNATURE_JSON] = signatureClone;
        using (ECDsaCng ecKey = new ECDsaCng(CngKey.Import(rawKey, CngKeyBlobFormat.EccPublicBlob)))
        {
            ecKey.HashAlgorithm = CngAlgorithm.Sha256;
            return ecKey.VerifyData(data, base64urldecode((string)signatureClone[VALUE_JSON]));
        }
    }
示例#18
0
 public override bool Verify(byte[] data, byte[] signature, SctHashAlgorithm algorithm)
 {
     byte[] blob;
     if(!EcdsaKeyFormatter.ToEcdsa256PublicKeyBlob(_key, out blob))
     {
         return false;
     }
     using (var key = CngKey.Import(blob, CngKeyBlobFormat.EccPublicBlob, CngProvider.MicrosoftSoftwareKeyStorageProvider))
     {
         using (var ecdsa = new ECDsaCng(key))
         {
             var hashAlgorithm = SctHashAlgorithmToCng(algorithm);
             if (hashAlgorithm == null)
             {
                 return false;
             }
             ecdsa.HashAlgorithm = hashAlgorithm;
             return ecdsa.VerifyData(data, signature);
         }
     }
 }
示例#19
0
 /// <inheritdoc />
 protected internal override bool VerifySignature(byte[] data, byte[] signature)
 {
     using (var cng = new ECDsaCng(this.key))
     {
         return cng.VerifyData(data, signature);
     }
 }
示例#20
0
        public static bool InstallPackages(string[] arguments)
        {
            try
            {
                Log.HighLight ("Installing nuget packages");

                var executingPath       = Assembly.GetExecutingAssembly ().Location;
                var appDirectory        = AppDomain.CurrentDomain.BaseDirectory;
                var solutionDirectory   = Path.GetFullPath (Path.Combine (appDirectory, @"..\..\.."));
                var packagesDirectory   = Path.GetFullPath (Path.Combine (solutionDirectory, @"packages"));
                var flagPath            = Path.Combine (packagesDirectory, "T4Include.NuGet.PackageInstaller.flag");
                var nugetPath           = Path.Combine (packagesDirectory, "NUGET.EXE");

                var executingInfo       = new FileInfo (executingPath);

                var dateTime = executingInfo.LastWriteTime.Ticks;

                if (File.Exists (flagPath))
                {
                    var flagContent = File.ReadAllText (flagPath);
                    long flagDateTime;
                    if (
                            long.TryParse (flagContent, NumberStyles.Integer, CultureInfo.InvariantCulture, out flagDateTime)
                        &&  flagDateTime >= dateTime
                        )
                    {
                        Log.Success ("Installing of nuget packages skipped as flag file found: {0}", flagPath);

                        return true;
                    }
                }

                if (!Directory.Exists (packagesDirectory))
                {
                    Log.HighLight ("package folder not found, creating it : {0}", packagesDirectory);
                    Directory.CreateDirectory (packagesDirectory);
                }

                if (!File.Exists (nugetPath))
                {
                    Log.HighLight ("NuGet.exe not found, downloading it to: {0}", nugetPath);

                    Log.Info ("Downloading signature: {0}", NuGetSignatureUri);

                    var webClient   = new WebClient ();
                    var signature   = Convert.FromBase64String (webClient.DownloadString (NuGetSignatureUri));

                    Log.Info ("Downloading binary: {0}", NuGetUri);

                    var webRequest  = WebRequest.Create (NuGetUri);
                    using (var webResponse = webRequest.GetResponse ())
                    using (var responseStream = webResponse.GetResponseStream ())
                    using (var gZipStream = new GZipStream (responseStream, CompressionMode.Decompress))
                    using (var ms = new MemoryStream ())
                    {
                        const int bufferSize = 4096;
                        var buffer = new byte[bufferSize];
                        var readBytes = 0;

                        while ((readBytes = gZipStream.Read (buffer, 0, bufferSize)) > 0)
                        {
                            ms.Write (buffer, 0, readBytes);
                        }

                        var nugetBits = ms.ToArray();

                        using (var cngKey = CngKey.Import (Convert.FromBase64String (PublicKey), CngKeyBlobFormat.EccPublicBlob))
                        using (var ecDsaCng = new ECDsaCng (cngKey))
                        {
                            if (!ecDsaCng.VerifyData (nugetBits, signature))
                            {
                                Log.Error ("Invalid nuget signature detected, this could be due to attempt to replace NuGet.exe @ T4Include with a malicious binary. Please notify the owner of T4Include.");
                                Environment.ExitCode = 102;
                                return false;
                            }
                        }

                        File.WriteAllBytes (nugetPath, nugetBits);
                    }

                }

                var packages = Directory
                    .GetDirectories (solutionDirectory)
                    .SelectMany (path => Directory.GetFiles (path, "packages.config"))
                    ;

                var result = true;

                foreach (var package in packages)
                {
                    var commandLine = string.Format (
                        CultureInfo.InvariantCulture,
                        @"install -o ""{0}"" ""{1}""",
                        packagesDirectory,
                        package
                        );

                    Log.HighLight ("Installing packages: {0}", package);
                    Log.Info ("  CommandLine: {0}", commandLine);

                    var process = new Process
                                        {
                                            StartInfo = new ProcessStartInfo (
                                                nugetPath,
                                                commandLine)
                                            {
                                                CreateNoWindow  = true                      ,
                                                ErrorDialog     = false                     ,
                                                WindowStyle     = ProcessWindowStyle.Hidden ,
                                            },
                                        };

                    process.Start ();
                    process.WaitForExit ();

                    var exitCode = process.ExitCode;

                    if (exitCode != 0)
                    {
                        result = false;
                        Log.Error ("Failed to install nuget package: {0}", exitCode);
                    }

                }

                if (result)
                {
                    Environment.ExitCode = 0;
                    File.WriteAllText (flagPath, dateTime.ToString (CultureInfo.InvariantCulture));
                    Log.Success ("Installing of nuget packages done");
                }
                else
                {
                    Environment.ExitCode = 101;
                    Log.Error ("Failed to install nuget packages");
                }

                return result;
            }
            catch (Exception exc)
            {
                Environment.ExitCode = 999;
                Log.Exception ("InstallPackages failed with: {0}", exc.Message);
                return false;
            }
        }
示例#21
0
        /// <summary>
        /// Проверка ЭЦП
        /// </summary>
        /// <param name="data">Поток данных.</param>
        /// <param name="signature">ЭЦП.</param>
        /// <param name="publicKey">Открытый ключ для проверки ЭЦП.</param>
        /// <returns>Булевский флаг проверки ЭЦП.</returns>
        private bool VerifyData(Stream data, byte[] signature, byte[] publicKey)
        {
            if(!IsInitialized)
            {
                throw new Exception("EcdhP521::VerifyData() ==> EcdhP521 is not initialized!");
            }

            using(var eECDsaCng = new ECDsaCng(ImportKeyBinData(publicKey, true, true))) // public, DS
            {
                eECDsaCng.HashAlgorithm = CngAlgorithm.Sha512;
                return eECDsaCng.VerifyData(data, signature);
            }
        }
示例#22
0
        public override bool VerifyData(byte[] buffer, HashAlgorithm hashAlgorithm, CertificatePublicKey publicKey, byte[] signature)
        {
            if (!CertificateKeyAlgorithm.Equals(publicKey.Oid)) {
                throw new Exception("ECDSA signature verification requires ECDSA public key");
            }

            string curveOid = DER2OID(publicKey.Parameters);
            if (curveOid == null) {
                throw new Exception("Unsupported ECDSA public key parameters");
            }

            byte[] keyData = publicKey.KeyValue;
            if (keyData[0] != 0x04) {
                throw new Exception("Only uncompressed ECDSA keys supported, format: " + keyData[0]);
            }

            UInt32 keyLength;
            byte[] blobMagic;
            if (curveOid.Equals(P256OID)) {
                keyLength = 32;
                blobMagic = Encoding.ASCII.GetBytes("ECS1");
            } else if (curveOid.Equals(P384OID)) {
                keyLength = 48;
                blobMagic = Encoding.ASCII.GetBytes("ECS3");
            } else if (curveOid.Equals(P521OID)) {
                keyLength = 66;
                blobMagic = Encoding.ASCII.GetBytes("ECS5");
            } else {
                throw new Exception("Unsupported ECC curve type OID: " + curveOid);
            }

            if (2*keyLength != keyData.Length-1) {
                throw new Exception("Invalid length of ECDSA public key: " + keyData.Length +
                                    " (should be " + (1+2*keyLength) + ")");
            }
            byte[] lengthData = BitConverter.GetBytes(keyLength);

            // Create the ECC public blob for ECDsaCng class
            byte[] eccBlob = new byte[8+2*keyLength];
            Buffer.BlockCopy(blobMagic, 0, eccBlob, 0, 4);
            Buffer.BlockCopy(lengthData, 0, eccBlob, 4, 4);
            Buffer.BlockCopy(keyData, 1, eccBlob, 8, (int) (2*keyLength));

            CngKey cngKey = CngKey.Import(eccBlob, CngKeyBlobFormat.EccPublicBlob);
            ECDsaCng ecdsaKey = new ECDsaCng(cngKey);
            ecdsaKey.HashAlgorithm = GetCngAlgorithm(hashAlgorithm);

            return ecdsaKey.VerifyData(buffer, DERDecodeSignature(signature, (int)keyLength));
        }
示例#23
0
 // Weryfikacja na podstawie klucza publicznego, podpisu i podpisanych danych
 public bool verifyData(byte[] publicKey, byte[] signature, byte[] data)
 {
     ECDSA = new ECDsaCng(CngKey.Import(publicKey, CngKeyBlobFormat.EccPublicBlob));
     ECDSA.HashAlgorithm = CngAlgorithm.Sha256;
     return ECDSA.VerifyData(data, signature);
 }
示例#24
0
        protected bool IsValidSignedMsg(byte[] msg, 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.VerifyData(msg, this.sgndData);
            }

            return ret;
        }