Ejemplo n.º 1
0
        public override CertificatePrivateKey ImportPrivateKey(byte[] keyData)
        {
            try {
                string keyString = Encoding.ASCII.GetString(keyData).Trim();
                if (keyString.StartsWith("<DSAKeyValue>")) {
                    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                    dsa.FromXmlString(keyString);
                    return new CertificatePrivateKey(CertificateKeyAlgorithm, dsa);
                }
            } catch (Exception) {}

            return null;
        }
Ejemplo n.º 2
0
        public static string CreateSignature(string inputData, String privateKey)
        {
            // create the crypto-service provider:
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            // setup the dsa from the private key:
            dsa.FromXmlString(privateKey);

            byte[] data = UTF8Encoding.ASCII.GetBytes(inputData);

            // get the signature:
            byte[] signature = dsa.SignData(data);

            return Convert.ToBase64String(signature);
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="publicKey">the public key</param>
        public NetSparkleDSAVerificator(String publicKey)
        {
            // 1. try to load this from resource
            Stream data = TryGetResourceStream(publicKey) ?? TryGetFileResource(publicKey);

            // 2. check the resource
            if ( data == null )
                throw new Exception("Couldn't find public key for verification");

            // 3. read out the key value
            using (StreamReader reader = new StreamReader(data))
            {
                    String key = reader.ReadToEnd();
                    _provider = new DSACryptoServiceProvider();
                    _provider.FromXmlString(key);
            }            
        }
Ejemplo n.º 4
0
        public static bool VerifySignature(string inputData, string signature, string publicKey)
        {
            // create the crypto-service provider:
            DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();

            // setup the provider from the public key:
            dsa.FromXmlString(publicKey);

            // get the license terms data:
            //byte[] data = Convert.FromBase64String(inputData);
            byte[] data = UTF8Encoding.ASCII.GetBytes(inputData);

            // get the signature data:
            byte[] signatureData = Convert.FromBase64String(signature);

            // verify that the license-terms match the signature data
            if (dsa.VerifyData(data, signatureData) == false)
                throw new SecurityException("Signature Not Verified!");

            return true;
        }
Ejemplo n.º 5
0
	public void CapiSignature () 
	{
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (CapiXml512);
		SignAndVerify ("Capi-512", dsa);

		dsa.FromXmlString (CapiXml576);
		SignAndVerify ("Capi-576", dsa);

		dsa.FromXmlString (CapiXml640);
		SignAndVerify ("Capi-640", dsa);

		dsa.FromXmlString (CapiXml704);
		SignAndVerify ("Capi-704", dsa);

		dsa.FromXmlString (CapiXml768);
		SignAndVerify ("Capi-768", dsa);

		dsa.FromXmlString (CapiXml832);
		SignAndVerify ("Capi-832", dsa);

		dsa.FromXmlString (CapiXml896);
		SignAndVerify ("Capi-896", dsa);

		dsa.FromXmlString (CapiXml960);
		SignAndVerify ("Capi-960", dsa);

		dsa.FromXmlString (CapiXml1024);
		SignAndVerify ("Capi-1024", dsa);
	}
Ejemplo n.º 6
0
		/// <summary>
		/// DSA验证
		/// </summary>
		/// <param name="CypherText">签名后的Base64字符串</param>
		/// <param name="xmlString">密钥(至少含公钥)</param>
		/// <param name="signString">签名串</param>
		public static bool VerifyString(string CypherText, string xmlString, string signString)
		{
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
			dsa.FromXmlString(xmlString);

			if (!string.IsNullOrEmpty(CypherText))
			{
				byte[] bEnc = System.Convert.FromBase64String(CypherText);
				byte[] bText = System.Text.Encoding.UTF8.GetBytes(signString.ToCharArray());

				DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(dsa);
				DSADeformatter.SetHashAlgorithm("SHA1");
				return DSADeformatter.VerifySignature(bEnc, bText);
			}
			return false;
		}
Ejemplo n.º 7
0
		//#region 文件处理
		///// <summary>
		///// 加密文件
		///// </summary>
		///// <param name="inName">来源文件</param>
		///// <param name="outName">输出文件</param>
		///// <param name="xmlString">密钥(至少含公钥)</param>
		//public static void EncryptFile(string inName, string outName, string xmlString)
		//{
		//    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
		//    dsa.FromXmlString(xmlString);
		//    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
		//    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
		//    {
		//        fout.SetLength(0);

		//        long rdlen = 0;					//This is the total number of bytes written.
		//        int len;						//This is the number of bytes to be written at a time.
		//        byte[] bin = new byte[FileReadStep];
		//        while (rdlen < fin.Length)
		//        {
		//            len = fin.Read(bin, 0, FileReadStep);
		//            byte[] bs = dsa.Encrypt(bin, false);
		//            fout.Write(bs, 0, bs.Length);
		//            rdlen += len;
		//        }

		//        fin.Close();
		//    }
		//}

		///// <summary>
		///// 解密文件
		///// </summary>
		///// <param name="inName">来源文件</param>
		///// <param name="outName">输出文件</param>
		///// <param name="xmlString">密钥(公钥私钥俱有)</param>
		//public static void DecryptFile(string inName, string outName, string xmlString)
		//{
		//    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
		//    dsa.FromXmlString(xmlString);
		//    FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
		//    using (FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write))
		//    {
		//        fout.SetLength(0);

		//        long rdlen = 0;					//This is the total number of bytes written.
		//        int len;						//This is the number of bytes to be written at a time.
		//        byte[] bin = new byte[FileReadStep];
		//        while (rdlen < fin.Length)
		//        {
		//            len = fin.Read(bin, 0, FileReadStep);
		//            byte[] bs = dsa.Decrypt(bin, false);
		//            fout.Write(bs, 0, bs.Length);
		//            rdlen += len;
		//        }

		//        fin.Close();
		//    }
		//}
		//#endregion

		#region 字符串处理
		/// <summary>
		/// DSA签名
		/// </summary>
		/// <param name="PlainText">原始字符串</param>
		/// <param name="xmlString">密钥(公钥私钥俱有)</param>
		/// <returns>Base64编码后的已签名字符串</returns>
		public static string SignString(string PlainText, string xmlString)
		{
			DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
			dsa.FromXmlString(xmlString);

			if (!string.IsNullOrEmpty(PlainText))
			{
				byte[] bText = System.Text.Encoding.UTF8.GetBytes(PlainText.ToCharArray());

				DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(dsa);
				DSAFormatter.SetHashAlgorithm("SHA1");
				byte[] bEnc = DSAFormatter.CreateSignature(bText);

				return System.Convert.ToBase64String(bEnc);
			}
			return string.Empty;
		}
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            try
            {
                // check if we have some parameters
                if (args.Count() < 1)
                {
                    Usage();
                    return;
                }

                // check what parameter we have
                switch (args[0].ToLower())
                {
                    case "/genkey_pair":
                        {
                            // show headline
                            ShowHeadLine();

                            // verify if output file exists
                            if (File.Exists(_dsaPrivKey) || File.Exists(_dsaPubKey))
                            {
                                Console.WriteLine("Error: Output files are currently exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            // start key generation
                            Console.WriteLine("Generating key pair with 1024 Bits...");
                            DSACryptoServiceProvider prv = new DSACryptoServiceProvider();

                            Console.WriteLine("Storing private key to " + _dsaPrivKey);
                            using (StreamWriter sw = new StreamWriter(_dsaPrivKey))
                            {
                                sw.Write(prv.ToXmlString(true));
                            }

                            Console.WriteLine("Storing public key to " + _dsaPubKey);
                            using (StreamWriter sw = new StreamWriter(_dsaPubKey))
                            {
                                sw.Write(prv.ToXmlString(false));
                            }

                            Console.WriteLine("");
                        }
                        break;
                    case "/sign_update":
                        {
                            if (args.Count() != 3)
                            {
                                Usage();
                                Environment.ExitCode = -1;
                                return;
                            }

                            // get parameter
                            String binary = args[1];
                            String privKey = args[2];

                            if (!File.Exists(binary))
                            {
                                Console.Error.WriteLine("Target binary " + binary + " does not exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            if (!File.Exists(privKey))
                            {
                                Console.Error.WriteLine("Private key file does not exists");
                                Environment.ExitCode = -1;
                                return;
                            }

                            // Reading private key
                            String key = null;
                            using (StreamReader reader = new StreamReader(privKey))
                            {
                                key = reader.ReadToEnd();
                            }

                            DSACryptoServiceProvider prv = new DSACryptoServiceProvider();
                            prv.FromXmlString(key);

                            // open stream
                            Byte[] hash = null;
                            using (Stream inputStream = File.OpenRead(binary))
                            {
                                hash = prv.SignData(inputStream);
                            }

                            String base64Hash = Convert.ToBase64String(hash);
                            Console.WriteLine(base64Hash);
                        }
                        break;
                    case "/verify_update":
                        {
                            if (args.Count() != 4)
                            {
                                Usage();
                                Environment.ExitCode = -1;
                                return;
                            }

                            // get parameter
                            String binary = args[1];
                            String pubKey = args[2];
                            String sign = args[3];

                            sign = sign.TrimStart('"');
                            sign = sign.TrimEnd('"');

                            AppLimit.NetSparkle.NetSparkleDSAVerificator dsaVerif = new AppLimit.NetSparkle.NetSparkleDSAVerificator(pubKey);
                            if (dsaVerif.VerifyDSASignature(sign, binary))
                                Console.WriteLine("Binary " + binary + " is valid");
                            else
                                Console.WriteLine("Binary " + binary + " is NOT valid");
                        }
                        break;
                    default:
                        Usage();
                        break;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Something went wrong :-(");
                Console.WriteLine(e.StackTrace);
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Validates the signature that follows the Licence data
 /// </summary>
 /// <param name="hashValue">Hash value</param>
 /// <param name="signedHashValue">Signed hash value</param>
 /// <param name="xmlKeyInfo">Public Key</param>
 /// <param name="hashAlg">Hash Algorithm</param>
 /// <returns>True if signature is valid</returns>
 private static bool DSAVerifyHash(byte[] hashValue, byte[] signedHashValue, string xmlKeyInfo, string hashAlg)
 {
     DSACryptoServiceProvider.UseMachineKeyStore = false;
     using (DSACryptoServiceProvider DSA = new DSACryptoServiceProvider())
     {
         DSA.FromXmlString(xmlKeyInfo);
         DSASignatureDeformatter DSAFormatter = new DSASignatureDeformatter(DSA);
         DSAFormatter.SetHashAlgorithm(hashAlg);
         return DSAFormatter.VerifySignature(hashValue, signedHashValue);
     }
 }
Ejemplo n.º 10
0
	public void MonoSignature () 
	{
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (MonoXml512);
		SignAndVerify ("Mono-512", dsa);

		dsa.FromXmlString (MonoXml576);
		SignAndVerify ("Mono-576", dsa);

		dsa.FromXmlString (MonoXml640);
		SignAndVerify ("Mono-640", dsa);

		dsa.FromXmlString (MonoXml704);
		SignAndVerify ("Mono-704", dsa);

		dsa.FromXmlString (MonoXml768);
		SignAndVerify ("Mono-768", dsa);

		dsa.FromXmlString (MonoXml832);
		SignAndVerify ("Mono-832", dsa);

		dsa.FromXmlString (MonoXml896);
		SignAndVerify ("Mono-896", dsa);

		dsa.FromXmlString (MonoXml960);
		SignAndVerify ("Mono-960", dsa);

		dsa.FromXmlString (MonoXml1024);
		SignAndVerify ("Mono-1024", dsa);
	}
Ejemplo n.º 11
0
        internal static bool VerifyLocalKeyfile(string filename, out AuthInfo authinfo)
        {
            StreamReader reader = null;
            string data = "";

            authinfo = null;

            try {
                reader = new StreamReader(filename);
                data = reader.ReadToEnd();
                reader.Close();
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Could not read keyfile.\n\n\n" + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            Regex rx = new Regex(@"\s*Keyfile(\n*|\s*)?" +
                @"(?<inner>" +
                @"(?>" +
                @"\{(?<LEVEL>)" +
                @"|" +
                @"\};(?<-LEVEL>)" +
                @"|" +
                @"(?!\{|\};)." +
                @")+" +
                @"(?(LEVEL)(?!))" +
                @")"
                , RegexOptions.IgnoreCase | RegexOptions.Singleline);

            Match topmatch = rx.Match(data);

            if (!topmatch.Success) {
                MessageBox.Show("Offline key authorization failure: Could not find valid 'keyfile' block.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            string keyfile_data = topmatch.Groups["inner"].Value;

            // Once we have the top matched group, parse each line in it
            rx = new Regex(@"\s*\b(?<name>[A-Z]*)\b\s*=\s*((" + "\"" + @"\s*(?<single>.*?)\s*" + "\"" + @"\s*;)|(\{(?<multi>.*?)\};))", RegexOptions.Singleline | RegexOptions.IgnoreCase);

            // 1 = name
            // 4 = normal definition
            // 6 = multiline definition

            string version = "";
            string name = "";
            string expires = "";
            string machinecode = "";
            string featurebit = "";
            string hash = "";
            string signature = "";
            string email = "";

            foreach(Match m in rx.Matches(keyfile_data)) {
                switch(m.Groups["name"].Value.ToLower()) {
                    case "version":
                        version = m.Groups["single"].Value;
                        break;
                    case "name":
                        name = m.Groups["single"].Value;
                        break;
                    case "expires":
                        expires = m.Groups["single"].Value;
                        break;
                    case "machinecode":
                        machinecode = m.Groups["single"].Value;
                        break;
                    case "featurebit":
                        featurebit = m.Groups["single"].Value;
                        break;
                    case "hash":
                        hash = m.Groups["single"].Value;
                        break;
                    case "keysignature":
                        signature = m.Groups["multi"].Value;
                        break;
                    case "email":
                        email = m.Groups["single"].Value;
                        break;
                }
            }

            // Clean up signature
            signature = signature.Replace(" ", "");
            signature = signature.Replace("\t", "");
            signature = signature.Replace("\n", "");
            signature = signature.Replace("\r", "");

            // Check field validity
            if (version == "" || expires == "" || machinecode == "" || featurebit == "" || hash == "" || name == "" || email == "" || signature == "") {
                MessageBox.Show("Offline key authorization failure: Keyfile construction incomplete.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check version
            if (version != "1.00") {
                MessageBox.Show("Offline key authorization failure: Incorrect version (Expected '1.00')", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check expiration date
            try {
                DateTime dt = DateTime.Parse(expires);
                if (DateTime.Now.Ticks >= dt.Ticks) {
                    MessageBox.Show("Offline key authorization has expired.  Please visit www.torquedev.com to request a new offline authorization file.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Unable to verify date stamp.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Check if the machine codes match
            if (machinecode != CConfig.GetHardKey()) {
                MessageBox.Show("Offline key authorization failure: Machine code mismatch.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify hash of data
            string sighash = CConfig.SHA1(version + name + machinecode + expires + featurebit + email);

            if (sighash != hash) {
                MessageBox.Show("Offline key authorization failure: Checksum mismatch.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify signature by first loading the public key into memory
            DSA dsa = new DSACryptoServiceProvider();

            try {
                dsa.FromXmlString(CVerify.PublicKey);
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: Unable to load DSA public key.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return false;
            }

            // Verify the data against the signature
            try {
                if (!dsa.VerifySignature(Convert.FromBase64String(hash), Convert.FromBase64String(signature))) {
                    MessageBox.Show("Offline key authorization failure: File signature is invalid.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    dsa.Clear();
                    return false;
                } else {
                    // Signature checked out.  Create the passback reference
                    authinfo = new AuthInfo(version, name, expires, machinecode, featurebit, hash, signature, email);
                    return true;
                }
            } catch (Exception exc) {
                MessageBox.Show("Offline key authorization failure: DSA verification failure.  Error returned was: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                dsa.Clear();
                return false;
            }
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="mode">The security mode of the validator. Control what parts has to be exist</param>
        /// <param name="publicKey">the public key as string (will be prefered before the file)</param>
        /// <param name="publicKeyFile">the public key file</param>
        public NetSparkleDSAVerificator(SecurityMode mode, String publicKey = null, String publicKeyFile = "NetSparkle_DSA.pub")
        {
            _securityMode = mode;

            String key = publicKey;

            if (string.IsNullOrEmpty(key))
            {
                // TODO: Loading Ressources don't work
                Stream data = TryGetResourceStream(publicKeyFile);
                if (data == null)
                    data = TryGetFileResource(publicKeyFile, data);

                if (data != null)
                {
                    using (StreamReader reader = new StreamReader(data))
                    {
                        key = reader.ReadToEnd();
                    }
                }
            }

            if (!string.IsNullOrEmpty(key))
            {
                try
                {
                    _provider = new DSACryptoServiceProvider();
                    _provider.FromXmlString(key);
                }
                catch
                {
                    _provider = null;
                }
            }
        }
	public void CapiXmlImportExport () 
	{
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (CapiXml512);
		AssertEquals ("Capi-Xml512", CapiXml512, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml576);
		AssertEquals ("Capi-Xml576", CapiXml576, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml640);
		AssertEquals ("Capi-Xml640", CapiXml640, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml704);
		AssertEquals ("Capi-Xml704", CapiXml704, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml768);
		AssertEquals ("Capi-Xml768", CapiXml768, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml832);
		AssertEquals ("Capi-Xml832", CapiXml832, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml896);
		AssertEquals ("Capi-Xml896", CapiXml896, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml960);
		AssertEquals ("Capi-Xml960", CapiXml960, dsa.ToXmlString (true));

		dsa.FromXmlString (CapiXml1024);
		AssertEquals ("Capi-Xml1024", CapiXml1024, dsa.ToXmlString (true));
	}
		public DSASigningService(Key key)
		{
			Debug.Assert(key.Format.Algorithm == AlgorithmName);
			_provider = new DSACryptoServiceProvider(key.Format.BitSize.signed());
			_provider.FromXmlString(System.Text.Encoding.UTF8.GetString(key.Data));
		}
Ejemplo n.º 15
0
	public void CapiVerify () 
	{
		byte[] hash = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 };
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (CapiXml512);
		byte[] sign512 = { 0xCA, 0x11, 0xA4, 0xCD, 0x5B, 0xBA, 0xA1, 0xC9, 0x8C, 0xEF, 0x9A, 0xB8, 0x84, 0x09, 0x96, 0xD0, 0x1B, 0x39, 0x6D, 0x1C, 0xE1, 0xB2, 0x0E, 0xD3, 0xCE, 0xCF, 0x6A, 0x48, 0xDC, 0x22, 0x40, 0xDC, 0xCD, 0x61, 0x25, 0x7F, 0x9E, 0x1B, 0x79, 0x89 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign512), "Capi-512-Verify");
		sign512[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign512), "Capi-512-VerBad");

		dsa.FromXmlString (CapiXml576);
		byte[] sign576 = { 0x10, 0x77, 0xE9, 0x4C, 0x29, 0xB0, 0xF4, 0x0E, 0x3B, 0xB7, 0x8E, 0x3A, 0x40, 0x22, 0x63, 0x70, 0xF3, 0xA5, 0xB7, 0x4A, 0x5C, 0x85, 0xB5, 0xF3, 0x4B, 0x1C, 0x4A, 0x92, 0xDD, 0x1D, 0xED, 0x63, 0x26, 0xC2, 0x42, 0x20, 0xBE, 0x33, 0x55, 0x57 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign576), "Capi-576-Verify");
		sign576[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign576), "Capi-576-VerBad");

		dsa.FromXmlString (CapiXml640);
		byte[] sign640 = { 0x4C, 0x04, 0xAC, 0xE0, 0x84, 0x04, 0x5A, 0x1D, 0x9D, 0x61, 0xA1, 0x62, 0xBE, 0x11, 0xEA, 0x0D, 0x1C, 0x21, 0xC7, 0x55, 0x2C, 0x7C, 0x84, 0x4F, 0x22, 0xE9, 0xA1, 0xF1, 0x2C, 0x83, 0x13, 0x90, 0xAE, 0x36, 0xFD, 0x59, 0x32, 0x21, 0xAE, 0x0F };
		Assert.IsTrue (dsa.VerifySignature (hash, sign640), "Capi-640-Verify");
		sign640[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign640), "Capi-640-VerBad");

		dsa.FromXmlString (CapiXml704);
		byte[] sign704 = { 0xA2, 0x75, 0x32, 0xE0, 0x4B, 0xCA, 0x92, 0x51, 0x84, 0xAC, 0x7C, 0xDE, 0x97, 0xB8, 0xC3, 0x25, 0xD7, 0xF8, 0xA7, 0xE0, 0x76, 0x42, 0x7E, 0x5E, 0x5E, 0x3F, 0x82, 0xDB, 0x87, 0xBF, 0xC9, 0xCC, 0xD9, 0xA2, 0x8E, 0xA2, 0xFE, 0xD3, 0x48, 0x30 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign704), "Capi-704-Verify");
		sign704[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign704), "Capi-704-VerBad");

		dsa.FromXmlString (CapiXml768);
		byte[] sign768 = { 0x92, 0x27, 0x89, 0x4B, 0xB2, 0xDF, 0xE9, 0x98, 0x5A, 0xC5, 0x78, 0x5E, 0xBD, 0x51, 0x6D, 0x10, 0x30, 0xEC, 0x14, 0x95, 0x6E, 0xEB, 0xA6, 0x5F, 0x3E, 0x47, 0x47, 0x86, 0x19, 0xD0, 0xF2, 0x9B, 0x70, 0x98, 0x97, 0x07, 0x04, 0x0C, 0x13, 0xC6 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign768), "Capi-768-Verify");
		sign768[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign768), "Capi-768-VerBad");

		dsa.FromXmlString (CapiXml832);
		byte[] sign832 = { 0xC7, 0x10, 0x86, 0x86, 0x4A, 0x19, 0xBC, 0x8E, 0xC5, 0x0E, 0x53, 0xC0, 0x9E, 0x70, 0x2C, 0xFD, 0x4B, 0x9B, 0xBD, 0x79, 0x46, 0x8E, 0x9F, 0x64, 0x41, 0xF9, 0xBB, 0xDD, 0x3B, 0x93, 0x63, 0x82, 0x7B, 0x9B, 0x5B, 0x12, 0x9B, 0xAA, 0x90, 0xAD };
		Assert.IsTrue (dsa.VerifySignature (hash, sign832), "Capi-832-Verify");
		sign832[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign832), "Capi-832-VerBad");

		dsa.FromXmlString (CapiXml896);
		byte[] sign896 = { 0x7F, 0x0F, 0x5F, 0xC4, 0x44, 0x38, 0x65, 0xD7, 0x0B, 0x03, 0xD1, 0xAC, 0x77, 0xA2, 0xA2, 0x47, 0x37, 0x37, 0x42, 0xA2, 0x97, 0x23, 0xDA, 0x7F, 0xEC, 0xD5, 0x78, 0x3D, 0x5E, 0xDA, 0xA0, 0x02, 0xD6, 0x2D, 0x4B, 0xFA, 0x79, 0x7B, 0x7A, 0x87 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign896), "Capi-896-Verify");
		sign896[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign896), "Capi-896-VerBad");

		dsa.FromXmlString (CapiXml960);
		byte[] sign960 = { 0x63, 0x77, 0x39, 0xE5, 0x03, 0xD2, 0x33, 0xF5, 0xFE, 0x16, 0xE4, 0x7E, 0x49, 0x4E, 0x72, 0xA0, 0x1B, 0x8D, 0x4D, 0xEC, 0x55, 0x15, 0x72, 0x1C, 0x22, 0x37, 0x4B, 0x64, 0xEB, 0x02, 0x3E, 0xC5, 0xCF, 0x32, 0x07, 0xC5, 0xD3, 0xA2, 0x02, 0x0A };
		Assert.IsTrue (dsa.VerifySignature (hash, sign960), "Capi-960-Verify");
		sign960[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign960), "Capi-960-VerBad");

		dsa.FromXmlString (CapiXml1024);
		byte[] sign1024 = { 0x1C, 0x5A, 0x9D, 0x82, 0xDD, 0xE0, 0xF5, 0x65, 0x74, 0x48, 0xFB, 0xD6, 0x27, 0x92, 0x98, 0xEA, 0xC6, 0x7F, 0x4F, 0x7C, 0x49, 0xFC, 0xCF, 0x46, 0xEB, 0x62, 0x27, 0x05, 0xFC, 0x9C, 0x40, 0x74, 0x5B, 0x13, 0x7E, 0x76, 0x9C, 0xE4, 0xF6, 0x53 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign1024), "Capi-1024-Verify");
		sign1024[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign1024), "Capi-1024-VerBad");
	}
Ejemplo n.º 16
0
	public void MonoXmlImportExport () 
	{
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (MonoXml512);
		Assert.AreEqual (MonoXml512, dsa.ToXmlString (true), "Mono-Xml512");

		dsa.FromXmlString (MonoXml576);
		Assert.AreEqual (MonoXml576, dsa.ToXmlString (true), "Mono-Xml576");

		dsa.FromXmlString (MonoXml640);
		Assert.AreEqual (MonoXml640, dsa.ToXmlString (true), "Mono-Xml640");

		dsa.FromXmlString (MonoXml704);
		Assert.AreEqual (MonoXml704, dsa.ToXmlString (true), "Mono-Xml704");

		dsa.FromXmlString (MonoXml768);
		Assert.AreEqual (MonoXml768, dsa.ToXmlString (true), "Mono-Xml768");

		dsa.FromXmlString (MonoXml832);
		Assert.AreEqual (MonoXml832, dsa.ToXmlString (true), "Mono-Xml832");

		dsa.FromXmlString (MonoXml896);
		Assert.AreEqual (MonoXml896, dsa.ToXmlString (true), "Mono-Xml896");

		dsa.FromXmlString (MonoXml960);
		Assert.AreEqual (MonoXml960, dsa.ToXmlString (true), "Mono-Xml960");

		dsa.FromXmlString (MonoXml1024);
		Assert.AreEqual (MonoXml1024, dsa.ToXmlString (true), "Mono-Xml1024");
	}
Ejemplo n.º 17
0
        private static void Sign(IList<string> args)
        {
            if (args.Count != 3)
            {
                Usage();
                Environment.Exit(-1);
            }

            // get parameter
            var artifact = args[1];
            var privKey = args[2];

            if (!File.Exists(artifact))
            {
                ShowErrorMessage(string.Format("\tArtifact {0} doesn't exist", artifact));
            }

            if (!File.Exists(privKey))
            {
                ShowErrorMessage(string.Format("\tPrivate key {0} doesn't exist", privKey));
            }

            string key;
            using (var reader = new StreamReader(privKey))
            {
                key = reader.ReadToEnd();
            }

            var prv = new DSACryptoServiceProvider();
            prv.FromXmlString(key);

            byte[] hash;
            using (Stream inputStream = File.OpenRead(artifact))
            {
                hash = prv.SignData(inputStream);
            }

            var base64Hash = Convert.ToBase64String(hash);
            Console.WriteLine(base64Hash);
        }
Ejemplo n.º 18
0
	public void MonoVerify () 
	{
		byte[] hash = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13 };
		DSACryptoServiceProvider dsa = new DSACryptoServiceProvider ();

		dsa.FromXmlString (MonoXml512);
		byte[] sign512 = { 0x53, 0x44, 0x0A, 0xD7, 0x43, 0x3C, 0x1F, 0xC7, 0xCE, 0x9C, 0xAE, 0xDC, 0xFC, 0x61, 0xD5, 0xCE, 0xC9, 0x5C, 0x8D, 0x13, 0x0F, 0x66, 0x15, 0xCB, 0x9F, 0x94, 0x19, 0x18, 0x63, 0x40, 0x6D, 0x3E, 0x16, 0xA8, 0x3E, 0x9B, 0x8A, 0xC2, 0xA5, 0x38 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign512), "Mono-512-Verify");
		sign512[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign512), "Mono-512-VerBad");

		dsa.FromXmlString (MonoXml576);
		byte[] sign576 = { 0xAC, 0xC8, 0xA3, 0x22, 0x3D, 0x77, 0xE1, 0x13, 0xFD, 0x65, 0x72, 0xE0, 0xA5, 0xF5, 0x94, 0xD6, 0x70, 0x70, 0x40, 0xA9, 0x10, 0x1E, 0x1D, 0xEA, 0x51, 0x68, 0x32, 0x2A, 0x24, 0x47, 0x22, 0x8D, 0xC0, 0xD0, 0x8A, 0x5A, 0x0E, 0x98, 0x5F, 0x2C };
		Assert.IsTrue (dsa.VerifySignature (hash, sign576), "Mono-576-Verify");
		sign576[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign576), "Mono-576-VerBad");

		dsa.FromXmlString (MonoXml640);
		byte[] sign640 = { 0x5E, 0x6E, 0x1F, 0x38, 0xCA, 0x0D, 0x01, 0x01, 0xBE, 0x5E, 0x8B, 0xAB, 0xCE, 0xD2, 0x42, 0x80, 0x4A, 0xBD, 0x74, 0x60, 0x56, 0x4B, 0x16, 0x4A, 0x71, 0xBC, 0xC3, 0x82, 0xE1, 0x54, 0x0D, 0xB0, 0x67, 0xB6, 0xB6, 0x71, 0x46, 0xA9, 0x01, 0x44 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign640), "Mono-640-Verify");
		sign640[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign640), "Mono-640-VerBad");

		dsa.FromXmlString (MonoXml704);
		byte[] sign704 = { 0x27, 0x33, 0x45, 0xC5, 0x41, 0xC7, 0xD6, 0x5D, 0x68, 0x32, 0x50, 0x4C, 0xB3, 0x4B, 0x59, 0xCF, 0x49, 0xD1, 0x61, 0x82, 0xCF, 0x73, 0x20, 0x20, 0x3E, 0x09, 0xA3, 0x49, 0xAA, 0x22, 0x1D, 0x1D, 0x27, 0xBA, 0x9F, 0xDD, 0xE2, 0x7D, 0xCD, 0x82 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign704), "Mono-704-Verify");
		sign704[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign704), "Mono-704-VerBad");

		dsa.FromXmlString (MonoXml768);
		byte[] sign768 = { 0xCA, 0x53, 0x91, 0x99, 0xAE, 0x1B, 0x97, 0xE5, 0x3B, 0x08, 0x78, 0x92, 0xD1, 0x2E, 0x0D, 0xAC, 0xB7, 0x82, 0xFB, 0xA3, 0x84, 0xEE, 0x9B, 0x5E, 0x12, 0x6C, 0x16, 0x6D, 0x97, 0xC1, 0xCF, 0x9A, 0xA9, 0xCF, 0x6A, 0x6E, 0x08, 0x45, 0xA7, 0x19 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign768), "Mono-768-Verify");
		sign768[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign768), "Mono-768-VerBad");

		dsa.FromXmlString (MonoXml832);
		byte[] sign832 = { 0x7F, 0x1C, 0xC5, 0xA4, 0xDB, 0x95, 0x27, 0xD3, 0x23, 0x6E, 0xCE, 0xBC, 0xC0, 0x9D, 0x82, 0x02, 0x6E, 0xA0, 0x80, 0x5D, 0x53, 0x54, 0x3D, 0x1B, 0x1C, 0x54, 0xDD, 0x1F, 0xD5, 0x7E, 0x07, 0x60, 0xDD, 0x2A, 0xB2, 0x96, 0x3C, 0x36, 0xB3, 0x60 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign832), "Mono-832-Verify");
		sign832[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign832), "Mono-832-VerBad");

		dsa.FromXmlString (MonoXml896);
		byte[] sign896 = { 0x36, 0x90, 0xA2, 0x4C, 0xDA, 0xDC, 0x6C, 0xF3, 0x83, 0xFE, 0xA8, 0x14, 0xFB, 0x01, 0x69, 0x5F, 0xFA, 0xFA, 0x71, 0xA6, 0x6F, 0xBE, 0x96, 0xB7, 0x11, 0xE7, 0xDE, 0xC7, 0x71, 0x10, 0x83, 0xEE, 0x34, 0x18, 0x4E, 0x88, 0xC1, 0xE0, 0xF9, 0x0A };
		Assert.IsTrue (dsa.VerifySignature (hash, sign896), "Mono-896-Verify");
		sign896[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign896), "Mono-896-VerBad");

		dsa.FromXmlString (MonoXml960);
		byte[] sign960 = { 0xCE, 0xE8, 0x52, 0x32, 0x9B, 0x30, 0xB5, 0x22, 0x6C, 0x21, 0x34, 0xC6, 0x09, 0xD8, 0xA8, 0x6D, 0x00, 0x87, 0x0F, 0x87, 0x21, 0x50, 0x18, 0x99, 0xED, 0x2A, 0xD3, 0xA5, 0x82, 0x8D, 0x38, 0x63, 0x21, 0xDA, 0xE1, 0x94, 0x65, 0xE1, 0x6E, 0x72 };
		Assert.IsTrue (dsa.VerifySignature (hash, sign960), "Mono-960-Verify");
		sign960[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign960), "Mono-960-VerBad");

		dsa.FromXmlString (MonoXml1024);
		byte[] sign1024 = { 0x67, 0x73, 0x4D, 0x6C, 0x0E, 0xB2, 0x85, 0xC6, 0x97, 0x5F, 0x09, 0x42, 0xEA, 0xDB, 0xC6, 0xE1, 0x6D, 0x84, 0xA0, 0x15, 0x63, 0x6C, 0xE3, 0x83, 0xA5, 0xCB, 0x58, 0xC6, 0x51, 0x3C, 0xB4, 0xD2, 0x6B, 0xA0, 0x70, 0xCE, 0xD9, 0x8D, 0x96, 0xCA };
		Assert.IsTrue (dsa.VerifySignature (hash, sign1024), "Mono-1024-Verify");
		sign1024[0] = 0x00;
		Assert.IsFalse (dsa.VerifySignature (hash, sign1024), "Mono-1024-VerBad");
	}
Ejemplo n.º 19
0
        //Верифицируем - проверяем документ
        private void button7_Click(object sender, EventArgs e)
        {
            // создаем объект выбранного заказа
            // определяем, выбран ли хотя бы один заказ
            if (dataGridView1.SelectedRows.Count == 0)
                return;
            else
            {

                //получение номера текущего выбранного заказа
                nom = (int)dataGridView1.SelectedRows[0].Cells["НомерЗаказа"].Value;
                // проверка, имеется ли цифровая подпись выбранного чека, 
                // т.е. имеется ли соответствующий файл
                if (!File.Exists("Zakaz" + nom + ".dat"))
                {
                    MessageBox.Show("Ещё не создана цифровая подпись!");
                    return;
                }
                else
                {
                    // создаем объект выбранного заказа аналогично предыдущей функции 
                    // (объект с класса Zakaz)
                    MessageBox.Show(nom.ToString());
                    //получение номера текущего выбранного заказа
                    date = (DateTime)dataGridView1.SelectedRows[0].Cells["ДатаЗаказа"].Value;
                    // поиск заказа по ключу
                    DataRow dr = ds.Tables["Заказы"].Rows.Find(new object[] { (object)nom, (object)date });
                    // создаем объект заказа для последующей сериализации
                    Zakaz c = new Zakaz((int)dr["IDЗаказчика"], (int)dr["IDИсполнителя"], (int)dr["НомерЗаказа"], (DateTime)dr["ДатаЗаказа"], (string)dr["Предмет/Тема"], (int)dr["Стоимость"]);

                    // проводим генерацию хэш-значения для объекта c
                    // бинарная сериализация объекта для формирования цифровой подписи
                    BinaryFormatter ser = new BinaryFormatter();
                    // создаем поток для сериализации объекта в оперативной памяти
                    MemoryStream ms = new MemoryStream();
                    ser.Serialize(ms, c);

                    // получаем массив байт, определяющий объект чека
                    byte[] message = new byte[ms.Length];
                    ms.Read(message, 0, (int)ms.Length);

                    // создаем провайдер для хэширования
                    SHA1 sha1 = new SHA1CryptoServiceProvider();
                    // проводим хэширование
                    byte[] hashMessage = sha1.ComputeHash(message);

                    // работа с цифровой подписью - считываем подпись и 
                    // ключ из файла и осуществляем верификацию
                    // читаем данные из файла-подписи
                    BinaryReader br = new BinaryReader(new FileStream("Zakaz" + nom + ".dat", FileMode.Open));

                    // читаем ключ для шифрования
                    string key = br.ReadString();
                    // читаем данные подписи
                    int n_sign = br.ReadInt32();
                    byte[] b_sign = br.ReadBytes(n_sign);
                    br.Close();

                    // импортируем параметры в провайдер шифрования
                    DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
                    dsa.FromXmlString(key);

                    // проводим верификацию подписей
                    // первый параметр - сгенерированный хэш объекта
                    // второй параметр - ключ
                    // третий параметр - цифровая подпись
                    if (dsa.VerifyHash(hashMessage, "1.3.14.3.2.26", b_sign))
                    {
                        MessageBox.Show("Успешная верификация!");
                    }
                    else
                    {
                        MessageBox.Show("Заказ был изменен. Ошибка верификации!");
                    }
                }
            }
        }
        /// <summary>
        /// Método verifica si firma digital es correcta.
        /// </summary>
        /// <param name="pClavePublica">Cadena clave pública.</param>
        /// <param name="pFirmaDigital">Array byte de firma digital.</param>
        /// <param name="pClaveHash">Array byte clave hash.</param>
        /// <returns>
        /// Resultado booleano de verificación.
        /// </returns>
        private static bool ComprobarFirmaDigitalDSA(string pClavePublica, byte[] pFirmaDigital, byte[] pClaveHash)
        {
            // Instancia servicio de criptación DSA.
            DSACryptoServiceProvider vServicioCriptorDSA = new DSACryptoServiceProvider();

            // Asigna clave pública a servicio criptor.
            vServicioCriptorDSA.FromXmlString(pClavePublica);

            // Instancia por medio de servicio criptor a formateador de firma por medio de DSA.
            DSASignatureDeformatter vFormateadorFirmaDSA = new DSASignatureDeformatter(vServicioCriptorDSA);

            // Indica el algoritmo hash a utilizar.
            vFormateadorFirmaDSA.SetHashAlgorithm(ALGORITMO);

            // Verifica si firma digital es correcto y asigna  resultado a una variable booleana.
            bool vFirmaEsCorrecta = vFormateadorFirmaDSA.VerifySignature(pClaveHash, pFirmaDigital);

            // Retorna resultado.
            return vFirmaEsCorrecta;
        }
        /// <summary>
        /// Método crea firma digital.
        /// </summary>
        /// <param name="pClaveHash">Array byte de clave hash.</param>
        /// <param name="pClavesXML">Claves xml pública y privada.</param>
        /// <returns>
        /// Firma digital.
        /// </returns>
        private static byte[] CrearFirmaDigitalDSA(byte[] pClaveHash, string pClavesXML)
        {
            // Instancia servicio criptor DSA.
            DSACryptoServiceProvider vServicioCriptorDSA = new DSACryptoServiceProvider();

            // Asignamos las claves públicas y privadas a servicio criptor.
            vServicioCriptorDSA.FromXmlString(pClavesXML);

            // Instancia por medio de servicio criptor a formateador de firma por medio de DSA.
            DSASignatureFormatter vFormateadorFirmaDSA = new DSASignatureFormatter(vServicioCriptorDSA);

            // Indica el algoritmo hash a utilizar.
            vFormateadorFirmaDSA.SetHashAlgorithm(ALGORITMO);

            // Creamos la firma digital y se retorna.
            return vFormateadorFirmaDSA.CreateSignature(pClaveHash);
        }
Ejemplo n.º 22
0
        /*private void GenerateLicense() {
            DSA dsa = new DSACryptoServiceProvider();
            dsa.FromXmlString(PrivateKey);

            string vfyhash =
                "Sam Bacsa" +
                "netMercs Group" +
                "Unlimited" +
                "CMS-102022-00UL" +
                "Never" +
                "1.2" +
                "1.3";

            // Grab all the featurebits
            foreach (bool val in _features.Values)
                vfyhash += val.ToString();

            // Hash it and get the result
            string hash = Convert.ToBase64String(dsa.CreateSignature(Convert.FromBase64String(CConfig.SHA1(vfyhash))));
        }*/
        private bool VerifyLicense()
        {
            // Verifies the loaded license details to see if they
            // check out
            g.LogDebug("LicenseManager::VerifyLicense: Enter");

            g.LogDebug("LicenseManager::VerifyLicense: Loading DSA object and public key");
            DSA dsa = new DSACryptoServiceProvider();
            dsa.FromXmlString(PublicKey);

            g.LogDebug("LicenseManager::VerifyLicense: Object loaded.  Key is " + PublicKey);

            string vfyhash = _user + _company + _limit + _serial + ((_expires.Year == 1) ? "Never" : _expires.ToString())
                    + _version.ToString() + _version_limit.ToString();

            // Load the feature bits
            foreach (bool val in _features.Values)
                vfyhash += val.ToString();

            g.LogDebug("LicenseManager::VerifyLicense: vfyhash is " + vfyhash);
            g.LogDebug("LicenseManager::VerifyLicense: Verifying signature");

            bool result = dsa.VerifySignature(
                    Convert.FromBase64String(CConfig.SHA1(vfyhash)),
                    Convert.FromBase64String(_signature)
            );

            g.LogDebug("LicenseManager::VerifyLicense: Result of signature verification is: " + result.ToString());
            g.LogDebug("LicenseManager::VerifyLicense: Leave");

            return result;
        }
Ejemplo n.º 23
0
 public static String GetPublicKey(String privateKey)
 {
     DSACryptoServiceProvider dsa = new DSACryptoServiceProvider();
     dsa.FromXmlString(privateKey);
     return dsa.ToXmlString(false);
 }