Exemple #1
0
        protected override void Execute(CodeActivityContext context)
        {
            var key        = Key.Get(context);
            var iv         = IV.Get(context);
            var cipherText = CipherText.Get(context);

            if (cipherText == null || cipherText.Length <= 0)
            {
                throw new ArgumentNullException("cipherText");
            }
            if (key == null || key.Length <= 0)
            {
                throw new ArgumentNullException("key");
            }

            string plaintext = null;

            using (AesManaged aes = new AesManaged())
            {
                ICryptoTransform decryptor = aes.CreateDecryptor(Encoding.UTF8.GetBytes(key), Encoding.UTF8.GetBytes(iv));
                using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(cipherText)))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader reader = new StreamReader(cs))
                            plaintext = reader.ReadToEnd();
                    }
                }
            }
            PlainText.Set(context, plaintext);
        }
        //Método de evento para o clique no botão "Descriptografar"
        private void Decrypt_Click(object sender, EventArgs e)
        {
            this.Encrypt.Enabled = true;
            control = true;
            //Verifica se a caixa do texto cifrado não está vazia
            if (cipher.Length != 0)
            {
                //O texto descriptografado é enviado para uma string
                string plain = AES.Decrypt(cipher, key, iv);

                //A caixa de texto recebe o texto descriptografado que está na string
                CipherText.Text = plain;

                //Desativa o botão "Descriptografar"
                this.Decrypt.Enabled = false;
            }
            else
            {
                MessageBox.Show("criptografe algo para poder descriptografar!", "Caixa de texto vazia!",
                                MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                CipherText.Clear();
                plain_text.Clear();

                plain_text.Focus();
            }
        }
Exemple #3
0
        /// <summary>
        /// May I have a new command that wraps and encrypts an inner command, to be transmitted securely?
        /// </summary>
        /// <param name="parent">The parent-station sending the command.</param>
        /// <param name="to">The address of the recipient.</param>
        /// <param name="innerCommand">The command to be wrapped.</param>
        public CryptoCommand(Station parent, IPEndPoint to, ICommand innerCommand)
        {
            Contract.Requires(parent != null);
            Contract.Requires(to != null);
            Contract.Requires(innerCommand != null);

            Sender = parent.Address;
            var crypto = parent.Crypto;

            var cmdBytes     = Bytes.From(innerCommand);
            var symmetricKey = crypto.GenerateSymmetricKey();

            crypto.NewIv();

            var symmetricallyEncryptedCmdBytes = crypto.SymmetricEncrypt(cmdBytes, new SymmetricKey(symmetricKey));

            var targetKey    = parent.IsManager && to.Equals(parent.Address) ? parent.Crypto.Keys.Item1 : parent.Peers[to];
            var asymKeyBytes = crypto.AsymmetricEncrypt(symmetricKey, new AsymmetricKey(targetKey));

            var senderHashBytes = crypto.AsymmetricEncrypt(crypto.Hash(cmdBytes), new AsymmetricKey(crypto.Keys.Item2));

            var symmetricKeyCipher = new CipherText(asymKeyBytes);
            var commandCipher      = new CipherText(symmetricallyEncryptedCmdBytes);
            var senderHash         = new CipherText(senderHashBytes);
            var iv = crypto.Iv;

            _content = new Message(symmetricKeyCipher, commandCipher, senderHash, iv);
        }
Exemple #4
0
        public void TestToString()
        {
            var testSubject = new CipherText
            {
                adata  = "atada",
                cipher = "rehpic",
                ct     = "tc",
                iter   = 1000,
                iv     = "vi",
                ks     = 1000,
                mode   = "edom",
                v      = 1,
                salt   = "tlas",
                ts     = 1
            };
            var testResult = testSubject.ToString();

            Assert.IsNotNull(testResult);
            Assert.IsFalse(String.IsNullOrWhiteSpace(testResult));

            Assert.IsTrue(testResult.Contains(string.Format("\"adata\":\"{0}\"", testSubject.adata)));
            Assert.IsTrue(testResult.Contains(string.Format("\"cipher\":\"{0}\"", testSubject.cipher)));
            Assert.IsTrue(testResult.Contains(string.Format("\"ct\":\"{0}\"", testSubject.ct)));
            Assert.IsTrue(testResult.Contains(string.Format("\"iter\":{0}", testSubject.iter)));
            Assert.IsTrue(testResult.Contains(string.Format("\"iv\":\"{0}\"", testSubject.iv)));
            Assert.IsTrue(testResult.Contains(string.Format("\"ks\":{0}", testSubject.ks)));
            Assert.IsTrue(testResult.Contains(string.Format("\"mode\":\"{0}\"", testSubject.mode)));
            Assert.IsTrue(testResult.Contains(string.Format("\"v\":{0}", testSubject.v)));
            Assert.IsTrue(testResult.Contains(string.Format("\"salt\":\"{0}\"", testSubject.salt)));
            Assert.IsTrue(testResult.Contains(string.Format("\"ts\":{0}", testSubject.ts)));
        }
Exemple #5
0
        public void TestTryParse()
        {
            var testValues = new CipherText
            {
                adata  = "atada",
                cipher = "rehpic",
                ct     = "tc",
                iter   = 1000,
                iv     = "vi",
                ks     = 1000,
                mode   = "edom",
                v      = 1,
                salt   = "tlas",
                ts     = 1
            };
            var toStringBuilder = new StringBuilder();

            toStringBuilder.Append("{");
            toStringBuilder.Append(string.Format("\"adata\":\"{0}\",", testValues.adata));
            toStringBuilder.Append(string.Format("\"cipher\":\"{0}\",", testValues.cipher));
            toStringBuilder.Append(string.Format("\"iter\":{0},", testValues.iter));
            toStringBuilder.Append(string.Format("\"iv\":\"{0}\",", testValues.iv));
            toStringBuilder.Append(string.Format("\"ks\":{0},", testValues.ks));
            toStringBuilder.Append(string.Format("\"mode\":\"{0}\",", testValues.mode));
            toStringBuilder.Append(string.Format("\"v\":{0},", testValues.v));
            toStringBuilder.Append(string.Format("\"salt\":\"{0}\",", testValues.salt));
            toStringBuilder.Append(string.Format("\"ts\":{0},", testValues.ts));
            toStringBuilder.Append(string.Format("\"ct\":\"{0}\"", testValues.ct));
            toStringBuilder.Append("}");

            CipherText testSubject;
            var        testResult = CipherText.TryParse(toStringBuilder.ToString(), out testSubject);

            Assert.IsTrue(testResult);
        }
Exemple #6
0
 public override string ToString()
 {
     return(String.Format("{0}.{1}.{2}.{3}.{4}", Header.ToBase64String(),
                          EncryptedMasterKey.ToBase64String(),
                          InitializationVector.ToBase64String(),
                          CipherText.ToBase64String(),
                          Tag.ToBase64String()));
 }
Exemple #7
0
 public byte[] SymmetricDecrypt(CipherText cipher, SymmetricKey symmetricKey)
 {
     _cipher.Init(
         false,
         new ParametersWithIV(
             new KeyParameter(symmetricKey), Iv));
     return(_cipher.DoFinal(cipher));
 }
        public void ReverseMessage(string message)
        {
            CipherText del = ShiftUpCharacters;

            char[] reversedMsg = del(message).ToCharArray();
            Array.Reverse(reversedMsg);
            Console.WriteLine(reversedMsg);
        }
Exemple #9
0
        /*
         * /// <summary>
         * ///   The cpr test.
         * /// </summary>
         * [Test] public void CPRTest() {
         * var cpr = new CPR(2312881133);
         * Assert.That(cpr.Value == 2312881133);
         * Assert.That(cpr.ToString().Equals("2312881133"));
         * Assert.That(2312881133.Equals(cpr));
         * }
         */
        /// <summary>
        ///   The cipher text test.
        /// </summary>
        [Test] public void CipherTextTest()
        {
            var bytes  = new byte[] { 1, 2, 3, 4, 5, 6 };
            var cipher = new CipherText(bytes);

            Assert.That(bytes.IsIdenticalTo(cipher));
            Assert.That(bytes.IsIdenticalTo(cipher.Value));
            Assert.That(cipher.ToString() != null);
        }
Exemple #10
0
        private void Clear_Click(object sender, EventArgs e)
        {
            HashText.Clear();
            PlainText.Clear();
            CipherText.Clear();

            PlainText.Focus();

            this.Encryption.Enabled = true;
        }
Exemple #11
0
        public static string ToPlainText(CipherText encryptedData, string bulkCipherKey)
        {
            //js and C# string escape seq's are the same...
            var results =
                Resources.ScriptEngine.Evaluate(string.Format("sjcl.decrypt(\"{0}\", \"{1}\" )",
                                                              bulkCipherKey,
                                                              encryptedData.ToString().Replace("\"", "\\\"")));

            return(results.ToString());
        }
Exemple #12
0
 /// <summary>
 /// Convert this payload to Base64Url string
 /// </summary>
 /// <returns></returns>
 public string SerializeToBase64UrlString()
 {
     return(String.Format("{0}.{1}.{2}.{3}.{4}",
                          Header.GetBase64UrlFromNormalString(),
                          EncryptedMasterKey.ToBase64UrlString(),
                          InitializationVector.ToBase64UrlString(),
                          CipherText.ToBase64UrlString(),
                          Tag.ToBase64UrlString()
                          ));
 }
Exemple #13
0
        private void Decrypt_Click(object sender, EventArgs e)
        {
            CipherText.Clear();

            this.Decrypt.Enabled    = false;
            this.Encryption.Enabled = true;

            UnicodeEncoding code = new UnicodeEncoding();

            CipherText.Text += code.GetString(enc);
        }
        //Método de evento para o clique no botão "Limpar"
        private void Clear_Click(object sender, EventArgs e)
        {
            //Limpa todas as caixas de texto
            CipherText.Clear();
            plain_text.Clear();
            TextHash.Clear();

            //Foca o mouse na primeira caixa
            plain_text.Focus();

            this.Encrypt.Enabled = true;
        }
Exemple #15
0
        public static CipherText ToEncryptedText(string plainText, string bulkCipherKey)
        {
            var        results = Resources.ScriptEngine.Evaluate(string.Format("sjcl.encrypt(\"{0}\",\"{1}\")", bulkCipherKey, plainText));
            CipherText cipherText;

            if (CipherText.TryParse(results.ToString(), out cipherText))
            {
                return(cipherText);
            }

            return(null);
        }
        public void EncryptedVoterDataTest()
        {
            var voternumber  = new CipherText(new byte[] { 2, 1 });
            var cpr          = new CipherText(new byte[] { 3, 2 });
            var ballotstatus = new CipherText(new byte[] { 4, 3 });

            var encVoterData = new EncryptedVoterData(voternumber, cpr, ballotstatus);

            Assert.That(voternumber.Equals(encVoterData.VoterNumber));
            Assert.That(cpr.Equals(encVoterData.CPR));
            Assert.That(ballotstatus.Equals(encVoterData.BallotStatus));
            Assert.That(encVoterData.ToString() != null);
        }
Exemple #17
0
        /// <summary>
        /// The symmetric test.
        /// </summary>
        [Test] public void SymmetricTest()
        {
            var          key        = new SymmetricKey(Crypto.GenerateSymmetricKey());
            const string TestString = "Howdy there, partner!";

            byte[]     bytes      = Bytes.From(TestString);
            CipherText ciphertext = Crypto.SymmetricEncrypt(bytes, key);

            Assert.That(!bytes.IsIdenticalTo(ciphertext));
            byte[] decryptedBytes = Crypto.SymmetricDecrypt(ciphertext, key);
            Assert.That(bytes.IsIdenticalTo(decryptedBytes));
            Assert.That(decryptedBytes.To <string>().Equals(TestString));
        }
Exemple #18
0
        /// <summary>
        /// Test asymmetric crypto features of Crypto subsystem.
        /// </summary>
        public void AsymmetricTest(string testString)
        {
            Contract.Requires(testString != null);
            // Encrypt/decrypt
            byte[]     bytes      = Bytes.From(testString);
            CipherText ciphertext = Crypto.AsymmetricEncrypt(bytes,
                                                             new AsymmetricKey(Crypto.KeyPair.Public));

            Assert.That(!bytes.IsIdenticalTo(ciphertext));
            byte[] decryptedBytes = Crypto.AsymmetricDecrypt(ciphertext,
                                                             new AsymmetricKey(Crypto.KeyPair.Private));
            Assert.That(bytes.IsIdenticalTo(decryptedBytes));
            Assert.That(decryptedBytes.To <string>().Equals(testString));
        }
        public string SolveChallenge()
        {
            var decipheredTexts = new List <DecipherText>();

            foreach (var cipher in _ciphers)
            {
                var cipherText = new CipherText(cipher, CipherTextFormat.HEXADECIMAL);
                decipheredTexts.Add(cipherText.Crack(_cracker, KEYLENGTH));
            }

            decipheredTexts.Sort();

            return(decipheredTexts.First().CipherText.Text);
        }
Exemple #20
0
        public byte[] Execute(byte[] arg)
        {
            var        cipherTextString = Encoding.UTF8.GetString(arg);
            CipherText cipherText;

            if (!CipherText.TryParse(cipherTextString, out cipherText))
            {
                throw new ArgumentException(string.Format("the cipher text could not be parsed \n '{0}'", cipherTextString));
            }

            var plainText = NoFuture.Encryption.Sjcl.BulkCipherKey.ToPlainText(cipherText, _bulkCipherKey);

            return(Encoding.UTF8.GetBytes(plainText));
        }
Exemple #21
0
        [Pure] public byte[] AsymmetricDecrypt(CipherText cipher,
                                               AsymmetricKey asymmetricKey)
        {
            //_aCipher.Init(false, asymmetricKey.Value);
            byte[] plainText =
                AsymmetricProcessBuffer(cipher.Value, asymmetricKey);
            return(new CipherText(plainText));

            /* int outputLength =
             * _aCipher.ProcessBytes(cipher.Value, 0, cipher.Value.Length, plainText, 0);
             * outputLength += _aCipher.DoFinal(plainText, outputLength);
             * byte[] result = new byte[outputLength];
             * Array.Copy(plainText, result, outputLength);
             * return new CipherText(result); */
        }
Exemple #22
0
        /// <summary>
        ///   The message test.
        /// </summary>
        [Test] public void MessageTest()
        {
            var symKey     = new CipherText(new byte[] { 1, 2 });
            var cmd        = new CipherText(new byte[] { 2, 3 });
            var senderHash = new CipherText(new byte[] { 3, 4 });
            var iv         = new byte[] { 5, 6 };

            var msg = new Message(symKey, cmd, senderHash, iv);

            Assert.That(msg.SymmetricKey.Equals(symKey));
            Assert.That(msg.Command.Equals(cmd));
            Assert.That(msg.SenderHash.Equals(senderHash));
            Assert.That(msg.Iv.IsIdenticalTo(iv));
            Assert.That(msg.ToString() != null);
        }
Exemple #23
0
 private void Decrypt()
 {
     try
     {
         if (Validate(false))
         {
             var plaintext = DES.Decrypt(
                 CipherText.FromHexStringToBitArray(),
                 Key.FromHexStringToBitArray());
             PlainText = plaintext.ToHexString();
         }
     }
     catch (Exception e)
     {
         ShowMessage(string.Format("Error: {0}", e));
     }
 }
Exemple #24
0
        public void ToggleStringJson()
        {
            var testValues = new CipherText
            {
                adata  = "atada",
                cipher = "rehpic",
                ct     = "tc",
                iter   = 1000,
                iv     = "vi",
                ks     = 1000,
                mode   = "edom",
                v      = 1,
                salt   = "tlas",
                ts     = 1
            };
            CipherText testSubject;
            var        testResultTryParse = CipherText.TryParse(testValues.ToString(), out testSubject);

            Assert.IsTrue(testResultTryParse);
        }
Exemple #25
0
        public IBuffer GetBufferWithoutHMAC()
        {
            bool usesPassword = (Options & (byte)1) == (byte)1;

            using (var ms = new MemoryStream((int)(HEADER_LENGTH + CipherText.Length)))
                using (var writer = new BinaryWriter(ms))
                {
                    writer.Write(Version);
                    writer.Write(Options);
                    if (usesPassword)
                    {
                        writer.Write(EncryptionSalt.ToByteArray());
                        writer.Write(HMACSalt.ToByteArray());
                    }
                    writer.Write(IV.ToByteArray());
                    writer.Write(CipherText.ToByteArray());

                    return(ms.ToArray().ToBuffer());
                }
        }
Exemple #26
0
        public State()
        {
            Message = System.IO.File.ReadAllText(@"C:\Users\kuba1\Desktop\crypt\crypt\AES\Jakub_Pilimon.txt");
            using (AesManaged aes = new AesManaged())
            {
                Key = aes.Key;
                IV  = aes.IV;
            }

            CipherText = Encypt(Message, Key, IV);

            InvalidCipher = new byte[CipherText.Length];
            CipherText.CopyTo(InvalidCipher, 0);

            InvalidCipher[0] += 1;

            InvalidKey = new byte[Key.Length];
            Key.CopyTo(InvalidKey, 0);

            InvalidKey[0] += 1;
        }
Exemple #27
0
        public static byte[] Encrypt(byte[] input, uint ms)
        {
            var ct = new CipherText(input, ms);
            var iv = Cipher8FromRand(ref ms);

            //encrypt
            foreach (var bytes in ct.Content)
            {
                for (var j = 0; j < 256; j++)
                {
                    bytes[j] ^= iv[j];
                }

                var temp2 = new uint[0x100 / 4];
                Buffer.BlockCopy(bytes, 0, temp2, 0, 0x100);
                ShufflesLegacy.Shuffle2(temp2);

                Buffer.BlockCopy(temp2, 0, iv, 0, 0x100);
                Buffer.BlockCopy(temp2, 0, bytes, 0, 0x100);
            }

            return(ct.GetBytes(ref ms));
        }
        //private static byte makeIntegrityByte(byte rand)
        //{
        //    char lastbyte = rand->rand();
        //    char tmp = lastbyte & 0xf3;
        //    return ((~tmp & 0x67) | (tmp & 0x98)) ^ 0x77 | (tmp & 0x10);
        //}

        public byte[] Encrypt(byte[] input, uint ms)
        {
            CipherText ct = new CipherText(input, ms);

            byte[] iv = cipher8_from_rand(ref ms);

            //encrypt
            for (int i = 0; i < ct.content.Count; i++)
            {
                for (int j = 0; j < 256; j++)
                {
                    ct.content[i][j] ^= iv[j];
                }

                uint[] temp2 = new uint[0x100 / 4];
                Buffer.BlockCopy(ct.content[i], 0, temp2, 0, 0x100);
                Shuffles.Shuffle2(temp2);

                Buffer.BlockCopy(temp2, 0, iv, 0, 0x100);
                Buffer.BlockCopy(temp2, 0, ct.content[i], 0, 0x100);
            }

            return(ct.getBytes(ref ms));
        }
Exemple #29
0
 public Challenge6(string cipherText, ICracker cracker)
 {
     _cipherText = new CipherText(cipherText, CipherTextFormat.BASE64);
     _cracker    = cracker;
 }
Exemple #30
0
 public byte[] SymmetricDecrypt(CipherText cipher, SymmetricKey symmetricKey)
 {
     Contract.Ensures(Contract.Result <byte[]>() != null);
     return(default(byte[]));
 }