Ejemplo n.º 1
1
		public void TestEncodeAndDecode_byteArr_Key()
		{
			Console.Out.WriteLine("encode and decode");

			RSAService instance = new RSAService(keysize);
			RSAPrivateKey privateKey = instance.ReadPrivateKey(privateKeyfile);
			RSAPublicKey publicKey = instance.ReadPublicKey(publicKeyfile);

			byte[] encData = instance.Encode(msgBytes, privateKey);
			byte[] decData = instance.Decode(encData, publicKey);

			Boolean bCompare = Compare.SafeEquals(msgBytes, decData);
			Assert.IsTrue(bCompare);

			encData = instance.Encode(msgBytes, publicKey);
			decData = instance.Decode(encData, privateKey);

			bCompare = Compare.SafeEquals(msgBytes, decData);
			Assert.IsTrue(bCompare);

		}
Ejemplo n.º 2
0
 /// <summary>
 /// Decrypts the specified data.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <returns></returns>
 public byte[] Decrypt(byte[] data)
 {
     using (var rsa = new RSAService(_xmlKey))
     {
         return(rsa.DecryptArrayBlock(data));
     }
 }
Ejemplo n.º 3
0
 /// <summary>
 /// Decrypts the string.
 /// </summary>
 /// <param name="data">The data.</param>
 /// <param name="encoding">The encoding.</param>
 /// <returns></returns>
 public string DecryptString(string data, Encoding encoding)
 {
     using (var rsa = new RSAService(_xmlKey))
     {
         return(rsa.DecryptString(data, encoding));
     }
 }
Ejemplo n.º 4
0
    //加密方法
    public static string Encrypt(string msg)
    {
        //随机生成key
        string key = Random.Range(10000000, 99999999).ToString().Substring(0, 8);

        //用key加密报文
        string securityData = DESservice.Encode(msg, key);

        //加密key
        string securityKey = RSAService.encriptByPublicKey(key, publickey);

        //Debug.Log("-----------------------------------------------");
        //Debug.Log(key + "  length: " + key.Length);
        //Debug.Log(publickey);

        //Debug.Log(securityKey);
        //Debug.Log("-----------------------------------------------");

        //返回string
        Dictionary <string, object> data = new Dictionary <string, object>();

        data.Add("securityKey", securityKey);
        data.Add("securityData", securityData);

        return(Json.Serialize(data));
    }
Ejemplo n.º 5
0
    /// <summary>
    /// 加密模块的创建
    /// </summary>
    /// <param name="type">加密类型</param>
    /// <param name="key">加密密钥</param>
    private static ICryptography GetService(ServiceType type, string key)
    {
        ICryptography _cryptography = null;

        if (type.Equals(ServiceType.AES))
        {
            AESService aes = new AESService();
            aes.Key       = key;
            _cryptography = aes;
        }
        else if (type.Equals(ServiceType.DES))
        {
            ThreeDesService des = new ThreeDesService();
            des.Key       = key;
            _cryptography = des;
        }
        else if (type.Equals(ServiceType.RSA))
        {
            RSAService rsa = new RSAService();
            rsa.PublicKey = key;
            _cryptography = rsa;
        }
        else
        {
        }
        return(_cryptography);
    }
Ejemplo n.º 6
0
        public async Task <ActionResult> Login(WebApplication_JS_RSA.ViewModels.LoginViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                //decrypt password
                var password = RSAService.GetPlainText(viewModel.EncryptedPassword);


                return(View(viewModel));
            }
            else
            {
                viewModel.ErrorMessage = "";
            }
            return(Json(viewModel));

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            //var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
            //switch (result)
            //{
            //    case SignInStatus.Success:
            //        return RedirectToLocal(returnUrl);
            //    case SignInStatus.LockedOut:
            //        return View("Lockout");
            //    case SignInStatus.RequiresVerification:
            //        return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            //    case SignInStatus.Failure:
            //    default:
            //        ModelState.AddModelError("", "Invalid login attempt.");
            //        return View(model);
            //}
        }
Ejemplo n.º 7
0
 public HomeController(
     IStringLocalizer <HomeController> localizer,
     RSAService rsaService,
     APIDbContext dbContext)
 {
     _localizer  = localizer;
     _rsaService = rsaService;
     _dbContext  = dbContext;
 }
Ejemplo n.º 8
0
        public ActionResult Login(string returnUrl)
        {
            var viewModel = new WebApplication_JS_RSA.ViewModels.LoginViewModel();

            viewModel.PublicKey = RSAService.GetPulicKey();

            ViewBag.ReturnUrl = returnUrl;
            return(View(viewModel));
        }
Ejemplo n.º 9
0
        public SignUpModel()
        {
            XmlService      = new XmlService();
            RSAService      = new RSAService();
            HashService     = new HashService();
            SymetricService = new SymetricService();

            User      = new UserDto();
            User.Salt = Guid.NewGuid().ToString();
        }
Ejemplo n.º 10
0
        public static byte[] RSADecrypt(byte[] DataToDecrypt, bool DoOAEPPadding = false)
        {
            try
            {
                return(RSAService.Decrypt(DataToDecrypt, DoOAEPPadding));
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());

                return(null);
            }
        }
Ejemplo n.º 11
0
        public bool SignUp()
        {
            try
            {
                if (!Directory.Exists(DatabaseDir))
                {
                    Directory.CreateDirectory(DatabaseDir);
                }

                if (!IsUserValid())
                {
                    return(false);
                }

                var emailExists = this.CheckUniqueEmail();
                if (emailExists)
                {
                    this.WarningMessage = "This email already exists. Please choose another one!";
                    return(false);
                }

                var isEmailValid = this.isEmailValid();
                if (!isEmailValid)
                {
                    this.WarningMessage = "Please input a valid email!";
                    return(false);
                }

                var emailEncoded = Convert.ToBase64String(Encoding.UTF8.GetBytes(this.User.Email));
                var filePath     = Path.Combine(DatabaseDir, emailEncoded);
                filePath = Path.ChangeExtension(filePath, "xml");

                var keyPair = RSAService.GenerateKeyPair((int)this.KeySize);
                User.Passphrase = HashService.SHA256Hash(User.Passphrase, User.Salt);
                User.IV         = Convert.ToBase64String(SymetricService.RijndaelGenerateIV());
                User.PrivateKey = SymetricService.RijndaelEncryptData(keyPair.PrivateKey,
                                                                      Convert.FromBase64String(User.Passphrase),
                                                                      Convert.FromBase64String(User.IV));
                User.PublicKey = Convert.ToBase64String(Encoding.UTF8.GetBytes(keyPair.PublicKey));

                XmlService.WriteToXml <UserDto>(filePath, User);
                this.InfoMessage = "Sign up successfully";
            }
            catch (Exception ex)
            {
                this.WarningMessage = "There was an error creating your account";
                return(false);
            }

            return(true);
        }
Ejemplo n.º 12
0
        private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            byte[] bytes = new byte[] { 4, 25, 156, 243 };
            long   p     = /*10007*/ 7;
            long   q     = /*10009*/ 13;
            var    keys  = RSAService.ZnajdzWykladnikPublicznyiPrywatny(p, q);

            var result = RSAService.Encode(bytes, keys[0], p * q);



            var inverse = RSAService.Decode(result, keys[1], p * q);

            int a = 0;
        }
Ejemplo n.º 13
0
		public void TestGenerateKey_String_String()
		{
			Console.Out.WriteLine("generateKey");
			RSAService rsa = new RSAService(keysize);
			if (!rsa.AreKeysPresent(privateKeyfile, publicKeyfile))
			{
				Console.Out.WriteLine("Begin Generating RSA Key Pair.");
				using (FileStream fos_private = new FileStream(privateKeyfile, FileMode.Create))
				{
					using (FileStream fos_public = new FileStream(publicKeyfile, FileMode.Create))
					{
						rsa.GenerateKey(fos_private, fos_public);
					}
				}
				Console.Out.WriteLine("Finish Generating RSA Key Pair.");
			}
			Assert.IsTrue(true);
		}
Ejemplo n.º 14
0
        internal bool SignFile()
        {
            if (!Validate())
            {
                return(false);
            }

            try
            {
                var privateKey = GetPrivateKey();
                RSAService.Sign(this.FileSignName, privateKey);
            }
            catch (Exception ex)
            {
                return(false);
            }

            return(true);
        }
Ejemplo n.º 15
0
        public void GenerateKey()
        {
            try
            {
                string publicKey, privateKey;

                if (!File.Exists(KeysFile))
                {
                    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                    publicKey  = rsa.ToXmlString(false);
                    privateKey = rsa.ToXmlString(true);

                    File.WriteAllText(KeysFile, publicKey + Environment.NewLine + privateKey);
                    rsa.Dispose();
                }
                else
                {
                    var lines = File.ReadAllLines(KeysFile);

                    publicKey  = lines[0];
                    privateKey = lines[1];
                }

                if (!File.Exists(EncFile))
                {
                    RSAService.Encrypt(publicKey, Strings.Generate(32), EncFile);

                    SymmetricalKey = File.ReadAllText(EncFile);
                }
                else
                {
                    SymmetricalKey = File.ReadAllText(EncFile);
                }
            } catch (Exception e) { }
        }
Ejemplo n.º 16
0
    //解密方法
    public static string Decrypt(string msg)
    {
        //解析json
        Dictionary <string, object> json = (Dictionary <string, object>)Json.Deserialize(msg);

        //如果未加密直接返回
        if (!json.ContainsKey("sign"))
        {
            return(msg);
        }

        string sign    = (string)json["sign"];
        string conetnt = (string)json["msg"];

        //验证签名
        if (RSAService.VerifySignedHash(conetnt, sign, publickey))
        {
            return(conetnt);
        }
        else
        {
            throw new System.Exception("签名验证失败 " + msg);
        }
    }
Ejemplo n.º 17
0
        public async Task DecodeRSA()
        {
            var segment = Segments.Find(i => i.Name == JPEGResources.SegmentNameDictionary[0xDA]);

            byte[] bytes       = FileBytes.Take(segment.SegmentEndByteIndexInFile - 2).Skip(segment.SegmentStartByteIndexInFile + 20).ToArray();
            int    excessBytes = bytes.Length * 8 - bytes.Length;

            byte[] newBytes = new byte[bytes.Length * 8];
            bytes.CopyTo(newBytes, 0);
            FileBytes.Skip(FileBytes.Length - excessBytes).ToArray().CopyTo(newBytes, bytes.Length);
            long p = 10007;
            long q = 10009;

            var keys = RSAService.ZnajdzWykladnikPublicznyiPrywatny(p, q);

            var result = RSAService.Decode(newBytes, keys[1], p * q);

            result.CopyTo(FileBytes, segment.SegmentStartByteIndexInFile + 20);
            byte[] newFileBytes = new byte[FileBytes.Length - excessBytes];
            FileBytes.Take(FileBytes.Length - excessBytes).ToArray().CopyTo(newFileBytes, 0);
            FileBytes = newFileBytes;
            Modified  = true;
            await SaveFile();
        }
Ejemplo n.º 18
0
        public async Task EncodeRSA()
        {
            var segment = Segments.Find(i => i.Name == JPEGResources.SegmentNameDictionary[0xDA]);

            byte[] bytes = FileBytes.Take(segment.SegmentEndByteIndexInFile - 2).Skip(segment.SegmentStartByteIndexInFile + 20).ToArray();
            long   p     = 10007;
            long   q     = 10009;
            var    keys  = RSAService.ZnajdzWykladnikPublicznyiPrywatny(p, q);

            var result = RSAService.Encode(bytes, keys[0], p * q);

            int takeSkip = segment.SegmentEndByteIndexInFile - 2 - segment.SegmentStartByteIndexInFile - 20;

            result.Take(takeSkip)
            .ToArray()
            .CopyTo(FileBytes, segment.SegmentStartByteIndexInFile + 20);
            var newFileBytes = new byte[FileBytes.Length + result.Length - takeSkip];

            FileBytes.CopyTo(newFileBytes, 0);
            result.Skip(takeSkip).ToArray().CopyTo(newFileBytes, FileBytes.Length);
            FileBytes = newFileBytes;
            Modified  = true;
            await SaveFile();
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Signs the specified x node.
 /// </summary>
 /// <param name="xNode">The x node.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static XmlNode Sign(XmlNode xNode, RSAService rsa)
 {
     return(Sign(xNode, rsa.Provider));
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Signs the specified x element.
 /// </summary>
 /// <param name="xElement">The x element.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static XmlElement Sign(XmlElement xElement, RSAService rsa)
 {
     return(Sign(xElement, rsa.Provider));
 }
Ejemplo n.º 21
0
		public void TestReadPublicKeyFromPrivate_String()
		{
			Console.Out.WriteLine("readPublicKeyFromPrivate");
			RSAService instance = new RSAService(keysize);
			RSAPublicKey result = instance.ReadPublicKeyFromPrivate(privateKeyfile);
			Assert.IsNotNull(result);
		}
Ejemplo n.º 22
0
 public ACTokenManager(RSAService rsa)
 {
     _rsa = rsa;
 }
Ejemplo n.º 23
0
		public void TestReadPublicKey_String()
		{
			Console.Out.WriteLine("readPublicKey");
			RSAService instance = new RSAService(keysize);
			RSAPublicKey publicKey = instance.ReadPublicKey(publicKeyfile);
			Assert.IsNotNull(publicKey);
		}
Ejemplo n.º 24
0
 /// <summary>
 /// Verifies the signature.
 /// </summary>
 /// <param name="xNode">The x node.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static bool VerifySignature(XmlNode xNode, RSAService rsa)
 {
     return(VerifySignature(xNode, rsa.Provider));
 }
Ejemplo n.º 25
0
 public FileSignModel()
 {
     User            = new UserDto();
     RSAService      = new RSAService();
     SymetricService = new SymetricService();
 }
Ejemplo n.º 26
0
		public static void Test()
		{
			Console.Out.WriteLine("Begin Example_010.");
			
			// Create some data to test with.
			Support.TestData(TESTDATA_FILE);

			/**
			 * Create a public / private RSA key pair.
			 */
			RSAService rsa = new RSAService();
			if (!rsa.AreKeysPresent(privateKeyfile, publicKeyfile))
			{
				Console.Out.WriteLine("Begin Create RSA Keys.");
				using (FileStream os_private = new FileStream(privateKeyfile, FileMode.Create),
					   os_public = new FileStream(publicKeyfile, FileMode.Create))
				{
					rsa.GenerateKey(os_private, os_public);
				}
				Console.Out.WriteLine("End Create RSA Keys.");
			}

			/**
			 * RSA keys are asynchronous; there is a public and private key. Each
			 * key can only decrypt data encrypted with the other key. A client
			 * process would not have both keys, this is only for demonstration
			 * purposes.
			 */

			Console.Out.WriteLine("Begin Read RSA Keys.");
			RSAPrivateKey privateKey = null;
			RSAPublicKey publicKey = null;
			using (FileStream is_private = new FileStream(privateKeyfile, FileMode.Open),
				   is_public = new FileStream(publicKeyfile, FileMode.Open))
			{
				privateKey = rsa.ReadPrivateKey(is_private);
				publicKey = rsa.ReadPublicKey(is_public);
			}
			Console.Out.WriteLine("End Read RSA Keys.");

			/**
			 * Use public key to encrypt a file stream directly to another file
			 * stream.
			 */
			Console.Out.WriteLine("Begin Encrypt Data.");
			using (FileStream outstream = new FileStream(TESTDATA_ENC_FILE, FileMode.Create),
				   instream = new FileStream(TESTDATA_FILE, FileMode.Open))
			{
				rsa.Encode(instream, outstream, publicKey);
			}
			Console.Out.WriteLine("End Encrypt Data.");

			/**
			 * Now decrypt the encrypted file using the private key.
			 */
			Console.Out.WriteLine("Begin Decrypt Data.");
			using (FileStream outstream = new FileStream(TESTDATA_DEC_FILE, FileMode.Create),
				instream = new FileStream(TESTDATA_ENC_FILE, FileMode.Open))
			{
				rsa.Decode(instream, outstream, privateKey);
			}
			Console.Out.WriteLine("End Decrypt Data.");

			/**
			 * Compare the original and decrypted files.
			 */
			string shaOriginal = DigestSHA.Sha256(new FileStream(TESTDATA_FILE, FileMode.Open));
			string shaDecripted = DigestSHA.Sha256(new FileStream(TESTDATA_DEC_FILE, FileMode.Open));
			if (Compare.SafeEquals(UTF8Encoding.UTF8.GetBytes(shaOriginal), UTF8Encoding.UTF8.GetBytes(shaDecripted)))
			{
				Console.Out.WriteLine("Encrypted and decrypted files are the same.");
			}
			else
			{
				Console.Out.WriteLine("Encrypted and decrypted files are NOT the same.");
			}
			Console.Out.WriteLine("End Example_010.");
		}
Ejemplo n.º 27
0
		public static void Test()
		{
			Console.Out.WriteLine("Begin Example_020.");
			// Create some data to test with.
			Support.TestData(TESTDATA_FILE);

			/**
			 * Create a public / private RS key pair.
			 */
			RSAService rsa = new RSAService();
			if (!rsa.AreKeysPresent(privateKeyfile, publicKeyfile))
			{
				Console.Out.WriteLine("Begin Create RSA Keys.");
				rsa.GenerateKey(privateKeyfile, publicKeyfile);
				Console.Out.WriteLine("End Create RSA Keys.");
			}

			/**
			 * RSA keys are asynchronous; there is a public and private key. Each
			 * key can only decrypt data encrypted with the other key. A client
			 * process would not have both keys, this is only for demonstration
			 * purposes.
			 */
			Console.Out.WriteLine("Begin Read RSA Keys.");
			RSAPrivateKey privateKey = rsa.ReadPrivateKey(privateKeyfile);
			RSAPublicKey publicKey = rsa.ReadPublicKey(publicKeyfile);
			Console.Out.WriteLine("End Read RSA Keys.");

			/**
			 * Read the test data into a byte array. Be sure to use UTF-8 when
			 * converting between strings and byte arrays.
			 */
			Console.Out.WriteLine("Begin Read Data.");
			string testdata = File.ReadAllText(TESTDATA_FILE);
			byte[] testdata_bytes = UTF8Encoding.UTF8.GetBytes(testdata);
			Console.Out.WriteLine("End Read Data.");

			/**
			 * Use public key to encrypt a byte array to another byte array.
			 */
			Console.Out.WriteLine("Begin Encrypt Data.");
			byte[] testdata_enc = rsa.Encode(testdata_bytes, publicKey);
			Console.Out.WriteLine("End Encrypt Data.");

			/**
			 * Now decrypt the encrypted file using the private key.
			 */
			Console.Out.WriteLine("Begin Decrypt Data.");
			byte[] testdata_dec = rsa.Decode(testdata_enc, privateKey);
			Console.Out.WriteLine("End Decrypt Data.");

			/**
			 * Compare the original and decrypted files.
			 */
			String shaOriginal = DigestSHA.Sha256(testdata_bytes);
			String shaDecripted = DigestSHA.Sha256(testdata_dec);
			if (Compare.SafeEquals(UTF8Encoding.UTF8.GetBytes(shaOriginal), UTF8Encoding.UTF8.GetBytes(shaDecripted)))
			{
				Console.Out.WriteLine("Encrypted and decrypted files are the same.");
			}
			else
			{
				Console.Out.WriteLine("Encrypted and decrypted files are NOT the same.");
			}
			Console.Out.WriteLine("End Example_020.");
		}
Ejemplo n.º 28
0
		public void TestEncodeAndDecode_3args()
		{
			Console.Out.WriteLine("encode and decode stream");

			RSAService instance = new RSAService(keysize);
			RSAPrivateKey privateKey = instance.ReadPrivateKey(privateKeyfile);
			RSAPublicKey publicKey = instance.ReadPublicKey(publicKeyfile);

			byte[] decData;
			using (MemoryStream outstream = new MemoryStream())
			{
				using (MemoryStream instream = new MemoryStream(msgBytes))
				{
					instance.Encode(instream, outstream, privateKey);
					byte[] encData = outstream.ToArray();
					decData = instance.Decode(encData, publicKey);
				}
			}

			Boolean bCompare = Compare.SafeEquals(msgBytes, decData);
			Assert.IsTrue(bCompare);

			using (MemoryStream outstream = new MemoryStream())
			{
				using (MemoryStream instream = new MemoryStream(msgBytes))
				{
					instance.Encode(instream, outstream, publicKey);
					byte[] encData = outstream.ToArray();
					decData = instance.Decode(encData, privateKey);
				}
			}

			bCompare = Compare.SafeEquals(msgBytes, decData);
			Assert.IsTrue(bCompare);
		}
Ejemplo n.º 29
0
 /// <summary>
 /// Signs the specified x document.
 /// </summary>
 /// <param name="xDoc">The x document.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static XmlDocument Sign(XmlDocument xDoc, RSAService rsa)
 {
     return(Sign(xDoc, rsa.Provider));
 }
Ejemplo n.º 30
0
 /// <summary>
 /// Verifies the signature.
 /// </summary>
 /// <param name="xElement">The x element.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static bool VerifySignature(XmlElement xElement, RSAService rsa)
 {
     return(VerifySignature(xElement, rsa.Provider));
 }
Ejemplo n.º 31
0
        public bool Verify(byte[] nis)
        {
            var digestAlgo = string.Empty;

            switch (OIDDSMessageDigestHashAlgo)
            {
            case "2.16.840.1.101.3.4.2.1":
                digestAlgo = "SHA256";
                break;

            case "2.16.840.1.101.3.4.2.3":
                digestAlgo = "SHA512";
                break;

            default:
                throw new Exception("hash algoritm not valid");
            }

            /*Get hashed data of
             * - ID servizi
             * - Seriale carta
             * - Certificato utente
             * - Chiave pubblica di internal authentication
             * - Chiave pubblica di internal authentication per i servizi
             * contained in SignedDataObject and calculate hash of hash*/
            var digestRecalculation = SignedDataObject.DeepChild(1, 0).Data.ToMessageDigest(digestAlgo);

            //Compare recalculation of hash with data contained in signer message digest object to verify equality
            if (digestRecalculation.ToHexString() != SignerMessageDigest.Data.ToHexString())
            {
                return(false); // Digest SOD not correspond to data
            }
            //Get Document Signer public key from SignedCert data
            var dsPubKey = DSCertificate.DeepChild(0, 6, 1, 0);
            //Get modulus and exponent from Document Signer public key
            var dsModPubKey = dsPubKey.Child(0, 0x02).Data; // modulus. 0x02 Verify that result is a INTEGER
            var dsExpPubKey = dsPubKey.Child(1, 0x02).Data; // exp. 0x02 Verify that result is a INTEGER

            //Verify SOD sign using DS public key and sign algoritm
            using (var rsa = new RSAService(dsModPubKey, dsExpPubKey))
            {
                var isValidSod = false;
                switch (OIDDSMessageDigestSignAlgo)
                {
                case "1.2.840.113549.1.1.5":
                    isValidSod = rsa.CheckSHA1withRSAEncryption(Signature.Data, SignatureAlgoritmIdentifier.MakeTag(0x31));
                    break;

                case "1.2.840.113549.1.1.10":
                    isValidSod = rsa.CheckRSASSAPSS(Signature.Data, SignatureAlgoritmIdentifier.MakeTag(0x31), digestAlgo);
                    break;

                default:
                    throw new Exception("Sign aloritm not supported");
                }
                if (!isValidSod)
                {
                    throw new Exception("SOD sign wrong"); //SOD sign wrong
                }
            }

            //Get issuer information from Document Signer certificate and compare it with data in IssuerName ASN1 tag
            var issuer = DSCertificate.DeepChild(0).Child(3, 0x30); //0x30 Verify that result is a SEQUENCE

            //Compare issuer information obtained from DS certificate with information stored directly in IssuerName tag
            if (issuer.Data.ToHexString() != IssuerName.Data.ToHexString())
            {
                return(false); //Issuer name check failed
            }
            //Get serial number information from Document Signer certificate and compare it with data in SignerCertSerialNumber ASN1 tag
            var serialNumber = DSCertificate.DeepChild(0).Child(1, 0x02); //02 Verify that result is a INTEGER

            if (serialNumber.Data.ToHexString() != SerialNumber.Data.ToHexString())
            {
                return(false); // Serial Number of certificate wrong
            }
            //Get hash of NIS and verify it with NIS stored in file system
            var dgsHash    = SignedData.Child(2, 0x30); //0x30 Verify that result is a SEQUENCE
            var isValidNis = false;

            foreach (var dg in dgsHash.children)
            {
                /*
                 * 0xa1 : IdServizi
                 * 0xa2 : Seriale carta
                 * 0xa3 : Certificato utente
                 * 0xa4 : Chiave pubblica di Internal Authentication
                 * 0xa5 : Chiave pubblica di Internal Authentication per i Servizi
                 * 0x1b : Parametri DH
                 */
                var oID = dg.Child(0, 02); //02 Verify that result is a INTEGER
                if (oID.Data.ToHexString() == "a1")
                {
                    //Get hashed NIS from DG
                    var hashedNis = dg.Child(1, 04).Data;  //04 Verify that result is a OCTECT STRING
                    //Calculate hash of file nis and compare it with the other in dg
                    if (hashedNis.ToHexString() == nis.ToMessageDigest(digestAlgo).ToHexString())
                    {
                        isValidNis = true;
                    }
                }
            }

            //TODO: Check that certificate is issued by https://csca-ita.interno.gov.it/index_ITA.htm (CSCA certificate)

            return(isValidNis);
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Verifies the signature.
 /// </summary>
 /// <param name="xDoc">The x document.</param>
 /// <param name="rsa">The RSA.</param>
 /// <returns></returns>
 public static bool VerifySignature(XmlDocument xDoc, RSAService rsa)
 {
     return(VerifySignature(xDoc, rsa.Provider));
 }
Ejemplo n.º 33
0
		public void TestReadPublicKeyFromPrivate_InputStream()
		{
			Console.Out.WriteLine("readPublicKeyFromPrivate");
			RSAService instance = new RSAService(keysize);
			using (FileStream instream = new FileStream(privateKeyfile, FileMode.Open))
			{
				RSAPublicKey result = instance.ReadPublicKeyFromPrivate(instream);
				Assert.IsNotNull(result);
			}
		}
Ejemplo n.º 34
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(input_d.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_dp.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_dq.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_exponent.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_inverseq.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_modulus.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_p.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;
            if (string.IsNullOrWhiteSpace(input_q.Text))
            {
                ShowErrorDoc2("Faltan Datos"); return;
            }
            ;

            RSAParameters P;

            try
            {
                P = new RSAParameters()
                {
                    D        = Convert.FromBase64String(input_d.Text),
                    DP       = Convert.FromBase64String(input_dp.Text),
                    DQ       = Convert.FromBase64String(input_dq.Text),
                    Exponent = Convert.FromBase64String(input_exponent.Text),
                    InverseQ = Convert.FromBase64String(input_inverseq.Text),
                    Modulus  = Convert.FromBase64String(input_modulus.Text),
                    P        = Convert.FromBase64String(input_p.Text),
                    Q        = Convert.FromBase64String(input_q.Text)
                };
            }
            catch (Exception)
            {
                ShowErrorDoc2("Datos Incorrectos");
                return;
            }

            if (!string.IsNullOrWhiteSpace(input_criptedFrase1.Text))
            {
                var r = RSAService.Decrypt(input_criptedFrase1.Text, P);
                if (r != null)
                {
                    output_Frase1.Text = new SICLib.Manager.StringBuilder(r).RemoveAsciiControllChars().GetString();
                }
                else
                {
                    output_Frase1.Text = "Error";
                }
            }
            else
            {
                output_Frase1.Text = "NULL";
            }

            if (!string.IsNullOrWhiteSpace(input_criptedFrase2.Text))
            {
                var r = RSAService.Decrypt(input_criptedFrase2.Text, P);
                if (r != null)
                {
                    output_Frase2.Text = new SICLib.Manager.StringBuilder(r).RemoveAsciiControllChars().GetString();
                }
                else
                {
                    output_Frase2.Text = "Error";
                }
            }
            else
            {
                output_Frase2.Text = "NULL";
            }

            if (!string.IsNullOrWhiteSpace(input_criptedFrase3.Text))
            {
                var r = RSAService.Decrypt(input_criptedFrase3.Text, P);
                if (r != null)
                {
                    output_Frase3.Text = new SICLib.Manager.StringBuilder(r).RemoveNoneAlphanumericChars().GetString();
                }
                else
                {
                    output_Frase3.Text = "Error";
                }
            }
            else
            {
                output_Frase3.Text = "NULL";
            }
        }
Ejemplo n.º 35
0
 public MockAcTokenValidator(RSAService rsa) : base(rsa)
 {
 }
Ejemplo n.º 36
0
 public FileVerifySignatureModel()
 {
     XmlService = new XmlService();
     RSAService = new RSAService();
 }
Ejemplo n.º 37
0
 public object Verify([FromBody] TokenModel tokens)
 {
     RSAService.rsa();
     return(authService.GetData(tokens.AccessToken));
 }