Пример #1
0
            public void ShouldReturnTrueWhenSignatureIsValid(CipherType cipherType)
            {
                var keyPair   = keys[cipherType];
                var signature = signatureProvider.CreateSignature(keyPair.PrivateKey, content);

                Assert.IsTrue(signatureProvider.VerifySignature(keyPair.PublicKey, signature));
            }
Пример #2
0
        private bool Initialize(CipherType type, uint key1, uint key2)
        {
            if (key1 == 0 && key2 == 0 && type == CipherType.CipherWithAKey)
            {
                type = CipherType.NoChipher;
            }

            switch (type)
            {
            case CipherType.NoChipher:
                Init0();
                break;

            case CipherType.CipherWithoutKeys:
                Init1();
                break;

            case CipherType.CipherWithAKey:
                Init56(key1, key2);
                break;

            default:
                return(false);
            }

            InitEncryptTable();

            return(true);
        }
Пример #3
0
 protected AsymmetricKey(byte[] content, AsymmetricKeyType keyType, int keyLength, CipherType cipherType)
 {
     Content    = content;
     KeyType    = keyType;
     KeySize    = keyLength;
     CipherType = cipherType;
 }
Пример #4
0
        public CipherSuiteInfo(BulkCipherAlgorithm cipher, CipherType cipherType,
                               byte encKeyLen, byte blockLen, byte ivLen, byte recordIVLen, MACAlgorithm mac,
                               KeyExchangeAlgorithm exchangeAlgo)
        {
            _bulk_cipher      = cipher;
            _cipherType       = cipherType;
            _enc_key_length   = encKeyLen;
            _block_length     = blockLen;
            _fixed_iv_length  = ivLen;
            _record_iv_length = recordIVLen;
            _mac          = mac;
            _exchangeAlgo = exchangeAlgo;
            switch (mac)
            {
            case MACAlgorithm.HMAC_MD5: _mac_length = _mac_key_length = 16; break;

            case MACAlgorithm.HMAC_SHA1: _mac_length = _mac_key_length = 20; break;

            case MACAlgorithm.HMAC_SHA256: _mac_length = _mac_key_length = 32; break;

            case MACAlgorithm.HMAC_SHA384: _mac_length = _mac_key_length = 48; break;

            case MACAlgorithm.HMAC_SHA512: _mac_length = _mac_key_length = 64; break;

            default: throw new ArgumentOutOfRangeException();
            }
            _isECC = exchangeAlgo == KeyExchangeAlgorithm.ECDH_anon ||
                     exchangeAlgo == KeyExchangeAlgorithm.ECDH_ECDSA ||
                     exchangeAlgo == KeyExchangeAlgorithm.ECDH_RSA ||
                     exchangeAlgo == KeyExchangeAlgorithm.ECDHE_ECDSA ||
                     exchangeAlgo == KeyExchangeAlgorithm.ECDHE_RSA;
        }
Пример #5
0
 public static void DecryptFile(string fileName, string key, CipherType cipherType, int n)
 {
     try
     {
         string cipherText   = File.ReadAllText(fileName);
         string originalText = ParallelCipher.Decrypt(cipherText, key, cipherType, n);
         File.WriteAllText(fileName, originalText);
         MessageBox.Show("The file has been decrypted");
     }
     catch (UnauthorizedAccessException)
     {
         MessageBox.Show("Access error");
     }
     catch (DirectoryNotFoundException)
     {
         MessageBox.Show("Didectory not found");
     }
     catch (FileNotFoundException)
     {
         MessageBox.Show("File not found");
     }
     catch (Exception e)
     {
         MessageBox.Show("Unexpected error: " + e.Message);
     }
 }
Пример #6
0
 public CipherSuiteInfo(BulkCipherAlgorithm cipher, CipherType cipherType,
     byte encKeyLen, byte blockLen, byte ivLen, byte recordIVLen, MACAlgorithm mac,
     KeyExchangeAlgorithm exchangeAlgo)
 {
     _bulk_cipher = cipher;
     _cipherType = cipherType;
     _enc_key_length = encKeyLen;
     _block_length = blockLen;
     _fixed_iv_length = ivLen;
     _record_iv_length = recordIVLen;
     _mac = mac;
     _exchangeAlgo = exchangeAlgo;
     switch (mac) {
         case MACAlgorithm.HMAC_MD5: _mac_length = _mac_key_length = 16; break;
         case MACAlgorithm.HMAC_SHA1: _mac_length = _mac_key_length = 20; break;
         case MACAlgorithm.HMAC_SHA256: _mac_length = _mac_key_length = 32; break;
         case MACAlgorithm.HMAC_SHA384: _mac_length = _mac_key_length = 48; break;
         case MACAlgorithm.HMAC_SHA512: _mac_length = _mac_key_length = 64; break;
         default: throw new ArgumentOutOfRangeException ();
     }
     _isECC = exchangeAlgo == KeyExchangeAlgorithm.ECDH_anon ||
         exchangeAlgo == KeyExchangeAlgorithm.ECDH_ECDSA ||
         exchangeAlgo == KeyExchangeAlgorithm.ECDH_RSA ||
         exchangeAlgo == KeyExchangeAlgorithm.ECDHE_ECDSA ||
         exchangeAlgo == KeyExchangeAlgorithm.ECDHE_RSA;
 }
Пример #7
0
            public void ShouldSetSignatureContent(CipherType cipherType)
            {
                var keyPair   = keys[cipherType];
                var signature = signatureProvider.CreateSignature(keyPair.PrivateKey, content);

                CollectionAssert.IsNotEmpty(signature.Content);
            }
        /// <summary>
        ///
        /// </summary>
        public static void ShredFile(string path, CipherType cipherType, bool nameObfuscation = true, bool propertyObfuscation = true)
        {
            if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
            {
                throw new FileNotFoundException(path);
            }
            if (!File.Exists(path))
            {
                throw new FileNotFoundException(path);
            }

            switch (cipherType)
            {
            case CipherType.Otp:
                OtpHelper.EncryptWithoutKey(path);
                break;

            case CipherType.Aes:
                AesHelper.EncryptFile(AesHelper.GetNewAesKey(), path);
                break;
            }

            if (propertyObfuscation)
            {
                ObfuscateFileProperties(path);
            }

            if (nameObfuscation)
            {
                path = ObfuscateFileName(path);
            }

            File.Delete(path);
        }
Пример #9
0
            public readonly int        KeyLength; // In Bits

            public Cipher(CipherType type, int iVLength, CipherMode mode, int keyLength)
            {
                // Initialization
                Type      = type;
                IVLength  = iVLength;
                Mode      = mode;
                KeyLength = keyLength;
            }
        public string MapToAlgorithmIdentifier(CipherType cipherType)
        {
            if (!bouncyCastleSignatureAlgorithms.ContainsKey(cipherType))
            {
                throw new ArgumentException("Cipher type not supported for signing.");
            }

            return(bouncyCastleSignatureAlgorithms[cipherType]);
        }
Пример #11
0
            public void ShouldSetDecryptedKeyAsResult(CipherType cipherType)
            {
                var key = Mock.Of <IAsymmetricKey>(k => k.IsEncrypted && k.CipherType == cipherType);

                command.Result = key;

                decorator.Execute(command);
                Assert.AreEqual(expectedKey, command.Result);
            }
        public VaultViewCipherPage(CipherType type, string cipherId)
        {
            _type                = type;
            _cipherId            = cipherId;
            _cipherService       = Resolver.Resolve <ICipherService>();
            _deviceActionService = Resolver.Resolve <IDeviceActionService>();

            Init();
        }
Пример #13
0
        public MapleCipher(short majorVersion, byte[] IV, AesCipher aes, CipherType transformDirection)
        {
            m_majorVersion = majorVersion;

            m_IV = new byte[IVLength];
            Buffer.BlockCopy(IV, 0, m_IV, 0, IVLength);

            m_aesCipher = aes;
        }
Пример #14
0
            public void ShouldReturnFalseWhenSignatureIsNotValid(CipherType cipherType)
            {
                var keyPair   = keys[cipherType];
                var signature = signatureProvider.CreateSignature(keyPair.PrivateKey, content);

                signature.Content[0] = (byte)(signature.Content[0] >> 1);

                Assert.IsFalse(signatureProvider.VerifySignature(keyPair.PublicKey, signature));
            }
        public void ShouldThrowExceptionWhenKeyTypeIsNotValid(CipherType cipherType)
        {
            var command = new VerifyKeyPairCommand
            {
                PrivateKey = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType),
                PublicKey  = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType)
            };

            Assert.Throws <InvalidOperationException>(() => { commandHandler.Execute(command); });
        }
        public void ShouldNotThrowExceptionWhenKeyPairIsValid(CipherType cipherType)
        {
            var command = new VerifyKeyPairCommand
            {
                PrivateKey = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType),
                PublicKey  = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType)
            };

            Assert.DoesNotThrow(() => { commandHandler.Execute(command); });
        }
Пример #17
0
            public void ShouldDecryptPrivateKey(CipherType cipherType)
            {
                var key = Mock.Of <IAsymmetricKey>(k => k.IsEncrypted && k.CipherType == cipherType);

                command.Result   = key;
                command.Password = "******";

                decorator.Execute(command);
                keyEncryptionProvider.Verify(kep => kep.DecryptPrivateKey(key, "foobar"));
            }
Пример #18
0
        public Cipher GetCipherData(CipherType cipherType)
        {
            string          returnString     = sessionAndroidClass.CallStatic <string>("nmg_session_getCipherData", (int)cipherType);
            CallbackMessage message          = new CallbackMessage(returnString);
            int             cipherTypeNum    = message.GetInt("cipherTypeNum");
            string          secretKey        = message.GetString("secretKey");
            string          aesInitialVector = message.GetString("aesInitialVector");

            Cipher cipher = new Cipher((CipherType)cipherTypeNum, secretKey, aesInitialVector);

            return(cipher);
        }
Пример #19
0
        public Cipher GetCipherData(CipherType cipherType)
        {
            string          returnString     = Marshal.PtrToStringAuto(nmg_session_getCipherData((int)cipherType));
            CallbackMessage message          = new CallbackMessage(returnString);
            int             cipherTypeNum    = message.GetInt("cipherTypeNum");
            string          secretKey        = message.GetString("secretKey");
            string          aesInitialVector = message.GetString("aesInitialVector");

            Cipher cipher = new Cipher((CipherType)cipherTypeNum, secretKey, aesInitialVector);

            return(cipher);
        }
Пример #20
0
        public MapleCipher(short majorVersion, byte[] IV, AesCipher aes, CipherType transformDirection)
        {
            m_majorVersion = majorVersion;

            m_IV = new byte[IVLength];
            Buffer.BlockCopy(IV, 0, m_IV, 0, IVLength);

            m_aesCipher = aes;

            m_transformer =
                transformDirection == CipherType.Encrypt ? new Action <byte[]>(EncryptTransform) : new Action <byte[]>(DecryptTransform);
        }
Пример #21
0
        public MapleCipher(short majorVersion, byte[] iv, CipherType transformDirection)
        {
            m_mMajorVersion = (short)(((majorVersion >> 8) & 0xFF) | ((majorVersion << 8) & 0xFF00));

            MIv = new byte[IvLength];
            Buffer.BlockCopy(iv, 0, MIv, 0, IvLength);

            m_mAesCipher = new AesCipher(SKey);

            m_mTransformer =
                transformDirection == CipherType.Encrypt ? EncryptTransform : new Action <byte[]>(DecryptTransform);
        }
Пример #22
0
            public void ShouldThrowExceptionWhenKeyTypeIsNotSupported(CipherType cipherType)
            {
                var typeMapperMock = new Mock <OidToCipherTypeMapper>();

                typeMapperMock.Setup(ctm => ctm.MapOidToCipherType(It.IsAny <string>()))
                .Returns(cipherType);

                keyProvider = new AsymmetricKeyProvider(typeMapperMock.Object, keyInfoWrapper.Object, rsaKeyProvider, dsaKeyProvider, ecKeyProvider, elGamalKeyProvider);
                Assert.Throws <ArgumentException>(() =>
                {
                    keyProvider.GetPublicKey(rsaKeyPair.PublicKey.Content);
                });
            }
Пример #23
0
        public void SetCipherSuite(CipherSuite suite, AsymmetricAlgorithm signAlgo)
        {
            CipherSuiteInfo info = SupportedCipherSuites.GetSuiteInfo(suite);

            if (info == null)
            {
                throw new NotSupportedException();
            }

            _bulk_cipher      = info.BulkCipherAlgorithm;
            _cipherType       = info.CipherType;
            _enc_key_length   = info.EncKeyLength;
            _block_length     = info.BlockLength;
            _fixed_iv_length  = info.FixedIVLength;
            _record_iv_length = info.RecordIVLength;
            _mac            = info.MACAlgorithm;
            _mac_length     = info.MACLength;
            _mac_key_length = info.MACKeyLength;
            _keyExchange    = info.KeyExchangeAlgorithm;

            // TODO: TLS1.2spec ?
            switch (_prfType)
            {
            case PRFAlgorithm.MD5_AND_SHA1: _prf = new MD5_AND_SHA1(); break;

            case PRFAlgorithm.SSL3: _prf = new SSL3_PRF(this); break;

            default: throw new NotSupportedException();
            }

            switch (_keyExchange)
            {
            case KeyExchangeAlgorithm.ECDHE_ECDSA:
                _keyExchanger = new ECDHE_ECDSA((openCrypto.EllipticCurve.Signature.ECDSA)signAlgo);
                break;

            case KeyExchangeAlgorithm.DHE_DSS:
                _keyExchanger = new DHE_DSS((DSACryptoServiceProvider)signAlgo);
                break;

            case KeyExchangeAlgorithm.RSA:
                _keyExchanger = new KeyExchange.RSA((RSACryptoServiceProvider)signAlgo);
                break;

            default:
                throw new NotImplementedException();
            }
        }
        public void ShouldThrowExceptionWhenKeyPairIsNotValid(CipherType cipherType)
        {
            var command = new VerifyKeyPairCommand
            {
                PrivateKey = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType),
                PublicKey  = Mock.Of <IAsymmetricKey>(k => k.CipherType == cipherType)
            };

            rsaKeyProvider.Setup(kp => kp.VerifyKeyPair(It.IsAny <IAsymmetricKeyPair>()))
            .Returns(false);
            dsaKeyProvider.Setup(kp => kp.VerifyKeyPair(It.IsAny <IAsymmetricKeyPair>()))
            .Returns(false);
            ecKeyProvider.Setup(kp => kp.VerifyKeyPair(It.IsAny <IAsymmetricKeyPair>()))
            .Returns(false);

            Assert.Throws <CryptographicException>(() => { commandHandler.Execute(command); });
        }
Пример #25
0
        public static string Details(this CipherType type)
        {
            switch (type)
            {
            case CipherType.ATBASH:
                return("A trivial substitution cipher based on reversing the indices of the letters of the alphabet.\nFor example, A maps to Z and B maps to Y.");

            case CipherType.ROT13:
                return("A trivial substitution cipher based on swapping the indices of the letters of the halves of the alphabet.\nThis is the same as a Caesar cipher with key N.\nFor example, A maps to N and B maps to O.");

            case CipherType.CAESAR:
                return("A simple substitution cipher based on shifting the letters of the alphabet n places, where n is any integer from 1 to 25.\nIt is broken using a monogram frequency test.");

            default:
                return("No Cipher Details.");
            }
        }
Пример #26
0
            public void ShouldReturnFalseWhenDataLengthExceptionIsThrown(CipherType cipherType)
            {
                var keyPair   = keys[cipherType];
                var signature = signatureProvider.CreateSignature(keyPair.PrivateKey, content);

                var signer = new Mock <ISigner>();

                signer.Setup(s => s.VerifySignature(It.IsAny <byte[]>()))
                .Throws <DataLengthException>();

                var signerUtilities = new Mock <SignerUtilitiesWrapper>();

                signerUtilities.Setup(w => w.GetSigner(It.IsAny <string>()))
                .Returns(signer.Object);

                signatureProvider = new SignatureProvider(algorithmIdentifierMapper, secureRandomGenerator, signerUtilities.Object);
                Assert.IsFalse(signatureProvider.VerifySignature(keyPair.PublicKey, signature));
            }
Пример #27
0
        public static string Decrypt(string cipherText, string key, CipherType cipherType, int n)
        {
            try
            {
                int amount = n;

                string[] textArray = new string[amount];
                int      chunkSize = cipherText.Length / amount;
                int      pos       = 0;
                for (int i = 0; i < amount - 1; ++i)
                {
                    textArray[i] = cipherText.Substring(pos, chunkSize);
                    pos         += chunkSize;
                }
                textArray[amount - 1] = cipherText.Substring(pos);

                string[] resArray = new string[amount];
                ICrypto  cryptor;
                if (cipherType == CipherType.AES)
                {
                    cryptor = new CryptorAES();
                }
                else
                {
                    cryptor = new CryptorDES();
                }

                for (int i = 0; i < amount; ++i)
                {
                    resArray[i] = cryptor.Decrypt(textArray[i], key);
                }
                return(String.Join("", resArray));
            }
            catch (FormatException)
            {
                MessageBox.Show("Некорректные входные данные для дешифрования: входная строка не является шифртекстом");
                return("");
            }
            catch (Exception e)
            {
                MessageBox.Show("Unexpected error: " + e.Message);
                return("");
            }
        }
Пример #28
0
        public static string Name(this CipherType type)
        {
            switch (type)
            {
            case CipherType.ATBASH:
                return("Atbash Cipher");

            case CipherType.ROT13:
                return("ROT13 Cipher");

            case CipherType.CAESAR:
                return("Caesar Shift Cipher");

            case CipherType.AFFINE:
                return("Affine Cipher");

            default:
                return("No Cipher");
            }
        }
Пример #29
0
        public bool Initialize(CipherType type, uint key1, uint key2, ushort keyMod)
        {
            if (keyMod == 0 || type == CipherType.NoChipher || (key1 == 0 && key2 == 0))
            {
                return(Initialize(type, key1, key2));
            }

            var fullKey = (ulong)key2 << 32 | key1;

            unchecked {
                var k2 = ((ulong)keyMod << 16) | (ushort)(~keyMod + 2);

                fullKey = fullKey * k2;
            }

            key1 = (uint)(fullKey & 0xffffffffu);
            key2 = (uint)((fullKey >> 32) & 0xffffffffu);

            return(Initialize(type, key1, key2));
        }
Пример #30
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Password.Length != 0)
            {
                hash ^= Password.GetHashCode();
            }
            if (CipherType != global::V2Ray.Core.Proxy.Shadowsocks.CipherType.Unknown)
            {
                hash ^= CipherType.GetHashCode();
            }
            if (Ota != global::V2Ray.Core.Proxy.Shadowsocks.Account.Types.OneTimeAuth.Auto)
            {
                hash ^= Ota.GetHashCode();
            }
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
        /// <summary>
        ///
        /// </summary>
        public static void ShredDirectory(string path, CipherType cipherType, bool recurse = false, bool nameObfuscation = true, bool propertyObfuscation = true)
        {
            if ((File.GetAttributes(path) & FileAttributes.Directory) != FileAttributes.Directory)
            {
                throw new DirectoryNotFoundException(path);
            }
            if (!Directory.Exists(path))
            {
                throw new DirectoryNotFoundException(path);
            }

            var files = Directory.GetFiles(path);

            foreach (var file in files)
            {
                ShredFile(file, cipherType, nameObfuscation, propertyObfuscation);
            }

            if (recurse)
            {
                var directories = Directory.GetDirectories(path);
                foreach (var directory in directories)
                {
                    ShredDirectory(directory, cipherType, true, nameObfuscation, propertyObfuscation);
                }
            }

            if (propertyObfuscation)
            {
                ObfuscateDirectoryProperties(path);
            }

            if (nameObfuscation)
            {
                path = ObfuscateDirectoryName(path);
            }

            Directory.Delete(path);
        }
Пример #32
0
        public void SetCipherSuite(CipherSuite suite, AsymmetricAlgorithm signAlgo)
        {
            CipherSuiteInfo info = SupportedCipherSuites.GetSuiteInfo (suite);
            if (info == null)
                throw new NotSupportedException ();

            _bulk_cipher = info.BulkCipherAlgorithm;
            _cipherType = info.CipherType;
            _enc_key_length = info.EncKeyLength;
            _block_length = info.BlockLength;
            _fixed_iv_length = info.FixedIVLength;
            _record_iv_length = info.RecordIVLength;
            _mac = info.MACAlgorithm;
            _mac_length = info.MACLength;
            _mac_key_length = info.MACKeyLength;
            _keyExchange = info.KeyExchangeAlgorithm;

            // TODO: TLS1.2spec ?
            switch (_prfType) {
                case PRFAlgorithm.MD5_AND_SHA1: _prf = new MD5_AND_SHA1 (); break;
                case PRFAlgorithm.SSL3: _prf = new SSL3_PRF (this); break;
                default: throw new NotSupportedException ();
            }

            switch (_keyExchange) {
                case KeyExchangeAlgorithm.ECDHE_ECDSA:
                    _keyExchanger = new ECDHE_ECDSA ((openCrypto.EllipticCurve.Signature.ECDSA)signAlgo);
                    break;
                case KeyExchangeAlgorithm.DHE_DSS:
                    _keyExchanger = new DHE_DSS ((DSACryptoServiceProvider)signAlgo);
                    break;
                case KeyExchangeAlgorithm.RSA:
                    _keyExchanger = new KeyExchange.RSA ((RSACryptoServiceProvider)signAlgo);
                    break;
                default:
                    throw new NotImplementedException ();
            }
        }