Ejemplo n.º 1
0
        public BigInteger[] GetDecryptedKeyMaterial(string strPassphrase)
        {
            BigInteger[] biKeys = new BigInteger[0];
            if (this.bIsEncrypted)
            {
                SharpPrivacy.Cipher.SymmetricAlgorithm saAlgo;
                switch (this.SymmetricalAlgorithm)
                {
                case SymAlgorithms.AES128:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 128;
                    break;

                case SymAlgorithms.AES192:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 192;
                    break;

                case SymAlgorithms.AES256:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 256;
                    break;

                case SymAlgorithms.Triple_DES:
                    saAlgo         = TripleDES.Create();
                    saAlgo.KeySize = 192;
                    break;

                case SymAlgorithms.CAST5:
                    saAlgo = CAST5.Create();
                    break;

                default:
                    throw(new System.NotSupportedException("Sorry, but the Algorithm that was used to encrypt the secret key data is not (yet) supported by SharpPrivacy!"));
                }

                saAlgo.Mode = CipherMode.CFB;
                saAlgo.Key  = this.S2KSpecifier.GetKey(strPassphrase, saAlgo.KeySize);

                if (this.PublicKey.Version == PublicKeyPacketVersionNumbers.v3)
                {
                    throw(new System.NotImplementedException("Sorry, but we have not yet implemented the decryption of v3 keys!"));
                }
                else if (this.PublicKey.Version == PublicKeyPacketVersionNumbers.v4)
                {
                    //In v4 keys, everything - including mpi headers and checksum
                    //is encrypted. Should be a heck of a lot easier than for
                    //v3 keys.

                    saAlgo.IV      = this.InitialVector;
                    saAlgo.Padding = PaddingMode.None;

                    byte[]           bOutput = new byte[this.bEncryptedKeyMaterial.Length];
                    ICryptoTransform ictDec  = saAlgo.CreateDecryptor();
                    ictDec.TransformBlock(bEncryptedKeyMaterial, 0, bEncryptedKeyMaterial.Length, ref bOutput, 0);

                    int iCurrentChecksum = 0;
                    for (int i = 0; i < bOutput.Length; i++)
                    {
                        iCurrentChecksum = (iCurrentChecksum + bOutput[i]) % 65536;
                    }

                    if (pkpPublicKey.Algorithm == AsymAlgorithms.DSA ||
                        pkpPublicKey.Algorithm == AsymAlgorithms.ElGama_Encrypt_Sign ||
                        pkpPublicKey.Algorithm == AsymAlgorithms.ElGamal_Encrypt_Only)
                    {
                        biKeys = new BigInteger[1];
                        try {
                            biKeys = BigInteger.ParseMPIs(bOutput, 1);
                        } catch (Exception) {
                            throw new Exception("Invalid Passphrase!");
                        }
                    }
                    else if (pkpPublicKey.Algorithm == AsymAlgorithms.RSA_Encrypt_Only ||
                             pkpPublicKey.Algorithm == AsymAlgorithms.RSA_Encrypt_Sign ||
                             pkpPublicKey.Algorithm == AsymAlgorithms.RSA_Sign_Only)
                    {
                        biKeys = new BigInteger[4];
                        try {
                            biKeys = BigInteger.ParseMPIs(bOutput, 4);
                        } catch (Exception) {
                            throw new Exception("Invalid Passphrase!");
                        }
                    }
                }
            }
            else
            {
                //Key Material is not encrypted anyway
                biKeys = this.DecryptedKeyMaterial;
            }

            return(biKeys);
        }
Ejemplo n.º 2
0
        public static object CreateFromKnownName(string name)
        {
            switch (name)
            {
            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315":
                return(new XmlDsigC14NTransform());

            case "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments":
                return(new XmlDsigC14NWithCommentsTransform());

            case "http://www.w3.org/2001/10/xml-exc-c14n#":
                return(new XmlDsigExcC14NTransform());

            case "http://www.w3.org/2001/10/xml-exc-c14n#WithComments":
                return(new XmlDsigExcC14NWithCommentsTransform());

            case "http://www.w3.org/2000/09/xmldsig#base64":
                return(new XmlDsigBase64Transform());

            case "http://www.w3.org/TR/1999/REC-xpath-19991116":
                return(new XmlDsigXPathTransform());

            case "http://www.w3.org/TR/1999/REC-xslt-19991116":
                return(new XmlDsigXsltTransform());

            case "http://www.w3.org/2000/09/xmldsig#enveloped-signature":
                return(new XmlDsigEnvelopedSignatureTransform());

            case "http://www.w3.org/2002/07/decrypt#XML":
                return(new XmlDecryptionTransform());

            case "urn:mpeg:mpeg21:2003:01-REL-R-NS:licenseTransform":
                return(new XmlLicenseTransform());

            case "http://www.w3.org/2000/09/xmldsig# X509Data":
                return(new KeyInfoX509Data());

            case "http://www.w3.org/2000/09/xmldsig# KeyName":
                return(new KeyInfoName());

            case "http://www.w3.org/2000/09/xmldsig# KeyValue/DSAKeyValue":
                return(new DSAKeyValue());

            case "http://www.w3.org/2000/09/xmldsig# KeyValue/RSAKeyValue":
                return(new RSAKeyValue());

            case "http://www.w3.org/2000/09/xmldsig# RetrievalMethod":
                return(new KeyInfoRetrievalMethod());

            case "http://www.w3.org/2001/04/xmlenc# EncryptedKey":
                return(new KeyInfoEncryptedKey());

            case "http://www.w3.org/2000/09/xmldsig#dsa-sha1":
                return(new DSASignatureDescription());

            case "System.Security.Cryptography.DSASignatureDescription":
                return(new DSASignatureDescription());

            case "http://www.w3.org/2000/09/xmldsig#rsa-sha1":
                return(new RSAPKCS1SHA1SignatureDescription());

            case "System.Security.Cryptography.RSASignatureDescription":
                return(new RSAPKCS1SHA1SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256":
                return(new RSAPKCS1SHA256SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384":
                return(new RSAPKCS1SHA384SignatureDescription());

            case "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512":
                return(new RSAPKCS1SHA512SignatureDescription());

            // workarounds for issue https://github.com/dotnet/corefx/issues/16563
            // remove attribute from this method when removing them
            case "http://www.w3.org/2000/09/xmldsig#sha1":
                return(SHA1.Create());

            case "MD5":
                return(MD5.Create());

            case "http://www.w3.org/2001/04/xmldsig-more#hmac-md5":
                return(new HMACMD5());

            case "http://www.w3.org/2001/04/xmlenc#tripledes-cbc":
                return(TripleDES.Create());
            }

            return(null);
        }
Ejemplo n.º 3
0
        public void EncryptKeyMaterial(BigInteger[] biGivenKeyMaterial, string strPassphrase)
        {
            this.biDecryptedKeyMaterial = biGivenKeyMaterial;
            if (!bIsEncrypted)
            {
                return;
            }

            if (this.PublicKey.Version == PublicKeyPacketVersionNumbers.v4)
            {
                int iKeyMaterialLength = 0;
                for (int i = 0; i < this.biDecryptedKeyMaterial.Length; i++)
                {
                    iKeyMaterialLength += biDecryptedKeyMaterial[i].GetMPI().Length;
                }

                byte[] bData = new byte[iKeyMaterialLength + 2];
                int    iPos  = 0;
                for (int i = 0; i < this.biDecryptedKeyMaterial.Length; i++)
                {
                    byte[] bMPI = biDecryptedKeyMaterial[i].GetMPI();
                    Array.Copy(bMPI, 0, bData, iPos, bMPI.Length);
                    iPos += bMPI.Length;
                }

                int iChecksum = 0;
                for (int i = 0; i < bData.Length - 2; i++)
                {
                    iChecksum = (iChecksum + bData[i]) % 65536;
                }

                bData[iPos++] = (byte)((iChecksum >> 8) & 0xFF);
                bData[iPos++] = (byte)(iChecksum & 0xFF);

                SharpPrivacy.Cipher.SymmetricAlgorithm saAlgo;
                switch (this.SymmetricalAlgorithm)
                {
                case SymAlgorithms.AES128:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 128;
                    break;

                case SymAlgorithms.AES192:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 192;
                    break;

                case SymAlgorithms.AES256:
                    saAlgo           = Rijndael.Create();
                    saAlgo.BlockSize = 128;
                    saAlgo.KeySize   = 256;
                    break;

                case SymAlgorithms.Triple_DES:
                    saAlgo         = TripleDES.Create();
                    saAlgo.KeySize = 192;
                    break;

                case SymAlgorithms.CAST5:
                    saAlgo = CAST5.Create();
                    break;

                default:
                    throw(new System.NotSupportedException("Sorry, but the Algorithm that was used to encrypt the secret key data is not (yet) supported by SharpPrivacy!"));
                }

                saAlgo.Mode    = CipherMode.CFB;
                saAlgo.Key     = this.S2KSpecifier.GetKey(strPassphrase, saAlgo.KeySize);
                saAlgo.IV      = this.InitialVector;
                saAlgo.Padding = PaddingMode.None;

                byte[]           bOutput = new byte[bData.Length];
                ICryptoTransform ictEnc  = saAlgo.CreateEncryptor();
                ictEnc.TransformBlock(bData, 0, bData.Length, ref bOutput, 0);

                byte[] bTmp = new byte[bData.Length];
                Array.Copy(bOutput, 0, bTmp, 0, bTmp.Length);
                bOutput = bTmp;

                if (bOutput.Length != bData.Length)
                {
                    throw new Exception("Encryption of the secret Key material did not work correctly. Look at the file SecretKeyPacket, function EncryptKeyMaterial()");
                }

                bEncryptedKeyMaterial = bOutput;
            }
            else
            {
                throw new Exception("Sorry, but we don't support v3 secret keys so far!");
            }
            this.bIsUpdated = true;
        }
Ejemplo n.º 4
0
 public void TripleDES_CFB()
 {
     Assert.AreEqual("89-9F-00-9D-26-BB-21-59-85-6D-A2-BF-15-FE-73-53-1F-CE-35-26-5B-DF-43-26",
                     Roundtrip(TripleDES.Create(), CipherMode.CFB), "Encrypted data");
 }
Ejemplo n.º 5
0
 public void TripleDES_CTS()
 {
     Assert.AreEqual("not implemented in any released framework",
                     Roundtrip(TripleDES.Create(), CipherMode.CTS), "Encrypted data");
 }
Ejemplo n.º 6
0
        public async Task TestDefaultBehaviorAsync()
        {
            // arrange
            var obj = new {
                username = "******"
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);

            var user = new User {
                Username = obj.username
            };

            var request = new UserRequest {
                Id          = 1,
                Username    = obj.username,
                RequestType = UserRequestType.Activation
            };

            var userSet = TestUtilities.CreateDbSetMock(new List <User> {
                user
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(userSet.Object);

            repository
            .Setup(x => x.GetAsync <User>(1))
            .ReturnsAsync(user);

            repository
            .Setup(x => x.GetAsync <UserRequest>(1))
            .ReturnsAsync(request);

            var password    = Guid.NewGuid().ToString();
            var credentials = JObject.FromObject(new {
                obj.username,
                password
            });

            string q;

            using (var algorithm = TripleDES.Create()) {
                request.Key      = algorithm.Key;
                request.IV       = algorithm.IV;
                request.Password = CryptoUtilities.CreateHash(password);

                var ciphertext = CryptoUtilities.Encrypt(credentials.ToString(), algorithm.Key, algorithm.IV);

                q = 1 + ":" + ciphertext;
            }

            dynamic model = JObject.FromObject(new {
                q
            });

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            await TestUtilities.DoesNotThrowAsync(async() => await accountService.ActivateAsync(model));

            // assert
            Assert.True(user.Enabled);

            repository.Verify(x => x.GetAsync <UserRequest>(It.IsAny <int>()), Times.Once);
            repository.Verify(x => x.AsQueryable <User>(), Times.Once);
            repository.Verify(x => x.UpdateAsync(user), Times.Once());
            repository.Verify(x => x.UpdateAsync(request), Times.Once());
        }
Ejemplo n.º 7
0
        public static byte[] OWHF2_8_2(KernelDatabaseBase database, byte[] pd)
        {
            int pl = database.Get(EMVTagsEnum.DS_ID_9F5E_KRN2).Value.Length;

            byte[] dsid = database.Get(EMVTagsEnum.DS_ID_9F5E_KRN2).Value;

            byte[] dspkl = new byte[6];
            byte[] dspkr = new byte[6];

            for (int i = 0; i < 6; i++)
            {
                dspkl[i] = (byte)(((dsid[i] / 16) * 10 + (dsid[i] % 16)) * 2);
                dspkr[i] = (byte)(((dsid[pl - 6 + i] / 16) * 10 + (dsid[pl - 6 + i] % 16)) * 2);
            }

            byte[] oid = new byte[8];
            if (database.IsNotEmpty(EMVTagsEnum.DS_SLOT_MANAGEMENT_CONTROL_9F6F_KRN2.Tag) &&
                (database.Get(EMVTagsEnum.DS_SLOT_MANAGEMENT_CONTROL_9F6F_KRN2).Value[0] & 0x80) == 0x80 && // Permanent slot type

                (database.Get(EMVTagsEnum.DS_ODS_INFO_DF62_KRN2).Value[0] & 0x40) == 0x40                   //Volatile slot type
                )
            {
                oid = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };
            }
            else
            {
                oid = database.Get(EMVTagsEnum.DS_REQUESTED_OPERATOR_ID_9F5C_KRN2).Value;
            }

            byte[] kl = new byte[8];
            byte[] kr = new byte[8];
            for (int i = 0; i < 6; i++)
            {
                kl[i] = dspkl[i];
                kr[i] = dspkr[i];
            }
            for (int i = 6; i < 8; i++)
            {
                kl[i] = oid[i - 2];
                kr[i] = oid[i];
            }

            TripleDES des = TripleDES.Create();

            List <byte[]> keyComps = new List <byte[]>();

            keyComps.Add(kl);
            keyComps.Add(kr);
            keyComps.Add(kl);
            byte[] key = keyComps.SelectMany(x => x).ToArray();

            des.Key     = key;
            des.Mode    = CipherMode.CBC;
            des.Padding = PaddingMode.None;

            byte[] exOrData = XOR(oid, pd);

            MemoryStream ms = new MemoryStream();

            using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(exOrData, 0, exOrData.Length);
            }
            byte[] r = ms.ToArray();
            ms.Dispose();
            return(XOR(r, pd));
        }
Ejemplo n.º 8
0
 protected override Stream Decrypt(Stream input)
 => new CryptoStream(input, TripleDES.Create().CreateDecryptor(_key, _iv), CryptoStreamMode.Read);
Ejemplo n.º 9
0
 protected override Stream Encrypt(Stream output)
 => new CryptoStream(output, TripleDES.Create().CreateEncryptor(_key, _iv), CryptoStreamMode.Write);
Ejemplo n.º 10
0
        /// Encodes the specified string.
        /// @param text The string to encode.
        /// @returns The encoded string.
        public string Encode(string text)
        {
            var bytes = Encoding.Default.GetBytes(text);

            return(Convert.ToBase64String(TripleDES.Create().CreateEncryptor().TransformFinalBlock(bytes, 0, bytes.Length)));
        }
Ejemplo n.º 11
0
 internal static TripleDES CreateTripleDES()
 {
     return(TripleDES.Create());
 }
Ejemplo n.º 12
0
        private static SymmetricAlgorithm PrepareCipher(byte[] decodedKey, Cipher cipher, byte[] iv, Options options)
        {
            // Pad key out to KeyLength in bytes if its too short or trancuate if it is too long
            int KeyLengthInBytes = cipher.KeyLength / 8;

            if (decodedKey.Length < KeyLengthInBytes || decodedKey.Length > KeyLengthInBytes)
            {
                var resizedKey = new byte[KeyLengthInBytes];
                Buffer.BlockCopy(decodedKey, 0, resizedKey, 0, Math.Min(decodedKey.Length, resizedKey.Length));
                decodedKey = resizedKey;
            }

            var iVector = new byte[cipher.IVLength];

            if (!ArrayUtils.IsNullOrEmpty(iv))
            {
                var ivLength = iv.Length;
                if (ivLength != cipher.IVLength)
                {
                    if (ivLength < cipher.IVLength) // Pad zeros
                    {
                        if ((options & Options.OPENSSL_DONT_ZERO_PAD_KEY) != 0 /* && !EVP_CIPHER_CTX_set_key_length(ivLength)*/)
                        {
                            // Warning: Key length cannot be set for the cipher method
                            throw new CryptographicException(Resources.LibResources.openssl_cannot_set_iv_length);
                        }

                        PhpException.Throw(PhpError.E_WARNING, Resources.LibResources.openssl_short_iv, iv.Length.ToString(), cipher.IVLength.ToString());
                    }
                    else if (ivLength > cipher.IVLength) // Trancuate
                    {
                        PhpException.Throw(PhpError.E_WARNING, Resources.LibResources.openssl_long_iv, iv.Length.ToString(), cipher.IVLength.ToString());
                        ivLength = cipher.IVLength;
                    }
                }

                Buffer.BlockCopy(iv, 0, iVector, 0, ivLength);
            }

            SymmetricAlgorithm alg = null;

            switch (cipher.Type)
            {
            case CipherType.AES:
                if (cipher.Mode == SupportedCipherMode.CTR)
                {
                    alg = new AesCounterMode();
                }
                else
                {
                    alg = new RijndaelManaged {
                        Padding = PaddingMode.PKCS7, KeySize = cipher.KeyLength
                    }
                };
                break;

            case CipherType.DES:
                alg = DES.Create();
                break;

            case CipherType.TripleDES:
                alg = TripleDES.Create();
                break;
            }

            if (TryGetDotNetCipherMode(cipher.Mode, out var cipherMode))
            {
                alg.Mode = cipherMode;
            }

            alg.Key = decodedKey;
            alg.IV  = iVector;

            if ((options & Options.OPENSSL_ZERO_PADDING) == Options.OPENSSL_ZERO_PADDING)
            {
                alg.Padding = PaddingMode.None;
            }

            return(alg);
        }
Ejemplo n.º 13
0
        private void createDecryptionCipher()
        {
            // Create and configure the symmetric algorithm
            switch (CipherAlgorithmType)
            {
            case CipherAlgorithmType.Des:
                decryptionAlgorithm = DES.Create();
                break;

            case CipherAlgorithmType.Rc2:
                decryptionAlgorithm = RC2.Create();
                break;

            case CipherAlgorithmType.Rc4:
                decryptionAlgorithm = new M.ARC4Managed();
                break;

            case CipherAlgorithmType.TripleDes:
                decryptionAlgorithm = TripleDES.Create();
                break;

            case CipherAlgorithmType.Rijndael:
                // only AES is really used - and we can use CommonCrypto for iOS and OSX this way
                decryptionAlgorithm = Aes.Create();
                break;
            }

            // If it's a block cipher
            if (CipherMode == CipherMode.CBC)
            {
                // Configure encrypt algorithm
                decryptionAlgorithm.Mode      = CipherMode;
                decryptionAlgorithm.Padding   = PaddingMode.None;
                decryptionAlgorithm.KeySize   = ExpandedKeyMaterialSize * 8;
                decryptionAlgorithm.BlockSize = blockSize * 8;
            }

            // Set the key and IV for the algorithm
            if (Context is ClientContext)
            {
                decryptionAlgorithm.Key = Context.ServerWriteKey;
                decryptionAlgorithm.IV  = Context.ServerWriteIV;
            }
            else
            {
                decryptionAlgorithm.Key = Context.ClientWriteKey;
                decryptionAlgorithm.IV  = Context.ClientWriteIV;
            }

            // Create decryption cipher
            DecryptionCipher = decryptionAlgorithm.CreateDecryptor();

            // Create the HMAC
            if (Context is ClientContext)
            {
                ServerHMAC = new HMAC(
                    CreateHashAlgorithm(),
                    Context.Negotiating.ServerWriteMAC);
            }
            else
            {
                ClientHMAC = new HMAC(
                    CreateHashAlgorithm(),
                    Context.Negotiating.ClientWriteMAC);
            }
        }
Ejemplo n.º 14
0
        public async Task Run()
        {
            const string pwd1 = "mypassword";

            // Create a byte array to hold the random value.
            var salt1 = new byte[8];

            using (var rngCsp = new RNGCryptoServiceProvider())
            {
                // Fill the array with a random value.
                rngCsp.GetBytes(salt1);
            }

            //data1 can be a string or contents of a file.
            const string data1 = "Some test data";

            //The default iteration count is 1000 so the two methods use the same iteration count.
            const int myIterations = 1000;

            try
            {
                var k1 = new Rfc2898DeriveBytes(pwd1, salt1, myIterations);
                var k2 = new Rfc2898DeriveBytes(pwd1, salt1);

                // Encrypt the data.
                var encAlg = TripleDES.Create();
                encAlg.Key = k1.GetBytes(16);
                var encryptionStream = new MemoryStream();
                var encrypt          = new CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write);
                var utfD1            = new UTF8Encoding(false).GetBytes(data1);

                encrypt.Write(utfD1, 0, utfD1.Length);
                encrypt.FlushFinalBlock();
                encrypt.Close();
                var edata1 = encryptionStream.ToArray();
                k1.Reset();

                // Try to decrypt, thus showing it can be round-tripped.
                var decAlg = TripleDES.Create();
                decAlg.Key = k2.GetBytes(16);
                decAlg.IV  = encAlg.IV;
                var decryptionStreamBacking = new MemoryStream();

                var decrypt = new CryptoStream(decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write);

                decrypt.Write(edata1, 0, edata1.Length);
                decrypt.Flush();
                decrypt.Close();
                k2.Reset();

                var data2 = new UTF8Encoding(false).GetString(decryptionStreamBacking.ToArray());

                if (!data1.Equals(data2))
                {
                    Console.WriteLine("Error: The two values are not equal.");
                }
                else
                {
                    Console.WriteLine("The two values are equal.");
                    Console.WriteLine("k1 iterations: {0}", k1.IterationCount);
                    Console.WriteLine("k2 iterations: {0}", k2.IterationCount);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 15
0
        static FormsAuthenticationTicket Decrypt2(byte [] bytes)
        {
            if (protection == FormsProtectionEnum.None)
            {
                return(FormsAuthenticationTicket.FromByteArray(bytes));
            }

#if NET_2_0
            MachineKeySection config = (MachineKeySection)WebConfigurationManager.GetWebApplicationSection(machineKeyConfigPath);
#else
            MachineKeyConfig config = HttpContext.GetAppConfig(machineKeyConfigPath) as MachineKeyConfig;
#endif
            bool all = (protection == FormsProtectionEnum.All);

            byte [] result = bytes;
            if (all || protection == FormsProtectionEnum.Encryption)
            {
                ICryptoTransform decryptor;
                decryptor = TripleDES.Create().CreateDecryptor(GetDecryptionKey(config), init_vector);
                result    = decryptor.TransformFinalBlock(bytes, 0, bytes.Length);
                bytes     = null;
            }

            if (all || protection == FormsProtectionEnum.Validation)
            {
                int count;
                MachineKeyValidation validationType;

#if NET_2_0
                validationType = config.Validation;
#else
                validationType = config.ValidationType;
#endif
                if (validationType == MachineKeyValidation.MD5)
                {
                    count = MD5_hash_size;
                }
                else
                {
                    count = SHA1_hash_size;                     // 3DES and SHA1
                }
#if NET_2_0
                byte [] vk = MachineKeySectionUtils.ValidationKeyBytes(config);
#else
                byte [] vk = config.ValidationKey;
#endif
                byte [] mix = new byte [result.Length - count + vk.Length];
                Buffer.BlockCopy(result, 0, mix, 0, result.Length - count);
                Buffer.BlockCopy(vk, 0, mix, result.Length - count, vk.Length);

                byte [] hash = null;
                switch (validationType)
                {
                case MachineKeyValidation.MD5:
                    hash = MD5.Create().ComputeHash(mix);
                    break;

                // From MS docs: "When 3DES is specified, forms authentication defaults to SHA1"
                case MachineKeyValidation.TripleDES:
                case MachineKeyValidation.SHA1:
                    hash = SHA1.Create().ComputeHash(mix);
                    break;
                }

                if (result.Length < count)
                {
                    throw new ArgumentException("Error validating ticket (length).", "encryptedTicket");
                }

                int i, k;
                for (i = result.Length - count, k = 0; k < count; i++, k++)
                {
                    if (result [i] != hash [k])
                    {
                        throw new ArgumentException("Error validating ticket.", "encryptedTicket");
                    }
                }
            }

            return(FormsAuthenticationTicket.FromByteArray(result));
        }
Ejemplo n.º 16
0
 public void TripleDES_ECB()
 {
     Assert.AreEqual("89-4B-C3-08-54-26-A4-41-89-4B-C3-08-54-26-A4-41-A3-CF-6E-C8-8B-D9-7D-73",
                     Roundtrip(TripleDES.Create(), CipherMode.ECB), "Encrypted data");
 }
Ejemplo n.º 17
0
        public async Task TestWithInvalidPasswordAsync()
        {
            // arrange
            var obj = new {
                username = "******",
                password = "******"
            };

            var repository            = new Mock <IRepository>();
            var settings              = new ApplicationSettings();
            var validationService     = new Mock <ValidationService>(repository.Object, settings);
            var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object);
            var mailService           = new Mock <MailService>(repository.Object);

            validationService
            .SetupGet(x => x.Bundles)
            .Returns(new ValidationBundles(validationService.Object));

            var user = new User {
                Username = obj.username
            };

            var request = new UserRequest {
                Id          = 1,
                Username    = obj.username,
                RequestType = UserRequestType.ResetPassword
            };

            var userSet = TestUtilities.CreateDbSetMock(new List <User> {
                user
            });

            repository
            .Setup(x => x.AsQueryable <User>())
            .Returns(userSet.Object);

            repository
            .Setup(x => x.GetAsync <UserRequest>(1))
            .ReturnsAsync(request);

            var password    = Guid.NewGuid().ToString();
            var credentials = JObject.FromObject(obj);

            string q;

            using (var algorithm = TripleDES.Create()) {
                request.Key      = algorithm.Key;
                request.IV       = algorithm.IV;
                request.Password = CryptoUtilities.CreateHash(password);

                var ciphertext = CryptoUtilities.Encrypt(credentials.ToString(), algorithm.Key, algorithm.IV);

                q = 1 + ":" + ciphertext;
            }

            dynamic model = JObject.FromObject(new {
                q
            });

            var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object);

            // act
            var exception = await TestUtilities.ThrowsAsync <ServiceException>(async() => await accountService.ResetPasswordAsync(model));

            // assert
            Assert.Equal(ServiceReason.ResetPasswordError, exception.Reason);
            Assert.Null(user.Password);

            repository.Verify(x => x.GetAsync <UserRequest>(It.IsAny <int>()), Times.Once);
            repository.Verify(x => x.AsQueryable <User>(), Times.Never);
            repository.Verify(x => x.UpdateAsync(user), Times.Never());
            repository.Verify(x => x.UpdateAsync(request), Times.Never());
        }
Ejemplo n.º 18
0
 public void TripleDES_CBC()
 {
     Assert.AreEqual("89-4B-C3-08-54-26-A4-41-06-8E-DF-B5-F0-23-AB-B4-76-40-68-9A-26-7D-8D-6E",
                     Roundtrip(TripleDES.Create(), CipherMode.CBC), "Encrypted data");
 }
Ejemplo n.º 19
0
        static void Main(string[] args)
        {
            /*                 Readme examples            */

            // Create encrypter with default algorithm (AES) and generate a new random key
            var encrypter = new EasyEncrypt();

            // Encrypt and decrypt a string
            var encryptedString = encrypter.Encrypt("Example data");
            var decryptedString = encrypter.Decrypt(encryptedString);

            /*                 AES encryption            */

            // Get key from encrypter
            byte[] key = encrypter.GetKey();

            // Create encrypter with default algorithm (AES) and use an existing key
            using var encrypterWithKey = new EasyEncrypt(key: key);

            // Create encrypter with default algorithm (AES) and create encryption key from password and salt (with PBKDF2)
            using var encrypterWithPassword = new EasyEncrypt("Password", "Salt12345678");

            // Encrypt and decrypt a byte[]
            var encryptedArray = encrypter.Encrypt(Encoding.UTF8.GetBytes("Example data"));
            var decryptedArray = encrypter.Decrypt(encryptedArray);

            /*                 Custom algorithms encryption            */

            // Create encrypter with DES encryption
            using var DESencrypter = new EasyEncrypt(DES.Create());

            // Create encryptor with TripleDES encryption and create encryption key from password and salt (with PBKDF2)
            using var tripleDeSencrypter = new EasyEncrypt("Password", "Salt12345678", TripleDES.Create());

            /*                Encrypting streams            */

            // Readable input stream, gets disposed when encrypted
            using var inputStream = new MemoryStream(Encoding.UTF8.GetBytes("Example data"));
            // Writable output stream, encrypted data gets written to this stream
            using var encryptedStream = new MemoryStream();
            // Encrypt our stream
            encrypter.EncryptStream(inputStream, encryptedStream);

            // Writable output stream, decrypted data gets written to this stream
            using var decryptedStream = new MemoryStream();
            // Decrypt our stream, encrypted data gets disposed
            encrypter.DecryptStream(encryptedStream, decryptedStream);

            /*            Encrypting files        */
            const string inputFile     = "Data.txt",
                         encryptedFile = "EncryptedData.txt",
                         decryptedFile = "DecryptedData.txt";

            // Encrypt a file, encrypted file gets created with encrypted data
            encrypter.EncryptFile(inputFile, encryptedFile);
            // Decrypt a file, decrypted file gets created with decrypted data
            encrypter.DecryptFile(encryptedFile, decryptedFile);
        }
Ejemplo n.º 20
0
 public TripleDES Create()
 {
     return(TripleDES.Create());
 }