Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            var str = Encryptor.Encrypt("qwerty");

            Console.WriteLine(str);
            Console.WriteLine(Decryptor.Decrypt("BmwzQACRCmddGbSXdUJIGw=="));
        }
Ejemplo n.º 2
0
        public static ConnectionProperties GetConnectionProperties(IDictionary <string, string> propDictionary)
        {
            if (propDictionary == null)
            {
                throw new InvalidConnectionException("Connection Properties are NULL");
            }
            //capture props
            var connectorProps = new ConnectionProperties();

            connectorProps.BaseUrl  = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.BaseUrl, ConnectionPropertyLabels.BaseUrl);
            connectorProps.Username = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.Username, ConnectionPropertyLabels.Username);
            connectorProps.Password = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.Password, ConnectionPropertyLabels.Password);

            //tweak data coming in
            connectorProps.Password = Decryptor.Decrypt_AesManaged(connectorProps.Password, Connector.CryptoKey);
            if (connectorProps.BaseUrl.ToString().EndsWith("/"))
            {
                connectorProps.BaseUrl = connectorProps.BaseUrl.Remove(connectorProps.BaseUrl.Length - 1);
            }

            // re-check unencrypted password
            if (string.IsNullOrEmpty(connectorProps.Password))
            {
                throw new InvalidConnectionException(string.Format("A value is required for '{0}'", ConnectionPropertyLabels.Password));
            }

            return(connectorProps);
        }
Ejemplo n.º 3
0
        public string GetDecryptData(string Message)
        {
            try
            {
                System.Text.UTF8Encoding UTF8         = new System.Text.UTF8Encoding();
                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
                byte[] TDESKey;
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
                byte[]           DataToDecrypt;
                ICryptoTransform Decryptor;

                TDESKey               = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
                TDESAlgorithm.Key     = TDESKey;
                TDESAlgorithm.Mode    = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;
                DataToDecrypt         = Convert.FromBase64String(Message);

                try
                {
                    Decryptor = TDESAlgorithm.CreateDecryptor();
                    DeResults = null;
                    DeResults = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
                }
                catch (Exception)
                {
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }
                return(UTF8.GetString(DeResults));
            }
            catch (Exception)
            {
                return("F");
            }
        }
Ejemplo n.º 4
0
        public ActionResult Register(User user)
        {
            if (ModelState.IsValid)
            {
                var encrypt = Encryptor.Encrypt(user.Password);
                user.Password = encrypt;
                var db  = new UserDAO();
                var dao = db.Create(user);

                if (dao == 1)
                {
                    //nếu đăng kí thành công thì sẽ tự động đăg nhập
                    TempData["Success"] = "Thêm tài khoản thành công";
                    Login(user.Username, Decryptor.Decrypt(user.Password)); //gọi hàm login
                    return(RedirectToAction("Index", "Home"));
                }
                else if (dao == 0)
                {
                    TempData["Error"] = "Email này đã tồn tại";
                    return(View());
                }
                else if (dao == -1)
                {
                    TempData["Error"] = "Tài khoản này đã tồn tại";
                    return(View("Register"));
                }
                else
                {
                    ModelState.AddModelError("", "Thêm tài khoản thất bại");
                }
            }
            return(View());
        }
Ejemplo n.º 5
0
        public void GetFirstNumberNotEqualToNPrecedentTest()
        {
            var strings   = File.ReadLines(Program.InputTxt);
            var decryptor = new Decryptor(strings);

            decryptor.GetFirstNumberNotEqualToNPrecedent(25).Should().Be(167829540);
        }
Ejemplo n.º 6
0
        private string InternalDecrypt(byte[] encryptedBytes)
        {
            byte[] decrypted = null;
            decrypted = Decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);

            return(Encoding.ASCII.GetString(decrypted));
        }
Ejemplo n.º 7
0
        public void Decrypt_EncyptedByteArrayFromFCMService_ShouldSuccessfullyDecrypt()
        {
            // use this captured data for debugging
            ////// generated on the client - ECDH with curve prime256v1//////
            // random bytes
            var authSecret = new byte[] { 5, 47, 48, 155, 244, 31, 204, 235, 11, 247, 67, 120, 24, 137, 25, 153 };

            //// public key sent to the server
            var receiverPublicKeyBytes = new byte[] { 4, 234, 243, 178, 1, 91, 224, 122, 211, 185, 63, 90, 135, 90, 206, 224, 43, 63, 63, 131, 227, 22, 157, 108, 31, 176, 83, 27, 70, 246, 89, 112, 7, 102, 79, 42, 205, 17, 100, 100, 149, 198, 135, 95, 241, 189, 182, 61, 103, 161, 4, 244, 127, 185, 128, 18, 139, 78, 3, 169, 111, 218, 80, 73, 55 };

            //// private key kept on the client
            var privateKey = new byte[] { 250, 117, 42, 156, 20, 153, 20, 193, 233, 136, 185, 246, 56, 52, 250, 150, 120, 250, 72, 147, 182, 144, 120, 103, 76, 11, 175, 143, 92, 1, 177, 59 };

            //// received from the server
            var salt = new byte[] { 248, 70, 134, 75, 160, 188, 58, 83, 105, 238, 59, 171, 27, 115, 224, 200 };

            //// server public key
            var senderPublicKeyBytes = new byte[] { 4, 26, 9, 166, 16, 222, 177, 154, 230, 15, 231, 11, 89, 108, 66, 97, 247, 3, 158, 199, 93, 98, 187, 162, 175, 76, 127, 2, 149, 67, 13, 195, 26, 145, 46, 223, 4, 34, 46, 70, 57, 0, 98, 139, 79, 25, 84, 187, 176, 126, 50, 108, 192, 61, 207, 83, 248, 189, 14, 10, 182, 18, 141, 52, 92 };

            //// actual data that needs decoding
            var rawData = new byte[] { 127, 5, 92, 210, 222, 94, 48, 180, 122, 71, 186, 120, 91, 171, 10, 6, 14, 182, 145, 108, 136, 161, 172, 8, 67, 27, 136, 55, 6, 224, 180, 181, 141, 242, 21, 101, 235, 6, 125, 162, 97, 236, 49, 150, 61, 225, 130, 58, 57, 93, 37, 79, 208, 21, 8, 139, 72, 235, 12, 173, 50 };

            var decryptor      = new Decryptor(privateKey, receiverPublicKeyBytes, authSecret);
            var decryptedBytes = decryptor.Decrypt(rawData, senderPublicKeyBytes, salt);
            var result         = Encoding.UTF8.GetString(decryptedBytes);

            Assert.AreEqual("{\"from\":\"550920961559\",\"priority\":\"normal\"}", result);
        }
			public void DecryptsToOriginalPlainText()
			{
				byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least. This is a test! It needs to be 128 characters long at least.");
				byte[] decryptedBytes;

				using (SymmetricAlgorithm algorithm = new AesManaged())
				{
					byte[] wrongDecryptionKey = algorithm.Key;

					algorithm.GenerateKey();

					byte[] encryptionKey = algorithm.Key;

					Assert.AreNotEqual(encryptionKey, wrongDecryptionKey);

					byte[] ciphertextBytes, iv;
					using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv))
					{
						Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key);
						Assert.AreEqual(iv, encryptor.Algorithm.IV);

						ciphertextBytes = encryptor.Encrypt(plaintextBytes);
					}

					using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions))
					{
						Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key);
						Assert.AreEqual(iv, decryptor.Algorithm.IV);

						decryptedBytes = decryptor.Decrypt(ciphertextBytes);
					}
				}

				Assert.AreEqual(plaintextBytes, decryptedBytes);
			}
Ejemplo n.º 9
0
        /// <summary>
        /// Decryptor
        ///
        /// <param name="text">Base64 string to be decrypted
        /// <returns>
        public string Decrypt(string text)
        {
            try
            {
                if (string.IsNullOrEmpty(text))
                {
                    return(null);
                }

                //text = text.Replace(" ", "");
                byte[] input = Convert.FromBase64String(text);

                var newClearData = Decryptor.TransformFinalBlock(input, 0, input.Length);
                return(Encoding.ASCII.GetString(newClearData));
            }
            catch (ArgumentException ae)
            {
                Console.WriteLine("inputCount uses an invalid value or inputBuffer has an invalid offset length. " + ae);
                return(null);
            }
            catch (ObjectDisposedException oe)
            {
                Console.WriteLine("The object has already been disposed." + oe);
                return(null);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Decrypts a string.
        /// </summary>
        /// <param name="Text">The encrypted string to be decrypted.</param>
        /// <param name="Key">The 8-bit string for decryption.</param>
        /// <returns>The plain text.</returns>
        public string Decrypt(string Text, string Key)
        {
            if(Key.Length != 8)
                throw new Exception("Key must be a 8-bit string!");

            byte[] IV = null;
            byte[] cipherText = null;
            byte[] key = null;
            byte[] plainText = null;

            try
            {
                Decryptor dec = new Decryptor(EncryptionAlgorithm.Des);

                IV = Encoding.ASCII.GetBytes("init vec");		// "init vec is big."

                dec.IV = IV;

                key = Encoding.ASCII.GetBytes(Key);
                cipherText = Convert.FromBase64String(Text);

                plainText = dec.Decrypt(cipherText, key);
            }
            catch(Exception ex)
            {
                throw new Exception("Exception while decrypting. " + ex.Message);
            }

            return Encoding.ASCII.GetString(plainText);
        }
        public ActionResult ChangePassword(UserModel userModel)
        {
            UserDAO db = new UserDAO();

            if (ModelState.IsValid)
            {
                var user = db.GetUserString(userModel.Username);
                if (user != null)
                {
                    if (Decryptor.Decrypt(user.Password) == userModel.Password)              //nếu đúng pass của tài khoản mới cập nhập
                    {
                        db.UpdatePass(user.Email, Encryptor.Encrypt(userModel.NewPassword)); //Hàm cập nhập mật khẩu
                        TempData["Success"] = "Đổi mật khẩu thành công";
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        TempData["Error"] = "Mật khẩu cũ không tồn tại";
                        return(View());
                    }
                }
            }
            TempData["Error"] = "Đổi mật khẩu thất bại";
            return(View());
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Constructor for MainWindow
        /// </summary>
        public MainWindow()
        {
            // Initialize in background thread
            Task.Run(() =>
            {
                KeyGenerator keygen = new KeyGenerator(GlobalProperties.Context);

                encryptor_ = new Encryptor(GlobalProperties.Context, keygen.PublicKey);
                decryptor_ = new Decryptor(GlobalProperties.Context, keygen.SecretKey);
                encoder_   = new BatchEncoder(GlobalProperties.Context);

                rlk_ = keygen.RelinKeys(decompositionBitCount: GlobalProperties.RelinKeysDBC);

                List <int> rotCounts = new List <int>();
                for (int i = (int)encoder_.SlotCount / GlobalProperties.MatrixSizeMax; i < (int)encoder_.SlotCount / 2; i *= 2)
                {
                    rotCounts.Add(i);
                }
                rotCounts.Add(0);
                galk_ = keygen.GaloisKeys(decompositionBitCount: GlobalProperties.GaloisKeysDBC, steps: rotCounts);

                // Choose the Session ID
                RandomizeSID();
            });

            InitializeComponent();
        }
Ejemplo n.º 13
0
        internal static byte[] DecryptByKey(byte[] encryptedPassword, byte[] initializationVector, byte[] passwordKey)
        {
            var dec = new Decryptor(ENCRYPTION_ALGORITHM);

            dec.IV = initializationVector;
            return(dec.Decrypt(encryptedPassword, passwordKey));
        }
Ejemplo n.º 14
0
        private string DecryptSignature(string js, string signature)
        {
            var functionLines = GetDecryptionFunctionLines(js);

            var decryptor = new Decryptor();

            foreach (var functionLine in functionLines)
            {
                if (decryptor.IsComplete)
                {
                    break;
                }

                var match = FunctionRegex.Match(functionLine);
                if (match.Success)
                {
                    decryptor.AddFunction(js, match.Groups[1].Value);
                }
            }

            foreach (var functionLine in functionLines)
            {
                var match = FunctionRegex.Match(functionLine);
                if (match.Success)
                {
                    signature = decryptor.ExecuteFunction(signature, functionLine, match.Groups[1].Value);
                }
            }

            return(signature);
        }
Ejemplo n.º 15
0
 /// <summary>Return decryptor to pool</summary>
 private void ReturnDecryptor(Decryptor decryptor)
 {
     if (decryptor != null)
     {
         decryptorPool.AddItem(decryptor);
     }
 }
Ejemplo n.º 16
0
        public string Decrypt(string Parameter)
        {
            Decryptor Decry = new Decryptor(EncryptionAlgorithm.TripleDes);

            Decry.IV = Encoding.ASCII.GetBytes("t3ilc0m3");
            return(Decry.Decrypt(Parameter, "3wmotherwdrtybnio12ewq23"));
        }
Ejemplo n.º 17
0
        public void TestAgileEncryptionModes()
        {
            int maxKeyLen = Cipher.GetMaxAllowedKeyLength(ca.jceId);

            Assume.That(maxKeyLen >= ca.defaultKeySize, "Please install JCE Unlimited Strength Jurisdiction Policy files");

            MemoryStream bos = new MemoryStream();

            POIFSFileSystem fsEnc   = new POIFSFileSystem();
            EncryptionInfo  infoEnc = new EncryptionInfo(EncryptionMode.Agile, ca, ha, -1, -1, cm);
            Encryptor       enc     = infoEnc.Encryptor;

            enc.ConfirmPassword("foobaa");
            Stream os = enc.GetDataStream(fsEnc);

            os.Write(testData, 0, testData.Length);
            os.Close();
            //bos.Reset();
            bos.Seek(0, SeekOrigin.Begin);
            fsEnc.WriteFileSystem(bos);

            POIFSFileSystem fsDec   = new POIFSFileSystem(new MemoryStream(bos.ToArray()));
            EncryptionInfo  infoDec = new EncryptionInfo(fsDec);
            Decryptor       dec     = infoDec.Decryptor;
            bool            passed  = dec.VerifyPassword("foobaa");

            Assert.IsTrue(passed);
            Stream is1 = dec.GetDataStream(fsDec);

            byte[] actualData = IOUtils.ToByteArray(is1);
            is1.Close();
            //assertThat("Failed roundtrip - " + ca + "-" + ha + "-" + cm, testData, EqualTo(actualData));
            Assert.That(testData, Is.EqualTo(actualData), "Failed roundtrip - " + ca + "-" + ha + "-" + cm);
        }
Ejemplo n.º 18
0
        /// <summary>Calculate the counter and iv, update the decryptor.</summary>
        /// <exception cref="System.IO.IOException"/>
        private void UpdateDecryptor(Decryptor decryptor, long position, byte[] iv)
        {
            long counter = GetCounter(position);

            codec.CalculateIV(initIV, counter, iv);
            decryptor.Init(key, iv);
        }
Ejemplo n.º 19
0
        public void InPlaceReWrite()
        {
            FileInfo f = TempFile.CreateTempFile("protected_agile", ".docx");
            // File f = new File("protected_agile.docx");
            FileStream fos = f.Create();
            Stream     fis = POIDataSamples.GetPOIFSInstance().OpenResourceAsStream("protected_agile.docx");

            IOUtils.Copy(fis, fos);
            fis.Close();
            fos.Close();

            NPOIFSFileSystem fs = new NPOIFSFileSystem(f, false);

            // decrypt the protected file - in this case it was encrypted with the default password
            EncryptionInfo encInfo = new EncryptionInfo(fs);
            Decryptor      d       = encInfo.Decryptor;
            bool           b       = d.VerifyPassword(Decryptor.DEFAULT_PASSWORD);

            Assert.IsTrue(b);

            // do some strange things with it ;)
            XWPFDocument docx = new XWPFDocument(d.GetDataStream(fs));

            docx.GetParagraphArray(0).InsertNewRun(0).SetText("POI was here! All your base are belong to us!");
            docx.GetParagraphArray(0).InsertNewRun(1).AddBreak();

            // and encrypt it again
            Encryptor e = encInfo.Encryptor;

            e.ConfirmPassword("AYBABTU");
            docx.Write(e.GetDataStream(fs));

            fs.Close();
        }
Ejemplo n.º 20
0
        // Get cookies from gecko browser
        public static List <Site> Get(string BrowserDir)
        {
            List <Site> scHistory = new List <Site>();
            // Get firefox default profile directory
            string profile = Profile.GetProfile(BrowserDir);

            // Read cookies from file
            if (profile == null)
            {
                return(scHistory);
            }
            string db_location = Path.Combine(profile, "places.sqlite");
            // Read data from table
            SQLite sSQLite = SQLite.ReadTable(db_location, "moz_places");

            if (sSQLite == null)
            {
                return(scHistory);
            }
            // Get values from table
            for (int i = 0; i < sSQLite.GetRowCount(); i++)
            {
                Site sSite = new Site();
                sSite.sUrl   = Decryptor.GetUTF8(sSQLite.GetValue(i, 1));
                sSite.sTitle = Decryptor.GetUTF8(sSQLite.GetValue(i, 2));
                sSite.iCount = Convert.ToInt32(sSQLite.GetValue(i, 4)) + 1;

                if (sSite.sTitle != "0")
                {
                    scHistory.Add(sSite);
                }
            }

            return(scHistory);
        }
Ejemplo n.º 21
0
        private bool TryFindEristaKeyRevision()
        {
            // Package1 has no indication of which key it's encrypted with,
            // so we must test each known key to find one that works

            var decHeader = new Package1Pk11Header();

            int       start     = IsModern ? 6 : 0;
            int       end       = IsModern ? 0x20 : 6;
            Decryptor decryptor = IsModern ? Crypto.Aes.DecryptCbc128 : (Decryptor)Crypto.Aes.DecryptCtr128;

            for (int i = start; i < end; i++)
            {
                decryptor(SpanHelpers.AsByteSpan(ref _pk11Header), SpanHelpers.AsByteSpan(ref decHeader),
                          KeySet.Package1Keys[i], _stage1Footer.Iv);

                if (decHeader.Magic == Package1Pk11Header.ExpectedMagic)
                {
                    KeyRevision = (byte)i;
                    _pk11Header = decHeader;
                    return(true);
                }
            }

            return(false);
        }
Ejemplo n.º 22
0
        public void Create2Test()
        {
            SEALContext  context = GlobalContext.BFVContext;
            KeyGenerator keygen1 = new KeyGenerator(context);

            keygen1.CreatePublicKey(out PublicKey publicKey);

            Encryptor encryptor1 = new Encryptor(context, publicKey);
            Decryptor decryptor1 = new Decryptor(context, keygen1.SecretKey);

            Ciphertext cipher = new Ciphertext();
            Plaintext  plain  = new Plaintext("2x^1 + 5");
            Plaintext  plain2 = new Plaintext();

            encryptor1.Encrypt(plain, cipher);
            decryptor1.Decrypt(cipher, plain2);

            Assert.AreNotSame(plain, plain2);
            Assert.AreEqual(plain, plain2);

            KeyGenerator keygen2 = new KeyGenerator(context, keygen1.SecretKey);

            keygen2.CreatePublicKey(out publicKey);
            Encryptor encryptor2 = new Encryptor(context, publicKey);
            Decryptor decryptor2 = new Decryptor(context, keygen2.SecretKey);

            Plaintext plain3 = new Plaintext();

            decryptor2.Decrypt(cipher, plain3);

            Assert.AreNotSame(plain, plain3);
            Assert.AreEqual(plain, plain3);
        }
Ejemplo n.º 23
0
        private void performDecryptionTest(string functionName, string encrypted, string expected, string password)
        {
            Decryptor cryptor   = new Decryptor();
            string    decrypted = cryptor.Decrypt(encrypted, password);

            this.reportSuccess(functionName, decrypted == expected);
        }
Ejemplo n.º 24
0
        private void testDecryptingWithBadPasswordFails()
        {
            Decryptor cryptor   = new Decryptor();
            string    decrypted = cryptor.Decrypt(TestStrings.IOS_ENCRYPTED_V2_NON_BLOCK_INTERVAL, "bad-password");

            this.reportSuccess(MethodBase.GetCurrentMethod().Name, decrypted == "");
        }
Ejemplo n.º 25
0
        private string DecryptSignature(string js, string signature)
        {
            var functionLines = GetDecryptionFunctionLines(js);
            var decryptor     = new Decryptor();

            foreach (var functionLine in functionLines)
            {
                if (decryptor.IsComplete)
                {
                    break;
                }
                /* Pass  TK["do"](a, 36); or TK.BH(a, 1); */
                var match = FunctionRegex.Match(functionLine.Replace("[\"", ".").Replace("\"]", ""));
                if (match.Success)
                {
                    decryptor.AddFunction(js, match.Groups[1].Value);
                }
            }

            foreach (var functionLine in functionLines)
            {
                var match = FunctionRegex.Match(functionLine.Replace("[\"", ".").Replace("\"]", ""));
                if (match.Success)
                {
                    signature = decryptor.ExecuteFunction(signature, functionLine, match.Groups[1].Value);
                }
            }

            return(signature);
        }
Ejemplo n.º 26
0
        public void Connect(IDictionary <string, string> propDictionary)
        {
            if (propDictionary == null)
            {
                throw new InvalidConnectionException("Connection Properties are NULL");
            }

            //capture properties from form
            var connectorProps = new ConnectionProperties();

            connectorProps.BaseUrl    = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.BaseUrl, ConnectionPropertyLabels.BaseUrl);
            connectorProps.Username   = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.Username, ConnectionPropertyLabels.Username);
            connectorProps.Password   = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.Password, ConnectionPropertyLabels.Password);
            connectorProps.CustomerId = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.CustomerId, ConnectionPropertyLabels.CustomderId);
            connectorProps.HMAC       = getRequiredPropertyValue(propDictionary, ConnectionPropertyKeys.HMAC, ConnectionPropertyLabels.HMAC);

            //remove extra slash for consistency
            if (connectorProps.BaseUrl.ToString().EndsWith("/"))
            {
                connectorProps.BaseUrl = connectorProps.BaseUrl.Remove(connectorProps.BaseUrl.Length - 1);
            }

            //decrypt password value for later
            connectorProps.Password = Decryptor.Decrypt_AesManaged(connectorProps.Password, Connector.CryptoKey);

            // re-check unencrypted password
            if (string.IsNullOrEmpty(connectorProps.Password))
            {
                throw new InvalidConnectionException(string.Format("A value is required for '{0}'", ConnectionPropertyLabels.Password));
            }

            properties  = connectorProps;
            reflector   = new Reflector(Assembly.GetExecutingAssembly());
            IsConnected = true;
        }
        static public List <List <long> > decryptValues(List <List <Ciphertext> > weihtedSums, SecretKey sk, SEALContext context)
        {
            List <List <long> > results = new List <List <long> >();

            Decryptor      decryptor = new Decryptor(context, sk);
            IntegerEncoder encoder   = new IntegerEncoder(context);

            int sample_ind = 0;

            foreach (List <Ciphertext> sample in weihtedSums)
            {
                List <long> resultsRow = new List <long>();
                foreach (Ciphertext encryptedClassScore in sample)
                {
                    Plaintext plainClassScore = new Plaintext();

                    if (decryptor.InvariantNoiseBudget(encryptedClassScore) == 0)
                    {
                        throw new Exception("Noise budget depleated in sample " + sample_ind + ". Aborting...");
                    }
                    decryptor.Decrypt(encryptedClassScore, plainClassScore);
                    long ClassScore = encoder.DecodeInt64(plainClassScore) / (1000 * 1000);

                    resultsRow.Add(ClassScore);
                }
                results.Add(resultsRow);
                sample_ind++;
            }

            return(results);
        }
Ejemplo n.º 28
0
        /// <summary>Decrypt length bytes in buffer starting at offset.</summary>
        /// <remarks>
        /// Decrypt length bytes in buffer starting at offset. Output is also put
        /// into buffer starting at offset. It is thread-safe.
        /// </remarks>
        /// <exception cref="System.IO.IOException"/>
        private void Decrypt(long position, byte[] buffer, int offset, int length)
        {
            ByteBuffer inBuffer  = GetBuffer();
            ByteBuffer outBuffer = GetBuffer();
            Decryptor  decryptor = null;

            try
            {
                decryptor = GetDecryptor();
                byte[] iv = initIV.MemberwiseClone();
                UpdateDecryptor(decryptor, position, iv);
                byte padding = GetPadding(position);
                inBuffer.Position(padding);
                // Set proper position for input data.
                int n = 0;
                while (n < length)
                {
                    int toDecrypt = Math.Min(length - n, inBuffer.Remaining());
                    inBuffer.Put(buffer, offset + n, toDecrypt);
                    // Do decryption
                    Decrypt(decryptor, inBuffer, outBuffer, padding);
                    outBuffer.Get(buffer, offset + n, toDecrypt);
                    n      += toDecrypt;
                    padding = AfterDecryption(decryptor, inBuffer, position + n, iv);
                }
            }
            finally
            {
                ReturnBuffer(inBuffer);
                ReturnBuffer(outBuffer);
                ReturnDecryptor(decryptor);
            }
        }
            /// <exception cref="System.IO.IOException"/>
            /// <exception cref="GeneralSecurityException"/>
            public virtual KeyProvider.KeyVersion DecryptEncryptedKey(KeyProviderCryptoExtension.EncryptedKeyVersion
                                                                      encryptedKeyVersion)
            {
                // Fetch the encryption key material
                string encryptionKeyVersionName = encryptedKeyVersion.GetEncryptionKeyVersionName
                                                      ();

                KeyProvider.KeyVersion encryptionKey = keyProvider.GetKeyVersion(encryptionKeyVersionName
                                                                                 );
                Preconditions.CheckNotNull(encryptionKey, "KeyVersion name '%s' does not exist",
                                           encryptionKeyVersionName);
                Preconditions.CheckArgument(encryptedKeyVersion.GetEncryptedKeyVersion().GetVersionName
                                                ().Equals(KeyProviderCryptoExtension.Eek), "encryptedKey version name must be '%s', is '%s'"
                                            , KeyProviderCryptoExtension.Eek, encryptedKeyVersion.GetEncryptedKeyVersion().GetVersionName
                                                ());
                // Encryption key IV is determined from encrypted key's IV
                byte[] encryptionIV = KeyProviderCryptoExtension.EncryptedKeyVersion.DeriveIV(encryptedKeyVersion
                                                                                              .GetEncryptedKeyIv());
                CryptoCodec cc        = CryptoCodec.GetInstance(keyProvider.GetConf());
                Decryptor   decryptor = cc.CreateDecryptor();

                decryptor.Init(encryptionKey.GetMaterial(), encryptionIV);
                KeyProvider.KeyVersion encryptedKV = encryptedKeyVersion.GetEncryptedKeyVersion();
                int        keyLen = encryptedKV.GetMaterial().Length;
                ByteBuffer bbIn   = ByteBuffer.AllocateDirect(keyLen);
                ByteBuffer bbOut  = ByteBuffer.AllocateDirect(keyLen);

                bbIn.Put(encryptedKV.GetMaterial());
                bbIn.Flip();
                decryptor.Decrypt(bbIn, bbOut);
                bbOut.Flip();
                byte[] decryptedKey = new byte[keyLen];
                bbOut.Get(decryptedKey);
                return(new KeyProvider.KeyVersion(encryptionKey.GetName(), Ek, decryptedKey));
            }
Ejemplo n.º 30
0
        // Get cookies from gecko browser
        public static List <Bookmark> Get(string BrowserDir)
        {
            List <Bookmark> scBookmark = new List <Bookmark>();
            // Get firefox default profile directory
            string profile = Profile.GetProfile(BrowserDir);

            // Read cookies from file
            if (profile == null)
            {
                return(scBookmark);
            }
            string db_location = Path.Combine(profile, "places.sqlite");
            // Read data from table
            SQLite sSQLite = SQLite.ReadTable(db_location, "moz_bookmarks");

            if (sSQLite == null)
            {
                return(scBookmark);
            }
            // Get values from table
            for (int i = 0; i < sSQLite.GetRowCount(); i++)
            {
                Bookmark bBookmark = new Bookmark();
                bBookmark.sTitle = Decryptor.GetUTF8(sSQLite.GetValue(i, 5));

                if (Decryptor.GetUTF8(sSQLite.GetValue(i, 1)).Equals("0") && bBookmark.sTitle != "0")
                {
                    scBookmark.Add(bBookmark);
                }
            }

            return(scBookmark);
        }
Ejemplo n.º 31
0
 public ResultHandler(Decryptor decryptor, ILogger <ResultHandler> logger, BlobFileService blobFileService, IConfiguration configuration)
 {
     _decryptor       = decryptor;
     _logger          = logger;
     _blobFileService = blobFileService;
     _configuration   = configuration;
 }
Ejemplo n.º 32
0
        public bool IsIn(Position searchPosition)
        {
            var encoded   = GetEncodedPosition(searchPosition);
            var evaluator = new Evaluator(GetContext());

            PositionEncrypted positionEncrypted = GetFromIota();

            evaluator.SubPlain(positionEncrypted.Lon, encoded.Lon);
            evaluator.SubPlain(positionEncrypted.Lat, encoded.Lat);

            var decryptor = new Decryptor(GetContext(), GetSecretKey());

            Plaintext plainResultLon = new Plaintext();
            Plaintext plainResultLat = new Plaintext();

            decryptor.Decrypt(positionEncrypted.Lon, plainResultLon);
            decryptor.Decrypt(positionEncrypted.Lat, plainResultLat);

            var    encoder   = GetEncoder(GetContext());
            double resultLon = encoder.Decode(plainResultLon);
            double resultLat = encoder.Decode(plainResultLat);

            var diff = Math.Abs(resultLon) + Math.Abs(resultLat);

            if (diff < 0.007)
            {
                return(true);
            }

            return(false);
        }
Ejemplo n.º 33
0
        private void performDecryptionTest(string functionName, string encrypted, string expected, string password)
        {
            Decryptor cryptor = new Decryptor();
            string decrypted = cryptor.Decrypt(encrypted, password);

            this.reportSuccess(functionName, decrypted == expected);
        }
        protected override void Context()
        {
            base.Context();

              TestType = new SaltedEncryptedString();
              Decryptor = new CryptographyFactory().CreateDecryptor();

              CurrentSession.Save(UnpersistedEntity);
        }
			public void CausesDecryptionToReturnNonsense()
			{
				byte[] plaintextBytes = Encoding.UTF8.GetBytes("This is a test!");
				byte[] decryptedBytes, decryptedBytesFromWrongKey = null;

				using (SymmetricAlgorithm algorithm = new AesManaged())
				{
					byte[] wrongDecryptionKey = algorithm.Key;

					algorithm.GenerateKey();

					byte[] encryptionKey = algorithm.Key;

					Assert.AreNotEqual(encryptionKey, wrongDecryptionKey);

					byte[] ciphertextBytes, iv;
					using (Encryptor encryptor = algorithm.CreateEncryptor(encryptionKey, out iv))
					{
						Assert.AreEqual(encryptionKey, encryptor.Algorithm.Key);
						Assert.AreEqual(iv, encryptor.Algorithm.IV);

						ciphertextBytes = encryptor.Encrypt(plaintextBytes);
					}

					using (Decryptor decryptorWithWrongKey = new Decryptor(algorithm, wrongDecryptionKey, iv, Encryption.DefaultOptions))
					{
						Assert.AreEqual(wrongDecryptionKey, decryptorWithWrongKey.Algorithm.Key);
						Assert.AreEqual(iv, decryptorWithWrongKey.Algorithm.IV);

						try
						{
							decryptedBytesFromWrongKey = decryptorWithWrongKey.Decrypt(ciphertextBytes);
						}
						catch (CryptographicException e)
						{
							// "Padding is invalid and cannot be removed."
							Assert.IsNull(decryptedBytesFromWrongKey);

							Console.WriteLine(e.Message);
						}
					}

					using (Decryptor decryptor = new Decryptor(algorithm, encryptionKey, iv, Encryption.DefaultOptions))
					{
						Assert.AreEqual(encryptionKey, decryptor.Algorithm.Key);
						Assert.AreEqual(iv, decryptor.Algorithm.IV);

						decryptedBytes = decryptor.Decrypt(ciphertextBytes);
					}
				}

				Assert.AreNotEqual(decryptedBytes, decryptedBytesFromWrongKey);
				Assert.AreEqual(plaintextBytes, decryptedBytes);
			}
Ejemplo n.º 36
0
        private void performSymmetricTest(string functionName, string plaintext, string password)
        {
            Encryptor encryptor = new Encryptor();
            string encryptedB64 = encryptor.Encrypt(plaintext, password);

            Decryptor decryptor = new Decryptor();
            string decrypted = decryptor.Decrypt(encryptedB64, password);

            this.reportSuccess(functionName, decrypted == plaintext);
        }
Ejemplo n.º 37
0
        private void performSymmetricTestWithExplicitSchema(string functionName, string plaintext, string password, Schema schemaVersion)
        {
            Encryptor encryptor = new Encryptor();
            string encryptedB64 = encryptor.Encrypt(plaintext, password, schemaVersion);

            Decryptor decryptor = new Decryptor();
            string decrypted = decryptor.Decrypt(encryptedB64, password);

            this.reportSuccess(functionName, decrypted == plaintext);
        }
Ejemplo n.º 38
0
        private void testCannotUseWithUnsupportedSchemaVersions()
        {
            Encryptor encryptor = new Encryptor();
            string encryptedB64 = encryptor.Encrypt(TestStrings.SAMPLE_PLAINTEXT, TestStrings.SAMPLE_PASSWORD_A);

            byte[] encrypted = Convert.FromBase64String(encryptedB64);
            encrypted[0] = 0x03;
            string encryptedV3 = Convert.ToBase64String(encrypted);

            Decryptor decryptor = new Decryptor();
            string decrypted = decryptor.Decrypt(encryptedV3, TestStrings.SAMPLE_PASSWORD_A);

            this.reportSuccess(MethodBase.GetCurrentMethod().Name, decrypted == "");
        }
Ejemplo n.º 39
0
        private void testDecryptingWithBadPasswordFails()
        {
            Decryptor cryptor = new Decryptor();
            string decrypted = cryptor.Decrypt(TestStrings.IOS_ENCRYPTED_V2_NON_BLOCK_INTERVAL, "bad-password");

            this.reportSuccess(MethodBase.GetCurrentMethod().Name, decrypted == "");
        }
Ejemplo n.º 40
0
 /// <summary> Wraps the stream with a cryptographic stream </summary>
 public sealed override Stream Decrypt(Stream stream)
 {
     try
     {
         ICryptoTransform xform = new Decryptor(this, TransformSize, BlockSize);
         return new DisposingStream(new CryptoStream(stream, xform, CryptoStreamMode.Read))
             .WithDisposeOf(xform);
     }
     catch (InvalidOperationException) { throw; }
     catch { throw CryptographicException(); }
 }