Used to encrypt or decrypt data using a given key set.
Inheritance: Encrypter
Ejemplo n.º 1
0
        public override int Run(string[] remainingArguments)
        {
            var ret = 0;
            Crypter crypter = null;
            IKeySet ks = new KeySet(_location);

            Func<string> prompt = CachedPrompt.Password(Util.PromptForPassword).Prompt;

            IDisposable dks = null;
            if (!String.IsNullOrWhiteSpace(_crypterLocation))
            {
                if (_password)
                {
                    var cks = new PbeKeySet(_crypterLocation, prompt);
                    crypter = new Crypter(cks);
                    dks = cks;
                }
                else
                {
                    crypter = new Crypter(_crypterLocation);
                }
                ks = new EncryptedKeySet(ks, crypter);
            }
            else if (_password)
            {
                ks = new PbeKeySet(ks, prompt);
            }
            var d2ks = ks as IDisposable;

            using (crypter)
            using (dks)
            using (d2ks)
            using (var keySet = new MutableKeySet(ks))
            {
                var pubKeySet = keySet.PublicKey();
                if (pubKeySet != null)
                {
                    using (pubKeySet)
                    {
                        IKeySetWriter writer = new KeySetWriter(_destination, overwrite: false);

                        if (pubKeySet.Save(writer))
                        {
                            Console.WriteLine(Localized.MsgNewPublicKeySet);
                            ret = 0;
                        }
                        else
                        {
                            ret = -1;
                        }
                    }
                }
                else
                {
                    ret = -1;
                }
            }

            return ret;
        }
 public void TestDecryptPrimaryOnly(String subDir)
 {
     var subPath = Util.TestDataPath(TEST_DATA, subDir);
     using (var crypter = new Crypter(subPath))
     {
         var primaryCiphertext = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "1.out")).First();
         var primaryDecrypted = crypter.Decrypt(primaryCiphertext);
         Expect(primaryDecrypted, Is.EqualTo(plaintext));
     }
 }
Ejemplo n.º 3
0
        public void TestAesNonRepeating(string subDir, string nestedDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir, nestedDir);

            using (var crypter = new Crypter(subPath))
            {
                var cipher = crypter.Encrypt(input);
                var cipher2 = crypter.Encrypt(input);
                Expect(cipher, Is.Not.EqualTo(cipher2));
            }
        }
Ejemplo n.º 4
0
        public void TestAesEncryptedKeyDecrypt(string subDir, string nestedDir)
        {
            // Test reading and using encrypted keys

            var basePath = Util.TestDataPath(TEST_DATA, nestedDir);
            var keyPath = Path.Combine(basePath, subDir);
            var dataPath = Path.Combine(basePath, subDir + "-crypted");
            using (var keyDecrypter = new Crypter(keyPath))
            using (var dataDecrypter = new Crypter(new EncryptedKeySet(dataPath, keyDecrypter)))
            {
                HelperDecrypt(dataDecrypter, dataPath);
            }
        }
Ejemplo n.º 5
0
        public void DecryptSession()
        {
            var path = TestData(Location);

            var material = (WebBase64) File.ReadAllLines(Path.Combine(path, "2.session.material")).First();
            var ciphertext = (WebBase64) File.ReadAllLines(Path.Combine(path, "2.session.ciphertext")).First();

            using (var crypter = new Crypter(path))
            using (var sessionCrypter = new SessionCrypter(crypter, material))
            {
                var decrypted = sessionCrypter.Decrypt(ciphertext);
                Expect(decrypted, Is.EqualTo(Input));
            }
        }
Ejemplo n.º 6
0
 public void TestCryptImport([Values("rsa")] String keyType, [Values("pem", "der")] String fileFormat)
 {
     using (
         var keyset = ImportedKeySet.Import.X509Certificate(KeyPurpose.Encrypt,
                                                            Util.TestDataPath(TEST_DATA,
                                                                              keyType + "-crypt-crt." +
                                                                              fileFormat)))
     using (var encrypter = new Encrypter(keyset))
     using (var crypter = new Crypter(Util.TestDataPath(TEST_DATA, "rsa-crypt")))
     {
         var ciphertext = encrypter.Encrypt(input);
         var plaintext = crypter.Decrypt(ciphertext);
         Expect(plaintext, Is.EqualTo(input));
     }
 }
Ejemplo n.º 7
0
 public void TestCryptImport(
     [Values("rsa")] string keyType,
     [Values("pem", "der")] string format)
 {
     using (var keystream = HelperOpenPkcsStream(keyType, format, "crypt"))
     using (
         var keyset = ImportedKeySet.Import.PkcsKey(KeyPurpose.DecryptAndEncrypt, keystream, () => "pass"
             /* hard coding for test only!!!!*/))
     using (var crypter = new Crypter(keyset))
     using (var encrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa-crypt")))
     {
         var ciphertext = encrypter.Encrypt(input);
         var plaintext = crypter.Decrypt(ciphertext);
         Expect(plaintext, Is.EqualTo(input));
     }
 }
Ejemplo n.º 8
0
        public void AESTest(
            [Values(2048)] int datasize,
            [Values(128, 192, 256)] int keysize,
            [Values("AES", "STDNET40_AES", "C#_AES_AEAD")] string alg
            )
        {
            KeyType type = alg;
            var key = Key.Generate(type, keysize);
            using (var ks = new ImportedKeySet(key, KeyPurpose.DecryptAndEncrypt, "Test"))
            using (var crypter = new Crypter(ks))
            {
                var watchEncrypt = new System.Diagnostics.Stopwatch();
                var watchDecrypt = new System.Diagnostics.Stopwatch();
                for (int i = 0; i < iterations; i++)
                {
                    var input = new byte[datasize];

                    watchEncrypt.Start();
                    var output = crypter.Encrypt(input);
                    watchEncrypt.Stop();

                    watchDecrypt.Start();
                    var result = crypter.Decrypt(output);
                    watchDecrypt.Stop();

                    Expect(result, Is.EqualTo(input));
                }

                Console.WriteLine(String.Format("{3}-{4},{2}\t\tEncryption Total:{0},\tThroughput:{1:#,##0.00} MB/S",
                                                watchEncrypt.Elapsed,
                                                (datasize*iterations*1000m)/
                                                (1024m*1024m*watchEncrypt.ElapsedMilliseconds),
                                                datasize,
                                                alg,
                                                keysize
                                      ));
                Console.WriteLine(String.Format("{3}-{4},{2}\t\tDecryption Total:{0},\tThroughput:{1:#,##0.00} MB/S",
                                                watchDecrypt.Elapsed,
                                                (datasize*iterations*1000m)/
                                                (1024m*1024m*watchDecrypt.ElapsedMilliseconds),
                                                datasize,
                                                alg,
                                                keysize
                                      ));
            }
        }
Ejemplo n.º 9
0
        public static string Decrypt(string[] data, PathProvider p)
        {
            WebBase64 sessionMaterial = (WebBase64)data[0];
            WebBase64 cipherText = (WebBase64)data[1];
            string output;

            //PathProvider pathProvider = new PathProvider();
            string path1 = p.GetPrivatePath();

            //string path1 = HostingEnvironment.ApplicationPhysicalPath + "encryption";

            using (var crypter = new Crypter(path1))
            using (var sessionCrypter = new SessionCrypter(crypter, sessionMaterial))
            {
                output = sessionCrypter.Decrypt(cipherText);

            }
            return output;
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SessionCrypter" /> class.
        /// </summary>
        /// <param name="keyDecrypter">The key decrypter.</param>
        /// <param name="sessionMaterial">The session material.</param>
        /// <param name="verifier">The verifier, optionally used to certify sender. (Equivialent to SignedSessionDecrypter)</param>
        /// <param name="keyPacker">The key packer.</param>
        public SessionCrypter(Crypter keyDecrypter, WebBase64 sessionMaterial, AttachedVerifier verifier = null,
                              ISessionKeyPacker keyPacker = null)
        {
            if (verifier != null)
            {
                keyPacker = keyPacker ?? new NonceSignedSessionPacker();
            }
            keyPacker = keyPacker ?? new SimpleAesHmacSha1KeyPacker();

            var sessionMaterialBytes = sessionMaterial.ToBytes();
            var sessionPacker        = keyPacker as IInteroperableSessionMaterialPacker;

            _verifier = verifier;

            if (sessionPacker == null && _verifier != null)
            {
                sessionMaterialBytes = _verifier.VerifiedMessage(sessionMaterialBytes);
            }
            var packedBytes = keyDecrypter.Decrypt(sessionMaterialBytes);

            Key key;

            if (sessionPacker == null)
            {
                key = keyPacker.Unpack(packedBytes);
            }
            else
            {
                var nonceSession = sessionPacker.UnpackMaterial(packedBytes);
                key    = nonceSession.Key;
                _nonce = nonceSession.Nonce.ToBytes();
            }

            _keyset          = new ImportedKeySet(key, KeyPurpose.DecryptAndEncrypt);
            _crypter         = new Crypter(_keyset);
            _sessionMaterial = sessionMaterial;
        }
Ejemplo n.º 11
0
 public void TestRsaCryptWithPublicKey()
 {
     using (var encrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa.public")))
     {
         var cipher = encrypter.Encrypt(input);
         var subPath = Util.TestDataPath(TEST_DATA, "rsa");
         using (var crypter = new Crypter(subPath))
         {
             var decrypt = crypter.Decrypt(cipher);
             Expect(decrypt, Is.EqualTo(input));
         }
     }
 }
Ejemplo n.º 12
0
 public void TestPkcsEncryption()
 {
     var ciphertext = new Encrypter(pkcsReader).Encrypt(input);
     var plaintext = new Crypter(pkcsReader).Decrypt(ciphertext);
     Expect(plaintext, Is.EqualTo(input));
 }
Ejemplo n.º 13
0
 public void TestIncompatibility()
 {
     var encrypter = new Encrypter(oaepReader);
     var ciphertext = encrypter.Encrypt(input);
     var crypter = new Crypter(pkcsReader);
     Expect(() => crypter.Decrypt(ciphertext), Throws.TypeOf<InvalidCryptoDataException>());
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EncryptedKeySet"/> class.
        /// </summary>
        /// <param name="keySet">The key set.</param>
        /// <param name="crypter">The crypter.</param>
        public EncryptedKeySet(IKeySet keySet, Crypter crypter)
        {
            _keySet = keySet;

            _crypter = crypter;
        }
Ejemplo n.º 15
0
 public void TestShortEncryptAndDecrypt(string subDir, string nestedDir)
 {
     var subPath = Util.TestDataPath(TEST_DATA, subDir, nestedDir);
     using (var crypter = new Crypter(subPath))
     {
         for (int i = 0; i < 32; i++)
         {
             var letters = Enumerable.Repeat('a', i).ToArray();
             var each = new String(letters);
             var ciphertext = crypter.Encrypt(each);
             var decrypted = crypter.Decrypt(ciphertext);
             Expect(decrypted, Is.EqualTo(each), "Length:" + i);
         }
     }
 }
Ejemplo n.º 16
0
        public void TestEncryptDecrypt(String subDir, string nestedDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir, nestedDir);

            using (var crypter = new Crypter(subPath))
            {
                var cipher = crypter.Encrypt(input);
                var decrypt = crypter.Decrypt(cipher);
                Expect(decrypt, Is.EqualTo(input));
            }
        }
Ejemplo n.º 17
0
 private SessionCrypter HelperSessionCrypter(Crypter crypter, WebBase64 session, string unoffical)
 {
     if (String.IsNullOrWhiteSpace(unoffical))
     {
         return new SessionCrypter(crypter, session);
     }
     else
     {
         return new SessionCrypter(crypter, session, keyPacker: new BsonSessionKeyPacker());
     }
 }
Ejemplo n.º 18
0
        public void TestOperateOnPbeKeys()
        {
            string result;

            var pathc = Util.TestDataPath(TEST_DATA, "rsa-pbe");

            if (Directory.Exists(pathc))
                Directory.Delete(pathc, true);

            result = Util.KeyczarTool(create: null, location: pathc, purpose: "crypt", asymmetric: null);
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKeySet));

            result = Util.KeyczarTool("cartman", "cartman", addkey: null, location: pathc, password: null,
                                      status: "primary");
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKey));

            var pathi = Path.Combine(pathc, "out.pem");

            result = Util.KeyczarTool(
                "cartman",
                "pass",
                "pass",
                export: null,
                location: pathc,
                password: null,
                destination: pathi);

            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgExportedPem));

            result = Util.KeyczarTool("cartman", "pass",
                                      importkey: null,
                                      location: pathc,
                                      status: "primary",
                                      password: null,
                                      importlocation: pathi);

            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgImportedNewKey));

            var pathp = Path.Combine(pathc, "export");

            result = Util.KeyczarTool(
                "cartman",
                pubkey: null,
                location: pathc,
                password: null,
                destination: pathp
                );
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgNewPublicKeySet));

            var patho = Path.Combine(pathc, "1.out");

            result = Util.KeyczarTool(
                "cartman",
                usekey: null,
                location: pathc,
                password: null,
                destination: patho,
                additionalArgs: new[] {input}
                );
            using (var pks = new PbeKeySet(pathc, () => "cartman" /*hardcoding because this is a test*/))
            using (var crypter = new Crypter(pks))
            {
                Expect(pks.Metadata.Encrypted, Is.True);
                result = crypter.Decrypt((WebBase64) File.ReadAllText(patho));
                Expect(result, Is.EqualTo(input));
            }

            Directory.Delete(pathc, true);
        }
Ejemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncryptedKeySet"/> class.
 /// </summary>
 /// <param name="keySetLocation">The key set location.</param>
 /// <param name="crypter">The crypter.</param>
 public EncryptedKeySet(string keySetLocation, Crypter crypter)
     : this(new KeySet(keySetLocation), crypter)
 {
 }
Ejemplo n.º 20
0
        public void TestDecrypt(String subDir, string nestedDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir, nestedDir);

            using (var crypter = new Crypter(subPath))
            {
                HelperDecrypt(crypter, subPath);
            }
        }
Ejemplo n.º 21
0
        public void TestOperateOnCryptedKeys()
        {
            string result;
            var path = Util.TestDataPath(TEST_DATA, "crypting");

            var pathc = Util.TestDataPath(TEST_DATA, "rsa-crypted");

            if (Directory.Exists(path))
                Directory.Delete(path, true);

            if (Directory.Exists(pathc))
                Directory.Delete(pathc, true);

            result = Util.KeyczarTool(create: null, location: path, purpose: "crypt");
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKeySet));

            result = Util.KeyczarTool(addkey: null, location: path, status: "primary");

            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKey));

            result = Util.KeyczarTool(create: null, location: pathc, purpose: "crypt", asymmetric: null);
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKeySet));

            result = Util.KeyczarTool(addkey: null, location: pathc, crypter: path, status: "primary");
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKey));

            var pathi = Path.Combine(pathc, "out.pem");

            result = Util.KeyczarTool(
                "pass",
                "pass",
                export: null,
                location: pathc,
                crypter: path,
                destination: pathi);

            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgExportedPem));

            result = Util.KeyczarTool("pass",
                                      importkey: null,
                                      location: pathc,
                                      status: "primary",
                                      crypter: path,
                                      importlocation: pathi);

            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgImportedNewKey));

            var pathp = Path.Combine(pathc, "export");

            result = Util.KeyczarTool(
                pubkey: null,
                location: pathc,
                crypter: path,
                destination: pathp
                );
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgNewPublicKeySet));

            var patho = Path.Combine(pathc, "1.out");

            result = Util.KeyczarTool(
                usekey: null,
                location: pathc,
                crypter: path,
                destination: patho,
                additionalArgs: new[] {input}
                );

            using (var kcrypter = new Crypter(path))
            {
                var eks = new EncryptedKeySet(pathc, kcrypter);
                Expect(eks.Metadata.Encrypted, Is.True);
                using (var crypter = new Crypter(eks))
                {
                    result = crypter.Decrypt((WebBase64) File.ReadAllText(patho));
                    Expect(result, Is.EqualTo(input));
                }
            }

            Directory.Delete(path, true);
        }
Ejemplo n.º 22
0
        private void HelperDecrypt(Crypter crypter, String subPath)
        {
            var activeCiphertext = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "1.out")).First();
            var primaryCiphertext = (WebBase64) File.ReadAllLines(Path.Combine(subPath, "2.out")).First();

            var activeDecrypted = crypter.Decrypt(activeCiphertext);
            Expect(activeDecrypted, Is.EqualTo(input));
            var primaryDecrypted = crypter.Decrypt(primaryCiphertext);
            Expect(primaryDecrypted, Is.EqualTo(input));
        }
Ejemplo n.º 23
0
 public static Func <IKeySet, EncryptedKeySet> Creator(Crypter crypter)
 => keySet => new EncryptedKeySet(keySet, crypter);
Ejemplo n.º 24
0
 public void Setup()
 {
     publicKeyEncrypter = new Encrypter(Util.TestDataPath(TEST_DATA, "rsa.public"));
     privateKeyDecrypter = new Crypter(Util.TestDataPath(TEST_DATA, "rsa"));
 }
Ejemplo n.º 25
0
        public void TestEncryptDecryptCompression(CompressionType compression)
        {
            var subPath = Util.TestDataPath(TEST_DATA, "aes");

            using (var crypter = new Crypter(subPath) {Compression = compression})
            {
                var cipher = crypter.Encrypt(input);
                var decrypt = crypter.Decrypt(cipher);
                Expect(decrypt, Is.EqualTo(input));
                using (var crypter2 = new Crypter(subPath))
                {
                    var decrypt2 = crypter2.Decrypt(cipher);
                    Expect(decrypt2, Is.Not.EqualTo(input));
                }

                var ciphertiny = crypter.Encrypt(bigInput);
                //large array of zeros will compress down a lot
                Expect(ciphertiny.Length, Is.LessThan(bigInput.Length));
                var big = crypter.Decrypt(ciphertiny);
                Expect(big, Is.EqualTo(bigInput));
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EncryptedKeySet"/> class.
        /// </summary>
        /// <param name="keySet">The key set.</param>
        /// <param name="crypter">The crypter.</param>
        public EncryptedKeySet(IKeySet keySet, Crypter crypter)
        {
            _keySet = keySet;

            _crypter = crypter;
        }
Ejemplo n.º 27
0
 public void Setup()
 {
     privateKeyDecrypter = new Crypter(Util.TestDataPath(TEST_DATA, "rsa"));
     publicKeyVerifier = new AttachedVerifier(Util.TestDataPath(TEST_DATA, "dsa.public"));
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncryptedKeySet"/> class.
 /// </summary>
 /// <param name="keySetLocation">The key set location.</param>
 /// <param name="crypter">The crypter.</param>
 public EncryptedKeySet(string keySetLocation, Crypter crypter)
     : this(new KeySet(keySetLocation), crypter)
 {
 }
Ejemplo n.º 29
0
        public void TestEncryptCompression(string compress)
        {
            string result;
            var subPath = Util.TestDataPath(TEST_DATA, "compress");

            if (Directory.Exists(subPath))
                Directory.Delete(subPath, true);

            result = Util.KeyczarTool(create: null, location: subPath, purpose: "crypt");
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKeySet));

            result = Util.KeyczarTool(addkey: null, location: subPath, status: "primary");
            Expect(result, Is.StringContaining(KeyczarTool.Localized.MsgCreatedKey));

            var ptext = Path.Combine(subPath, "ptext");
            File.WriteAllBytes(ptext, bigInput);

            var ctext = Path.Combine(subPath, "ctext");

            result = Util.KeyczarTool(
                usekey: null,
                location: subPath,
                file: null,
                destination: ctext,
                compression: compress,
                binary: null,
                additionalArgs: new[] {ptext}
                );

            var compression = compress == "zlib" ? CompressionType.Zlib : CompressionType.Gzip;

            using (var crypter = new Crypter(subPath) {Compression = compression})
            {
                using (var write = new MemoryStream())
                using (var read = File.OpenRead(ctext))
                {
                    crypter.Decrypt(read, write);
                    Expect(write.ToArray(), Is.EqualTo(bigInput));
                }

                Expect(new FileInfo(ctext).Length, Is.LessThan(new FileInfo(ptext).Length));
            }
        }
Ejemplo n.º 30
0
        public void TestBadCipherText(string subDir, string nestedDir)
        {
            var subPath = Util.TestDataPath(TEST_DATA, subDir, nestedDir);

            using (var crypter = new Crypter(subPath))
            {
                Expect(() => crypter.Decrypt(new byte[0]), Throws.TypeOf<InvalidCryptoDataException>());
                byte[] ciphertext = crypter.Encrypt(inputBytes);
                // Munge the key hash
                ciphertext[1] ^= 44;
                Expect(() => crypter.Decrypt(ciphertext), Throws.TypeOf<InvalidCryptoDataException>());
                //restore
                ciphertext[1] ^= 44;
                // Munge the ciphertext
                ciphertext[15] ^= 39;
                Expect(() => crypter.Decrypt(ciphertext), Throws.TypeOf<InvalidCryptoDataException>());
            }
        }