public static byte[] KrbFxCf2(EncryptionType type, byte[] protocolKey1, byte[] protocolKey2, string pepper1, string pepper2)
        {
            byte[] octetString1 = null;
            byte[] octetString2 = null;
            switch (type)
            {
                case EncryptionType.AES256_CTS_HMAC_SHA1_96:
                case EncryptionType.AES128_CTS_HMAC_SHA1_96:
                    {
                        octetString1 = AesPrfPlus(protocolKey1, Encoding.UTF8.GetBytes(pepper1));
                        octetString2 = AesPrfPlus(protocolKey2, Encoding.UTF8.GetBytes(pepper2));
                        break;
                    }
                case EncryptionType.RC4_HMAC:
                    {
                        octetString1 = Rc4PrfPlus(protocolKey1, Encoding.UTF8.GetBytes(pepper1));
                        octetString2 = Rc4PrfPlus(protocolKey2, Encoding.UTF8.GetBytes(pepper2));
                        break;
                    }
                default:
                    throw new NotSupportedException("Encryption type not support");
            }

            return RandomToKey(type, ExclusiveOr(octetString1, octetString2));
        }
        public static String Encode(EncryptionType type, String algorithm, String plainText, String salt)
        {
            Byte[] arrText = Encoding.Unicode.GetBytes(plainText);
            Byte[] arrSalt = Convert.FromBase64String(salt);
            Byte[] arrAll = new Byte[arrText.Length + arrSalt.Length];
            Byte[] arrResult = null;

            Buffer.BlockCopy(arrText, 0, arrAll, 0, arrText.Length);
            Buffer.BlockCopy(arrSalt, 0, arrAll, arrText.Length, arrSalt.Length);
            //Buffer.BlockCopy(arrSalt, 0, arrAll, 0, arrSalt.Length);
            //Buffer.BlockCopy(arrText, 0, arrAll, arrSalt.Length, arrAll.Length);

            switch (type)
            {
                case EncryptionType.Clear:
                    return plainText;
                case EncryptionType.Hashed:
                    using (HashAlgorithm hashAlgorithm = HashAlgorithm.Create(algorithm))
                    {
                        arrResult = hashAlgorithm.ComputeHash(arrAll);
                    }
                    return Convert.ToBase64String(arrResult);
                case EncryptionType.Encrypted:
                    Byte[] key, iv;
                    GetEncryptionKeyAndIvFromSalt(salt, out key, out iv);
                    arrResult = EncryptStringToBytes(algorithm, Convert.ToBase64String(arrAll), key, iv);
                    return Convert.ToBase64String(arrResult);
                default:
                    throw new InvalidOperationException("Unknown encryption type");
            }
        }
        /// <summary>
        /// Generate key according to password, salt and encryption type
        /// </summary>
        /// <param name="type">encryption type</param>
        /// <param name="password">password</param>
        /// <param name="salt">salt</param>
        /// <returns>the generated key in bytes</returns>
        public static byte[] MakeKey(EncryptionType type, string password, string salt)
        {
            switch (type)
            {
                case EncryptionType.AES128_CTS_HMAC_SHA1_96:
                    {
                        return AesKey.MakeStringToKey(password, salt,
                            AesKey.DEFAULT_ITERATION_COUNT, AesKeyType.Aes128BitsKey);
                    }

                case EncryptionType.AES256_CTS_HMAC_SHA1_96:
                    {
                        return AesKey.MakeStringToKey(password, salt,
                            AesKey.DEFAULT_ITERATION_COUNT, AesKeyType.Aes256BitsKey);
                    }

                case EncryptionType.DES_CBC_CRC:
                case EncryptionType.DES_CBC_MD5:
                    {
                        return DesKey.MakeStringToKey(password, salt);
                    }

                case EncryptionType.RC4_HMAC:
                case EncryptionType.RC4_HMAC_EXP:
                    {
                        return Rc4Key.MakeStringToKey(password);
                    }

                default:
                    throw new ArgumentException("Unsupported encryption type.");
            }
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientRequestWrapper"/> class.
 /// </summary>
 /// <param name="encryptionPublicKey">The encryption public key.</param>
 /// <param name="encryption">The encryption.</param>
 /// <param name="timeStamp">The time stamp.</param>
 /// <param name="request">The request.</param>
 public ClientRequestWrapper(byte[] encryptionPublicKey,
                             EncryptionType encryption, 
                             DateTime timeStamp, 
                             byte [] request)
     : this(encryptionPublicKey, encryption, timeStamp, 0, request)
 {
 }
Example #5
0
 public DataEncrypter(EncryptionType Algo, String Key, String Vector)
 {
     _encryptionAlgorithm = Algo;
     _key = Key;
     _vector = Vector;
     _data = "";
 }
        /// <summary>
        /// Construct a Kerberos test client
        /// </summary>
        /// <param name="domain">The realm part of the client's principal identifier.
        /// This argument cannot be null.</param>
        /// <param name="cName">The account to logon the remote machine. Either user account or computer account
        /// This argument cannot be null.</param>
        /// <param name="password">The password of the user. This argument cannot be null.</param>
        /// <param name="accountType">The type of the logon account. User or Computer</param>
        public KerberosFunctionalClient(string domain, string cName, string password, KerberosAccountType accountType, string kdcAddress, int kdcPort, TransportType transportType, KerberosConstValue.OidPkt oidPkt, ITestSite baseTestSite,string salt = null)
            : base(domain, cName, password, accountType, kdcAddress, kdcPort, transportType, oidPkt, salt)
        {
            testSite = baseTestSite;
            if (accountType == KerberosAccountType.Device)
            {
                testSite.Log.Add(LogEntryKind.Debug, "Construct Kerberos client using computer account: {0}@{1}.",
                                    cName, domain);
            }
            else
            {
                testSite.Log.Add(LogEntryKind.Debug, "Construct Kerberos client using user account: {0}@{1}.",
                                    cName, domain);
            }
            EncryptionType[] encryptionTypes = new EncryptionType[]
            {
                EncryptionType.AES256_CTS_HMAC_SHA1_96,
                EncryptionType.AES128_CTS_HMAC_SHA1_96,
                EncryptionType.RC4_HMAC,
                EncryptionType.RC4_HMAC_EXP,
                EncryptionType.DES_CBC_CRC,
                EncryptionType.DES_CBC_MD5
            };

            KerbInt32[] etypes = new KerbInt32[encryptionTypes.Length];
            for (int i = 0; i < encryptionTypes.Length; i++)
            {
                etypes[i] = new KerbInt32((int)encryptionTypes[i]);
            }
            Asn1SequenceOf<KerbInt32> etype = new Asn1SequenceOf<KerbInt32>(etypes);

            Context.SupportedEType = etype;

            Context.Pvno = KerberosConstValue.KERBEROSV5;
        }
Example #7
0
        public static string Encrypt(string text, EncryptionType CryptType)
        {
            string retVal = text;
            //if (CryptType & EncryptionType.SIMPLE) {
            //    retVal = SimpleEncrypt(retVal);
            //}

            //if (CryptType & EncryptionType.HEX) {
            //    retVal = HexEncode(retVal);
            //}

            //if (CryptType & EncryptionType.REVERSE) {
            //    retVal = Strings.StrReverse(retVal);
            //}

            //if (CryptType & EncryptionType.BASE64) {
            //    retVal = Base64Encode(retVal);
            //}

            //if (CryptType & EncryptionType.ASCII) {
            //    retVal = ASCIIEncode(retVal);
            //}

            return retVal;
        }
        public KeyPair GenerateKeypair(EncryptionType encryption)
        {
            int modulus;
            switch (encryption)
            {
                case EncryptionType.RSA_512:
                    modulus = 512;
                    break;

                case EncryptionType.RSA_1024:
                    modulus = 1024;
                    break;

                case EncryptionType.RSA_1536:
                    modulus = 1536;
                    break;

                case EncryptionType.RSA_2048:
                    modulus = 2048;
                    break;

                case EncryptionType.RSA_4096:
                    modulus = 4096;
                    break;

                default:
                    throw new ArgumentException("encryption");
            }

            KeyPair kp = null;

            using (var rsa = new RSACryptoServiceProvider(modulus))
            {
                try
                {
                    var privParams = rsa.ExportParameters(true);
                    var pubParams = rsa.ExportParameters(false);

                    var privBlob = rsa.ToXmlString(true);
                    var pubBlob = rsa.ToXmlString(false);

                    kp = new KeyPair
                    {
                        PrivKey = privBlob,
                        PubKey = pubBlob
                    };
                }
                catch (Exception)
                {
                    throw;
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }

            return kp;
        }
Example #9
0
 public Preferences()
 {
     _algorithm = EncryptionType.TripleDES;
     _password = "******";
     _key = "abcdefghijklmnopqrstuvwx";
     _defaultPath = "\\Windows\\SNOP";
     _AskPassword = true;
 }
 public MailConnection(EncryptionType encryption, string server, int port, string username, string password)
 {
     _encryption = encryption;
     _server = server.Trim();
     _port = port;
     _username = username.Trim();
     _password = password.Trim();
 }
 /// <summary>
 /// RC4-HMAC / RC4-HMAC-EXP decryption
 /// </summary>
 /// <param name="key">the secret key</param>
 /// <param name="cipher">the encrypted cipher data</param>
 /// <param name="usage">key usage number</param>
 /// <param name="encryptionType">encryption type</param>
 /// <returns>the decrypted data</returns>
 public static byte[] Decrypt(
     byte[] key,
     byte[] cipher,
     int usage,
     EncryptionType encryptionType)
 {
     return Decrypt(key, cipher, usage, encryptionType, null);
 }
Example #12
0
 public frmProperties(EncryptionType Type, String sPassword, String sKey, bool AskPass)
 {
     InitializeComponent();
     _algorithm = Type;
     _isCanceled = true;
     _password = sPassword;
     _key = sKey;
     _askPassword = AskPass;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ClientRequestWrapper"/> class.
 /// </summary>
 /// <param name="encryptionPublicKey">The encryption public key.</param>
 /// <param name="encryption">The encryption.</param>
 /// <param name="timeStamp">The time stamp.</param>
 /// <param name="crc32">The CR C32.</param>
 /// <param name="request">The request.</param>
 public ClientRequestWrapper(byte[] encryptionPublicKey,
         EncryptionType encryption, DateTime timeStamp,
         uint crc32, byte [] request)
 {
     _publicKey = encryptionPublicKey;
     _encryption = encryption;
     _timestamp = timeStamp;
     _crc32 = crc32;
     _request = request;
 }
Example #14
0
 /// <summary>
 /// Allows adding a new server with the added option of specifying the encryption type if any and whether the server needs any authentication.
 /// </summary>
 /// <param name="host">Hostname/IP Address for server.</param>
 /// <param name="port">Port to be used to connect to server.</param>
 /// <param name="username">Username for authentication.</param>
 /// <param name="password">Password for authentication.</param>
 /// <param name="RequiresAuthentication">true if authentication is needed, false otherwise.</param>
 /// <param name="EncType">Encryption type see EncryptionType enumeration.</param>
 public Server(string host, int port, string username, string password,bool RequiresAuthentication, EncryptionType EncType)
 {
     this.Host = host;
     this.Port = port;
     this.Username = username;
     this.Password = password;
     _requiresAuthentication = RequiresAuthentication;
     _encType = EncType;
     
 }
 /// <summary>
 /// We-use the remote info as: accountName = awsAccessKeyId and accountKey = awsSecretAccessKey
 /// </summary>
 public AmazonS3Synchronizer(RemoteInfo remoteInfo, string bucket, SynchronizeDirection syncDirection, CompressionType compressionType, EncryptionType encryptionType, byte[] encryptionKey, byte[] initializationVector, Logger log, int ChunkSize,  int ThreadPoolSize = 1 )
 {
     this.logger = log;
     disposed = false;
     this.syncDirection = syncDirection;
     bucketName = bucket.ToString().Replace(' ', '-').ToLower(); ;// amazon S3 does not like spaces in bucket names
     
     amazonS3Helper = new AmazonS3Helper(remoteInfo, bucket, compressionType, encryptionType, encryptionKey, initializationVector, logger, ChunkSize, ThreadPoolSize);
     this.MaxConcurrentFileSyncThreads = ThreadPoolSize;
 }
Example #16
0
        public static byte[] Decrypt(byte[] encrypted, EncryptionType encType, string userPassword)
        {
            if (encType == EncryptionType.None)
                return encrypted;

            // Decrypt second pass (AES/PBKDF2)
            byte[] secondPassDecrypt;

            if (encType.HasFlag(EncryptionType.Password))
            {
                try
                {
                    secondPassDecrypt = AESDecrypt(encrypted, userPassword);
                }
                catch (Exception) { return null; }
            }
            else
            {
                secondPassDecrypt = encrypted;
            }

            // Decrypt first pass (Machine/User Lock)
            byte[] decrypted;

            if (encType.HasFlag(EncryptionType.LocalUser) || encType.HasFlag(EncryptionType.LocalMachine))
            {
                try
                {
                    decrypted = MachineDecrypt(secondPassDecrypt, encType);
                }
                catch (Exception) { return null; }
            }
            else
            {
                decrypted = secondPassDecrypt;
            }

            // Verify token signature
            if (decrypted.Length != 30)
                return null;

            byte[] token = new byte[20];
            Array.Copy(decrypted, token, 20);

            byte[] signature = new byte[10];
            Array.Copy(decrypted, 20, signature, 0, 10);

            byte[] expectedSignature = SignToken(token);

            if (expectedSignature.SequenceEqual(signature))
                return token;

            return null;
        }
        /// <summary>
        /// RC4-HMAC / RC4-HMAC-EXP decryption
        /// </summary>
        /// <param name="key">the secret key</param>
        /// <param name="cipher">the encrypted cipher data</param>
        /// <param name="usage">key usage number</param>
        /// <param name="encryptionType">encryption type</param>
        /// <param name="getToBeSignedDateCallback">
        /// A callback to get to-be-signed data. 
        /// The method will use decrypted data directly if this parameter is null.
        /// </param>
        /// <returns>the decrypted data</returns>
        public static byte[] Decrypt(
            byte[] key,
            byte[] cipher,
            int usage,
            EncryptionType encryptionType,
            GetToBeSignedDataFunc getToBeSignedDateCallback)
        {
            // check inputs
            if (null == key)
            {
                throw new ArgumentNullException("key");
            }
            if (null == cipher)
            {
                throw new ArgumentNullException("cipher");
            }

            // get checksum and encrypted data
            byte[] checksum = ArrayUtility.SubArray(cipher, 0, ConstValue.MD5_CHECKSUM_SIZE);
            byte[] encryptedData = ArrayUtility.SubArray(cipher, ConstValue.MD5_CHECKSUM_SIZE);

            // get salt and hash
            byte[] salt = GetSalt(usage, encryptionType);
            byte[] hash = CryptoUtility.ComputeMd5Hmac(key, salt);
            byte[] hashExp = GetExpHash(hash, encryptionType);

            // get rc4 decryption key
            byte[] rc4Key = CryptoUtility.ComputeMd5Hmac(hashExp, checksum);

            // decrypt
            ICryptoTransform decryptor = CryptoUtility.CreateRc4Decryptor(rc4Key);
            byte[] plain = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);

            byte[] toBeSignedData;
            if (getToBeSignedDateCallback != null)
            {
                toBeSignedData = getToBeSignedDateCallback(plain);
            }
            else
            {
                toBeSignedData = plain;
            }

            // verify checksum
            byte[] expectedChecksum = CryptoUtility.ComputeMd5Hmac(hash, toBeSignedData);
            if (!ArrayUtility.CompareArrays(checksum, expectedChecksum))
            {
                throw new FormatException("Decryption: invalid checksum.");
            }

            // remove confounder
            return ArrayUtility.SubArray(plain, ConstValue.CONFOUNDER_SIZE);
        }
 //protected SyncOrchestrator orchestrator;
 public AzureChunkSynchronizer(RemoteInfo ri, string container, SynchronizeDirection syncDirection, CompressionType compressionType, EncryptionType encryptionType, byte[] encryptionKey, byte[] initializationVector, Logger log, int ChunkSize, int ThreadPoolSize=1)
 {
     logger = log;
     disposed = false;
     // Setup Store and Provider
     //
     this.accountName = ri.accountName;
     this.accountKey = ri.accountKey;
     this.container = container;
     this.syncDirection = syncDirection;
     this.azureHelper = new AzureHelper(this.accountName, this.accountKey, this.container, compressionType, encryptionType, encryptionKey, initializationVector, log, ChunkSize, ThreadPoolSize);
     this.chunkListHash = null;
     this.ThreadPoolSize = ThreadPoolSize;
 }
        public static IEncryption GetInstance(EncryptionType encryptionType)
        {
            switch (encryptionType)
            {
                case EncryptionType.AesEncryiption:
                    return new AesEncryption();

                case EncryptionType.TripleDes:
                    return new TripleDESEncyption();

                default:
                    throw new ArgumentOutOfRangeException("Not found encryption type in encrypted list!");
            }
        }
 /// <summary>
 /// Make keys for given encryption types.
 /// </summary>
 /// <param name="principal">Principal name</param>
 /// <param name="realm">Realm</param>
 /// <param name="password">Password</param>
 /// <param name="salt">Salt</param>
 /// <param name="type">Encryption type</param>
 public void MakeKey(string principal, string realm, string password, string salt, EncryptionType type)
 {
     EncryptionKey key = KerberosUtility.MakeKey(type, password, salt);
     var ExistingKey = QueryKey(principal, realm, type);
     if (ExistingKey != null) throw new Exception("Key already exists.");
     KeytabItem item = new KeytabItem()
     {
         Principal = principal,
         Realm = realm,
         Kvno = 0, // Set to 0 for self generated keys.
         KeyType = type,
         Key = key
     };
     keytabItems.Add(item);
 }
         public AmazonS3Helper(RemoteInfo remoteInfo,  string bucketName, CompressionType chunkCompression, EncryptionType chunkEncryption , byte[] encryptionKey , byte[] initializationVector, Logger log, int ChunkSize, int ThreadPoolSize)
        {
            this.logger = log;
            this.remoteInfo = remoteInfo;
            this.bucketName = bucketName;
            this.chunkCompressionType = chunkCompression;
            this.chunkEncryptionType = chunkEncryption;
            this.encryptionKey = encryptionKey;
            this.InitializationVector = initializationVector;
            amazonS3Client = new AmazonS3Client(remoteInfo.accountName, remoteInfo.accountKey);
            this.StaticChunkSize = ChunkSize;
            this.MaxConcurrentUploadThreads = ThreadPoolSize;

            this.disposed = false;
            CreateBucket(this.bucketName);
        }
 public ISync CreateSynchronizer(LocationInfo Li, string container, Logger log, SynchronizeDirection syncDirection = SynchronizeDirection.Upload, CompressionType compressionType = CompressionType.None, int ChunkSizeForUpload = 4*1024*1024, int ThreadPoolSize =1 ,   EncryptionType encryptionType = EncryptionType.None , byte[] encryptionKey = null, byte[] initializationVector =null)
 {
     ISync isync = null;
     switch (Li.st)
     {
         case SynchronizerType.Azure:
             isync = CreateAzureSynchronizer(new RemoteInfo(Li.accountName, Li.accountKey), container, log, syncDirection, compressionType, ChunkSizeForUpload, ThreadPoolSize, encryptionType, encryptionKey, initializationVector);
             break;
         case SynchronizerType.AmazonS3:
             isync = CreateAmazonS3Synchronizer(new RemoteInfo(Li.accountName, Li.accountKey), container, log, syncDirection, compressionType, ChunkSizeForUpload, ThreadPoolSize, encryptionType, encryptionKey, initializationVector);
             break;
         default:
             isync = null;
             break;
     }
     return isync;
 }
 public static String Decode(EncryptionType type, String algorithm, String cipherText, String salt)
 {
     switch (type)
     {
         case EncryptionType.Clear:
             return cipherText;
         case EncryptionType.Hashed:
             throw new InvalidOperationException("Hashed value cannot be decoded");
         case EncryptionType.Encrypted:
             Byte[] arrCipher = Convert.FromBase64String(cipherText);
             Byte[] key, iv;
             GetEncryptionKeyAndIvFromSalt(salt, out key, out iv);
             String plainText = DecryptStringFromBytes(algorithm, arrCipher, key, iv);
             // strip the salt
             Byte[] arrText = Convert.FromBase64String(plainText);
             //plainText = Encoding.Unicode.GetString(arrText, key.Length, arrText.Length - key.Length);
             plainText = Encoding.Unicode.GetString(arrText, 0, arrText.Length);
             return plainText;
         default:
             throw new InvalidOperationException("Unknown encryption type");
     }
 }
Example #24
0
        public IPDTPacket(string source, string dest, string hash, string dataType, int sessionid, int processid, EncryptionType encryptiontype, Encoding encoding, string NETNAME, string Data)
        {
            SourceAdress      = source;
            DestinationAdress = dest;
            Hash               = hash;
            DataType           = dataType;
            SessionID          = sessionid;
            ProcessID          = processid;
            DataEncryptionType = encryptiontype;
            ContentEncoding    = encoding;
            Networkname        = NETNAME;

            if (encryptiontype == EncryptionType.DECRYP)
            {
                Content    = Security.BFromBase64(Data, encoding);
                ContentB64 = Convert.ToBase64String(Content);
            }
            else if (encryptiontype == EncryptionType.DPL128)
            {
                Content    = Security.BFromBase64(Security.Decrypt(Data), encoding);
                ContentB64 = Convert.ToBase64String(Content);
            }
            else
            {
                Content    = Security.BFromBase64(Security.DecryptTripleDES(Data, PacketBuilder.password), encoding);
                ContentB64 = Convert.ToBase64String(Content);
            }
        }
Example #25
0
        /// <summary>
        /// We-use the remote info as: accountName = awsAccessKeyId and accountKey = awsSecretAccessKey
        /// </summary>
        public AmazonS3Synchronizer(RemoteInfo remoteInfo, string bucket, SynchronizeDirection syncDirection, CompressionType compressionType, EncryptionType encryptionType, byte[] encryptionKey, byte[] initializationVector, Logger log, int ChunkSize, int ThreadPoolSize = 1)
        {
            this.logger        = log;
            disposed           = false;
            this.syncDirection = syncDirection;
            bucketName         = bucket.ToString().Replace(' ', '-').ToLower();;// amazon S3 does not like spaces in bucket names

            amazonS3Helper = new AmazonS3Helper(remoteInfo, bucket, compressionType, encryptionType, encryptionKey, initializationVector, logger, ChunkSize, ThreadPoolSize);
            this.MaxConcurrentFileSyncThreads = ThreadPoolSize;
        }
 // The same as its overload that getToBeSignedDateCallback = null
 public static byte[] Encrypt(EncryptionType type, byte[] sessionKey, byte[] plainData, int usage)
 {
     return(Encrypt(type, sessionKey, plainData, usage, null));
 }
 /// <summary>
 /// Make fast armor key
 /// </summary>
 /// <param name="type">Encryption type</param>
 /// <param name="subkey">Subkey, generated by client</param>
 /// <param name="sessionKey">Session key, generated by kdc</param>
 /// <returns></returns>
 public static byte[] MakeArmorKey(EncryptionType type, byte[] subkey, byte[] sessionKey)
 {
     return(KeyGenerator.KrbFxCf2(type, subkey, sessionKey, "subkeyarmor", "ticketarmor"));
 }
Example #28
0
 public static void UnregisterCryptographicAlgorithm(EncryptionType encryptionType)
 {
     CryptoAlgorithms.Remove(encryptionType);
 }
Example #29
0
 public static bool SupportsEType(EncryptionType etype)
 {
     return(CryptoAlgorithms.ContainsKey(etype));
 }
Example #30
0
        protected override void OnEVH()
        {
            switch (step)
            {
            case 1:
                parallelism = encVal.Length;
                encType     = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    Numeric enckaa = program.GetValue(code.operand1);
                    encVal = new NumericArray(enckaa);
                    length = Config.NumericBits;
                    if (encVal[0].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (encVal[0].GetUnsignedBigInteger() == 0)
                        {
                            encH = new NumericArray(new Numeric(1, 0));
                        }
                        else
                        {
                            encH = new NumericArray(new Numeric(0, 0));
                        }
                        // jump to round 4
                        step = 3;
                        Run();
                        break;
                    }
                }
                new HammingDistanceOnEVH(party, line, this, encVal, encH, length).Run();
                break;

            case 2:
                new FastEqualZeroOnEVH(party, line, this, encH, encH, (int)Math.Ceiling(Math.Log(length + 1, 2))).Run();
                break;

            case 3:
                // as subfunction, the result should be 0 if secret == 0
                // however the result from FastEqualZero if 1 if secret == 0
                if (ReferenceEquals(code, null))
                {
                    for (int p = 0; p < parallelism; p++)
                    {
                        encH[p] ^= new Numeric(1, 0);
                    }
                }
                Run();
                break;

            case 4:
                SetResult(encType, encH.GetArray());
                break;

            case 5:
                InvokeCaller();
                break;

            default:
                throw new Exception();
                ////System.Diagnostics.Debug.Assert(le >= 2 || le == 0);
                //if (le > 2)
                //{
                //    le = (int)Math.Ceiling(Math.Log(le + 1, 2));
                //    new HammingDistanceOnEVH(party, line, this, encH, encH, le).Run();
                //}
                //else if (le == 2)
                //{
                //    var OROperand = new Numeric[2 * parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        OROperand[2 * p] = encH[p] >> 1;
                //        OROperand[2 * p + 1] = encH[p].ModPow(1);
                //    }
                //    le = 0;
                //    new OROnEVH(party, line, this, new NumericArray(OROperand), encH).Run();
                //}
                //else
                //{
                //    Numeric[] enckf = new Numeric[parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        enckf[p] = encH[p].ModPow(1);
                //        //enckf[p].SetEncType(EncryptionType.XOR);
                //    }
                //    if(!ReferenceEquals(code, null))
                //    {
                //        // not as a subfunction
                //        enckf[0] ^= new Numeric(1, 0);
                //    }
                //    SetResult(enckf);
                //}
                //break;
            }
        }
Example #31
0
        public string ProcessEncryptionTypeof(string input, EncryptionType encryptionType)
        {
            try
            {
                lock (encryptionResult)
                {
                    Stopwatch watch = new Stopwatch();
                    watch.Start();
                    Cursor = Cursors.WaitCursor;
                    switch (encryptionType)
                    {
                    case EncryptionType.Cesar:
                        try
                        {
                            //resultBox.Text = Encryption.CesarEncryption(inputText.Text,
                            //    Convert.ToInt32(cesarEncryptionOffset.Value));

                            encryptionResult = Encryption.CesarEncryption(input,
                                                                          Convert.ToInt32(cesarEncryptionOffset.Value));
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;

                    case EncryptionType.TextBased:
                        try
                        {
                            //resultBox.Text = Encryption.TextBasedEncryption(inputText.Text,
                            //    textBasedEncryptionKey.Text);

                            encryptionResult = Encryption.TextBasedEncryption(input,
                                                                              textBasedEncryptionKey.Text);
                        }
                        catch (Exception e)
                        {
                            if (e.GetType().Equals(typeof(IndexOutOfRangeException)))
                            {
                                MessageBox.Show("Please fill the Key text box !", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;

                    case EncryptionType.Substitution:
                        try
                        {
                            List <char> chars = new List <char>();

                            #region Adding Chars To List

                            chars.Add(substitutionChar0.Text[0]);
                            chars.Add(substitutionChar1.Text[0]);
                            chars.Add(substitutionChar2.Text[0]);
                            chars.Add(substitutionChar3.Text[0]);
                            chars.Add(substitutionChar4.Text[0]);
                            chars.Add(substitutionChar5.Text[0]);
                            chars.Add(substitutionChar6.Text[0]);
                            chars.Add(substitutionChar7.Text[0]);
                            chars.Add(substitutionChar8.Text[0]);
                            chars.Add(substitutionChar9.Text[0]);
                            chars.Add(substitutionChar10.Text[0]);
                            chars.Add(substitutionChar11.Text[0]);
                            chars.Add(substitutionChar12.Text[0]);
                            chars.Add(substitutionChar13.Text[0]);
                            chars.Add(substitutionChar14.Text[0]);
                            chars.Add(substitutionChar15.Text[0]);
                            chars.Add(substitutionChar16.Text[0]);
                            chars.Add(substitutionChar17.Text[0]);
                            chars.Add(substitutionChar18.Text[0]);
                            chars.Add(substitutionChar19.Text[0]);
                            chars.Add(substitutionChar20.Text[0]);
                            chars.Add(substitutionChar21.Text[0]);
                            chars.Add(substitutionChar22.Text[0]);
                            chars.Add(substitutionChar23.Text[0]);
                            chars.Add(substitutionChar24.Text[0]);
                            chars.Add(substitutionChar25.Text[0]);

                            #endregion Adding Chars To List

                            //resultBox.Text = Encryption.SubstitutionEncryption(inputText.Text, chars);

                            encryptionResult = Encryption.SubstitutionEncryption(input, chars);
                        }
                        catch (Exception e)
                        {
                            if (e.Equals(typeof(IndexOutOfRangeException)))
                            {
                                MessageBox.Show("Fill all characters substitutions please!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                            else
                            {
                                MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                        break;

                    case EncryptionType.Polybe:
                        try
                        {
                            char[,] table = new char[polybeTable.RowCount, polybeTable.ColumnCount];
                            for (int i = 0; i < table.GetLength(0); i++)
                            {
                                for (int j = 0; j < table.GetLength(1); j++)
                                {
                                    if (polybeTable[j, i].Value != null)
                                    {
                                        table[i, j] = Convert.ToChar(polybeTable[j, i].Value);
                                    }
                                }
                            }
                            if (lineColumnTypeRadioButtonPolybe.Checked)
                            {
                                encryptionResult = Encryption.PolybeEncryption(input, table, Encryption.PolybeType.LineColumn);
                            }
                            else if (columnLineTypeRadioButtonPolybe.Checked)
                            {
                                encryptionResult = Encryption.PolybeEncryption(input, table, Encryption.PolybeType.ColumnLine);
                            }
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;

                    case EncryptionType.ToBinary:
                        try
                        {
                            string separator = separatorToBinaryEncryption.Text;
                            int    fillBits  = Convert.ToInt32(fillBitsToBinaryEncryption.Value);

                            if (normalTypeRadioButtonToBinary.Checked)
                            {
                                encryptionResult = Encryption.ToBinaryEncryption(input, Encryption.ToBinaryType.Normal, fillBits, separator);
                            }
                            else if (cp1TypeRadioButtonToBinary.Checked)
                            {
                                encryptionResult = Encryption.ToBinaryEncryption(input, Encryption.ToBinaryType.CP1, fillBits, separator);
                            }
                            else if (cp2TypeRadioButtonToBinary.Checked)
                            {
                                encryptionResult = Encryption.ToBinaryEncryption(input, Encryption.ToBinaryType.CP2, fillBits, separator);
                            }
                        }
                        catch (Exception e)
                        {
                            MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                        break;

                    default:
                        throw new Exception("Unexpected Exception" +
                                            "\nWhooops! Something went wrong::Unkown encryption type");
                    }
                    Cursor = Cursors.Default;
                    watch.Stop();
                    elapsedTimeLabel.Text = watch.Elapsed.TotalSeconds.ToString() + "s";

                    return(encryptionResult);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.GetType().ToString() + " EXCEPTION: " + e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return(null);
            }
        }
Example #32
0
		public ProfileItem(
			string name,
			Guid interfaceId,
			string interfaceName,
			string interfaceDescription,
			AuthenticationMethod authentication,
			EncryptionType encryption,
			int position,
			bool isAutomatic,
			int signal,
			bool isConnected)
		{
			if (string.IsNullOrWhiteSpace(name))
				throw new ArgumentNullException(nameof(name));

			if (interfaceId == Guid.Empty)
				throw new ArgumentException(nameof(interfaceId));

			this.Name = name;
			this.InterfaceId = interfaceId;
			this.InterfaceName = interfaceName;
			this.InterfaceDescription = interfaceDescription;
			this.Authentication = authentication;
			this.Encryption = encryption;
			this.Position = position;
			this.IsAutomatic = isAutomatic;
			this.Signal = signal;
			this.IsConnected = isConnected;
		}
Example #33
0
        public KileTgsResponse CreateTgsResponse(
            KileConnection kileConnection,
            Asn1SequenceOf <PA_DATA> seqOfPaData,
            EncTicketFlags encTicketFlags,
            EncryptionKey ticketEncryptKey,
            AuthorizationData ticketAuthorizationData)
        {
            KileServerContext serverContext = GetServerContextByKileConnection(kileConnection);

            if (ticketEncryptKey == null)
            {
                throw new ArgumentNullException(nameof(ticketEncryptKey));
            }
            else
            {
                serverContext.TicketEncryptKey = ticketEncryptKey;
            }
            var response = new KileTgsResponse(serverContext);

            // Construct a Ticket
            var ticket = new Ticket();

            ticket.tkt_vno = new Asn1Integer(ConstValue.KERBEROSV5);
            ticket.realm   = new Realm(domain);
            ticket.sname   = serverContext.SName;

            // Set EncTicketPart
            var            encTicketPart  = new EncTicketPart();
            EncryptionType encryptionType = (EncryptionType)serverContext.EncryptType.Elements[0].Value;

            encTicketPart.key                = new EncryptionKey(new KerbInt32((int)encryptionType), new Asn1OctetString(GetEncryptionKeyByType(encryptionType)));
            encTicketPart.flags              = new TicketFlags(KileUtility.ConvertInt2Flags((int)encTicketFlags));
            encTicketPart.crealm             = serverContext.TgsTicket.crealm;
            encTicketPart.cname              = serverContext.TgsTicket.cname;
            encTicketPart.transited          = serverContext.TgsTicket.transited;
            encTicketPart.authtime           = KileUtility.CurrentKerberosTime;
            encTicketPart.starttime          = KileUtility.CurrentKerberosTime;
            encTicketPart.endtime            = serverContext.TgsTicket.endtime;
            encTicketPart.renew_till         = serverContext.TgsTicket.renew_till;
            encTicketPart.caddr              = serverContext.Addresses;
            encTicketPart.authorization_data = ticketAuthorizationData;
            response.TicketEncPart           = encTicketPart;

            // Set AS_REP
            response.Response.pvno     = new Asn1Integer(ConstValue.KERBEROSV5);
            response.Response.msg_type = new Asn1Integer((int)MsgType.KRB_TGS_RESP);
            response.Response.padata   = seqOfPaData;
            response.Response.crealm   = serverContext.UserRealm;
            response.Response.cname    = serverContext.UserName;
            response.Response.ticket   = ticket;

            // Set EncASRepPart
            var encTGSRepPart = new EncTGSRepPart();

            encTGSRepPart.key = encTicketPart.key;
            var element = new LastReqElement(new KerbInt32(0), KileUtility.CurrentKerberosTime);

            encTGSRepPart.last_req   = new LastReq(new LastReqElement[] { element });
            encTGSRepPart.nonce      = serverContext.Nonce;
            encTGSRepPart.flags      = encTicketPart.flags;
            encTGSRepPart.authtime   = encTicketPart.authtime;
            encTGSRepPart.starttime  = encTicketPart.starttime;
            encTGSRepPart.endtime    = encTicketPart.endtime;
            encTGSRepPart.renew_till = encTicketPart.renew_till;
            encTGSRepPart.srealm     = ticket.realm;
            encTGSRepPart.sname      = ticket.sname;
            encTGSRepPart.caddr      = encTicketPart.caddr;
            response.EncPart         = encTGSRepPart;

            return(response);
        }
Example #34
0
        public KileAsResponse CreateAsResponse(
            KileConnection kileConnection,
            KileAccountType accountType,
            string password,
            Asn1SequenceOf <PA_DATA> SeqofPaData,
            EncTicketFlags encTicketFlags,
            AuthorizationData ticketAuthorizationData)
        {
            KileServerContext serverContext = GetServerContextByKileConnection(kileConnection);
            string            cName         = serverContext.UserName.name_string.Elements[0].Value;
            string            cRealm        = serverContext.UserRealm.Value;

            serverContext.Salt             = GenerateSalt(cRealm, cName, accountType);
            serverContext.TicketEncryptKey = new EncryptionKey(new KerbInt32((int)EncryptionType.RC4_HMAC),
                                                               new Asn1OctetString(GetEncryptionKeyByType(EncryptionType.RC4_HMAC)));

            if (password == null)
            {
                throw new ArgumentNullException(nameof(password));
            }
            else
            {
                serverContext.Password = password;
            }
            KileAsResponse response = new KileAsResponse(serverContext);

            // Construct a Ticket
            var ticket = new Ticket();

            ticket.tkt_vno = new Asn1Integer(ConstValue.KERBEROSV5);
            ticket.realm   = new Realm(domain);
            ticket.sname   = serverContext.SName;

            // Set EncTicketPart
            var            encTicketPart  = new EncTicketPart();
            EncryptionType encryptionType = (EncryptionType)serverContext.EncryptType.Elements[0].Value;

            encTicketPart.key                = new EncryptionKey(new KerbInt32((int)encryptionType), new Asn1OctetString(GetEncryptionKeyByType(encryptionType)));
            encTicketPart.flags              = new TicketFlags(KileUtility.ConvertInt2Flags((int)encTicketFlags));
            encTicketPart.crealm             = serverContext.UserRealm;
            encTicketPart.cname              = serverContext.UserName;
            encTicketPart.transited          = new TransitedEncoding(new KerbInt32(4), null);
            encTicketPart.authtime           = KileUtility.CurrentKerberosTime;
            encTicketPart.starttime          = KileUtility.CurrentKerberosTime;
            encTicketPart.endtime            = serverContext.endTime;
            encTicketPart.renew_till         = serverContext.rtime ?? encTicketPart.endtime;
            encTicketPart.caddr              = serverContext.Addresses;
            encTicketPart.authorization_data = ticketAuthorizationData;
            response.TicketEncPart           = encTicketPart;

            // Set AS_REP
            response.Response.pvno     = new Asn1Integer(ConstValue.KERBEROSV5);
            response.Response.msg_type = new Asn1Integer((int)MsgType.KRB_AS_RESP);
            response.Response.padata   = SeqofPaData;
            response.Response.crealm   = serverContext.UserRealm;
            response.Response.cname    = serverContext.UserName;
            response.Response.ticket   = ticket;

            // Set EncASRepPart
            var encASRepPart = new EncASRepPart();

            encASRepPart.key = encTicketPart.key;
            var element = new LastReqElement(new KerbInt32(0), KileUtility.CurrentKerberosTime);

            encASRepPart.last_req   = new LastReq(new LastReqElement[] { element });
            encASRepPart.nonce      = serverContext.Nonce;
            encASRepPart.flags      = encTicketPart.flags;
            encASRepPart.authtime   = encTicketPart.authtime;
            encASRepPart.starttime  = encTicketPart.starttime;
            encASRepPart.endtime    = encTicketPart.endtime;
            encASRepPart.renew_till = encTicketPart.renew_till;
            encASRepPart.srealm     = ticket.realm;
            encASRepPart.sname      = ticket.sname;
            encASRepPart.caddr      = encTicketPart.caddr;
            response.EncPart        = encASRepPart;

            return(response);
        }
Example #35
0
 public void WhitelistCryptoTo(EncryptionType CT)
 {
     CryptoType   = (CT == EncryptionType.BDCryptoV1);
     WhiteListing = true;
 }
        /// <summary>
        /// Make keys for given encryption types.
        /// </summary>
        /// <param name="principal">Principal name</param>
        /// <param name="realm">Realm</param>
        /// <param name="password">Password</param>
        /// <param name="salt">Salt</param>
        /// <param name="type">Encryption type</param>
        public void MakeKey(string principal, string realm, string password, string salt, EncryptionType type)
        {
            EncryptionKey key         = KerberosUtility.MakeKey(type, password, salt);
            var           existingKey = QueryKey(principal, realm, type);

            if (existingKey != null)
            {
                throw new Exception("Key already exist.");
            }
            KeytabItem item = new KeytabItem()
            {
                Principal = principal,
                Realm     = realm,
                Kvno      = 0, // Set to 0 for self generated keys.
                KeyType   = type,
                Key       = key
            };

            keytabItems.Add(item);
        }
 public void AddEncryptionData(EncryptionType encryptionType, string ktb)
 {
     AddEncryptionData(encryptionType, ktb, null);
 }
        ////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Set encryption
        /// </summary>
        /// <param name="UserPassword">User password</param>
        /// <param name="OwnerPassword">Owner password</param>
        /// <param name="Permissions">Permission flags</param>
        /// <param name="EncryptionType">Encryption type</param>
        /// <remarks>
        /// The PDF File Writer library will encrypt the PDF document
        /// using either AES-128 encryption or standard 128 (RC4) encryption.
        /// Encryption type is specified by the last argument. Note: the 
        /// standard 128 (RC4) is considered unsafe and should not be used.
        /// User and owner passwords are as per
        /// the two arguments. A PDF reader such as Acrobat will request the 
        /// user to enter a password. The user can supply either the user
        /// or the owner password. Permissions flags are set as per argument.
        /// </remarks>
        ////////////////////////////////////////////////////////////////////
        public void SetEncryption(
			String		UserPassword,
			String		OwnerPassword,
			Permission	Permissions,
			EncryptionType EncryptionType = EncryptionType.Aes128
			)
        {
            // encryption can be set only once
            if(Encryption != null) throw new ApplicationException("Encryption is already set");

            // create encryption dictionary object
            Encryption = new PdfEncryption(this, UserPassword, OwnerPassword, Permissions, EncryptionType);

            // exit
            return;
        }
 public void SendMessage(MessageType msg_type, object message,
                          EncryptionType encryption = EncryptionType.kDefaultEncryption,
                          TransportProtocol protocol = TransportProtocol.kDefault,
                          string expected_reply_type = null, float expected_reply_time = 0f,
                          TimeoutEventHandler onReplyMissed = null)
 {
     string _msg_type = MessageTable.Lookup(msg_type);
     SendMessage(_msg_type, message, encryption, protocol, expected_reply_type, expected_reply_time, onReplyMissed);
 }
Example #40
0
        protected bool doHandshaking(string encryption_type, string encryption_header)
        {
            if (encryption_type == kEncryptionHandshakeBegin)
            {
                // encryption list
                List <EncryptionType> encryption_list = new List <EncryptionType>();

                if (encryption_header.Length > 0)
                {
                    int            begin = 0;
                    int            end   = encryption_header.IndexOf(kDelim2);
                    EncryptionType type;

                    while (end != -1)
                    {
                        type = (EncryptionType)Convert.ToInt32(encryption_header.Substring(begin, end - begin));
                        encryption_list.Add(type);
                        begin = end + 1;
                        end   = encryption_header.IndexOf(kDelim2, begin);
                    }

                    type = (EncryptionType)Convert.ToInt32(encryption_header.Substring(begin));
                    encryption_list.Add(type);
                }

                // Create encryptors
                foreach (EncryptionType type in encryption_list)
                {
                    if (!createEncryptor(type))
                    {
                        return(false);
                    }
                }
            }
            else
            {
                // Encryption handshake message
                EncryptionType type = (EncryptionType)Convert.ToInt32(encryption_type);
                if (!encryptors_.ContainsKey(type))
                {
                    LogWarning("Encryptor.doHandshaking - Unavailable type: {0}", type);
                    return(false);
                }

                Encryptor encryptor = encryptors_[type];
                if (encryptor.state != Encryptor.State.kHandshaking)
                {
                    LogWarning("Encryptor.doHandshaking - Encryptor state is not handshaking. " +
                               "state: {0}", encryptor.state);
                    return(false);
                }

                string out_header = "";
                if (!encryptor.Handshake(encryption_header, ref out_header))
                {
                    LogWarning("Encryptor.doHandshaking - Failure in '{0}' Handshake.",
                               encryptor.name);
                    return(false);
                }

                FunDebug.Assert(encryptor.state == Encryptor.State.kEstablished);
            }

            bool handshake_complete = true;

            foreach (KeyValuePair <EncryptionType, Encryptor> pair in encryptors_)
            {
                if (pair.Value.state != Encryptor.State.kEstablished)
                {
                    handshake_complete = false;
                    break;
                }
            }

            return(handshake_complete);
        }
Example #41
0
        private void ShowEncryptionTypeof(EncryptionType unhidedElementsRelatedToType)
        {
            foreach (EncryptionType type in Enum.GetValues(typeof(EncryptionType)))
            {
                switch (type)
                {
                case EncryptionType.Cesar:
                    cesarSettersGroupBox.Visible = false;
                    break;

                case EncryptionType.TextBased:
                    textBasedEncryptionSettersGroupBox.Visible = false;
                    break;

                case EncryptionType.Substitution:
                    substitutionEncryptionSettersGroupBox.Visible = false;
                    break;

                case EncryptionType.Polybe:
                    polybeEncryptionSettersGroupBox.Visible = false;
                    polybeDefaultTableCheckbox.Checked      = false;
                    break;

                case EncryptionType.ToBinary:
                    toBinaryEncryptionSettersGroupBox.Visible = false;
                    break;

                default:
                    break;
                }
            }
            switch (unhidedElementsRelatedToType)
            {
            case EncryptionType.Cesar:
                flowLayoutPanel1.Controls.Add(cesarSettersGroupBox);
                cesarSettersGroupBox.Visible = true;
                break;

            case EncryptionType.TextBased:
                flowLayoutPanel1.Controls.Add(textBasedEncryptionSettersGroupBox);
                textBasedEncryptionSettersGroupBox.Visible = true;
                break;

            case EncryptionType.Substitution:
                flowLayoutPanel1.Controls.Add(substitutionEncryptionSettersGroupBox);
                SetColumns(polybeTable, (int)columnsCountPolybeEncryption.Value);
                substitutionEncryptionSettersGroupBox.Visible = true;
                break;

            case EncryptionType.Polybe:
                flowLayoutPanel1.Controls.Add(polybeEncryptionSettersGroupBox);
                SetColumns(polybeTable, Convert.ToInt32(columnsCountPolybeEncryption.Value));
                polybeEncryptionSettersGroupBox.Visible = true;
                break;

            case EncryptionType.ToBinary:
                flowLayoutPanel1.Controls.Add(toBinaryEncryptionSettersGroupBox);
                toBinaryEncryptionSettersGroupBox.Visible = true;
                break;

            default:
                break;
            }
        }
Example #42
0
 protected Encryptor(EncryptionType type, string name, State initial_state)
 {
     type_  = type;
     name_  = name;
     state_ = initial_state;
 }
Example #43
0
        /// <summary>
        /// Initializes a new instance of AeadAes256CbcHmac256Algorithm algorithm with a given key and encryption type
        /// </summary>
        /// <param name="encryptionKey">
        /// Root encryption key from which three other keys will be derived
        /// </param>
        /// <param name="encryptionType">Encryption Type, accepted values are Deterministic and Randomized.
        /// For Deterministic encryption, a synthetic IV will be genenrated during encryption
        /// For Randomized encryption, a random IV will be generated during encryption.
        /// </param>
        /// <param name="algorithmVersion">
        /// Algorithm version
        /// </param>
        internal AeadAes256CbcHmac256Algorithm(AeadAes256CbcHmac256EncryptionKey encryptionKey, EncryptionType encryptionType, byte algorithmVersion)
        {
            this.dataEncryptionKey = encryptionKey;
            this.algorithmVersion  = algorithmVersion;

            version[0] = algorithmVersion;

            Debug.Assert(encryptionKey != null, "Null encryption key detected in AeadAes256CbcHmac256 algorithm");
            Debug.Assert(algorithmVersion == 0x01, "Unknown algorithm version passed to AeadAes256CbcHmac256");

            // Validate encryption type for this algorithm
            // This algorithm can only provide randomized or deterministic encryption types.
            // Right now, we support only randomized encryption for Cosmos DB client side encryption.
            Debug.Assert(encryptionType == EncryptionType.Randomized, "Invalid Encryption Type detected in AeadAes256CbcHmac256Algorithm");
            this.isDeterministic = false;

            this.cryptoProviderPool = new ConcurrentQueue <AesCryptoServiceProvider>();
        }
Example #44
0
        public bool Encrypt(string src, string des, string pass, int et, int padMode, int ciMode)
        {
            SymmetricAlgorithm EncryptionType;

            if (et == 0)
            {
                EncryptionType = new RijndaelManaged();
            }
            else
            {
                EncryptionType = new TripleDESCryptoServiceProvider();
            }

            //set padding mode
            EncryptionType.Padding = padMode == 0 ? PaddingMode.PKCS7 : PaddingMode.ISO10126;
            //set mode of operation
            EncryptionType.Mode = ciMode == 0 ? CipherMode.CBC : CipherMode.CFB;
            //generate random Initial Vector
            EncryptionType.GenerateIV();

            Tool t   = new Tool();
            var  key = Encoding.ASCII.GetBytes(t.Expand(pass, EncryptionType.KeySize / 8));

            EncryptionType.Key = key;

            ICryptoTransform transform = EncryptionType.CreateEncryptor();

            //prepare header
            byte[] LenKey          = new byte[4];
            byte[] LenIV           = new byte[4];
            byte[] mPadMode        = new byte[4];
            byte[] mEncryptionType = new byte[4];
            byte[] mModeOperation  = new byte[4];

            LenKey          = BitConverter.GetBytes(EncryptionType.KeySize);
            LenIV           = BitConverter.GetBytes(EncryptionType.IV.Length);
            mPadMode        = BitConverter.GetBytes(padMode);
            mEncryptionType = BitConverter.GetBytes(et);
            mModeOperation  = BitConverter.GetBytes(ciMode);


            //write encrypted data to file
            using (FileStream outFs = new FileStream(des, FileMode.Create))
            {
                outFs.Write(mEncryptionType, 0, 4);
                outFs.Write(mModeOperation, 0, 4);
                outFs.Write(mPadMode, 0, 4);
                outFs.Write(LenKey, 0, 4);
                outFs.Write(LenIV, 0, 4);
                outFs.Write(EncryptionType.IV, 0, EncryptionType.IV.Length);

                using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                {
                    int    blockSizeBytes = EncryptionType.BlockSize / 8;
                    byte[] data           = new byte[blockSizeBytes];
                    int    bytesRead      = 0;
                    int    count          = 0;
                    int    offset         = 0;
                    using (FileStream inFs = new FileStream(src, FileMode.Open))
                    {
                        do
                        {
                            count   = inFs.Read(data, 0, blockSizeBytes);
                            offset += count;
                            outStreamEncrypted.Write(data, 0, count);
                            bytesRead += blockSizeBytes;
                        }while (count > 0);
                        inFs.Close();
                    }
                    outStreamEncrypted.FlushFinalBlock();
                    outStreamEncrypted.Close();
                }
                outFs.Close();
            }


            return(true);
        }
        public static EncryptionKey MakeKey(EncryptionType type, string password, string salt)
        {
            EncryptionKey key = new EncryptionKey(new KerbInt32((long)type), new Asn1OctetString(KeyGenerator.MakeKey(type, password, salt)));

            return(key);
        }
Example #46
0
 /// <summary>Initializes a new instance of <see cref="EncryptionAlgorithm"/>.</summary>
 /// <param name="id"></param>
 /// <param name="name"></param>
 /// <param name="requiredKeySizeInBytes"></param>
 /// <param name="signatureAlgorithm"></param>
 /// <param name="requiredKeyWrappedSizeInBytes"></param>
 /// <param name="category"></param>
 public EncryptionAlgorithm(AlgorithmId id, string name, ushort requiredKeySizeInBytes, SignatureAlgorithm signatureAlgorithm, ushort requiredKeyWrappedSizeInBytes, EncryptionType category)
 {
     _id       = id;
     _utf8Name = JsonEncodedText.Encode(name);
     _requiredKeySizeInBytes = requiredKeySizeInBytes;
     _signatureAlgorithm     = signatureAlgorithm;
     _keyWrappedSizeInBytes  = requiredKeyWrappedSizeInBytes;
     _category  = category;
     _encryptor = CreateAuthenticatedEncryptor(this);
     _decryptor = CreateAuthenticatedDecryptor(this);
 }
 // The same as its overload that getToBeSignedDateCallback = null
 public static byte[] Decrypt(EncryptionType type, byte[] sessionKey, byte[] cipherData, int usage)
 {
     return(Decrypt(type, sessionKey, cipherData, usage, null));
 }
Example #48
0
        public MailAccountData CreateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool imap,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            string errorText = null;
            var    mbox      = new MailBox
            {
                Name         = name,
                EMail        = new MailAddress(email),
                Account      = account,
                Password     = password,
                Port         = port,
                Server       = server,
                SmtpAccount  = smtp_account,
                SmtpPassword = smtp_password,
                SmtpPort     = smtp_port,
                SmtpServer   = smtp_server,
                SmtpAuth     = smtp_auth,
                Imap         = imap,
                Restrict     = restrict,
                TenantId     = TenantId,
                UserId       = Username,
                BeginDate    = restrict ?
                               DateTime.Now.Subtract(new TimeSpan(MailBox.DefaultMailLimitedTimeDelta)) :
                               new DateTime(MailBox.DefaultMailBeginTimestamp),
                IncomingEncryptionType  = incoming_encryption_type,
                OutcomingEncryptionType = outcoming_encryption_type,
                AuthenticationTypeIn    = auth_type_in,
                AuthenticationTypeSmtp  = auth_type_smtp
            };

            try
            {
                MailServerHelper.Test(mbox);
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            if (!string.IsNullOrEmpty(errorText))
            {
                throw new Exception(errorText);
            }

            try
            {
                mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                        new MailServerSettings
                {
                    AccountName        = mbox.Account,
                    AccountPass        = mbox.Password,
                    AuthenticationType =
                        mbox.AuthenticationTypeIn,
                    EncryptionType =
                        mbox.IncomingEncryptionType,
                    Port = mbox.Port,
                    Url  = mbox.Server
                },
                                                                        imap ? "imap" : "pop3",
                                                                        AuthorizationServiceType.Unknown);
                mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                          new MailServerSettings
                {
                    AccountName        = mbox.SmtpAccount,
                    AccountPass        = mbox.SmtpPassword,
                    AuthenticationType =
                        mbox.AuthenticationTypeSmtp,
                    EncryptionType =
                        mbox.OutcomingEncryptionType,
                    Port = mbox.SmtpPort,
                    Url  = mbox.SmtpServer
                },
                                                                          "smtp", AuthorizationServiceType.Unknown);

                MailBoxManager.SaveMailBox(mbox);
                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                                  false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (Exception ex)
            {
                //TODO: change AttachmentsUnknownError to common unknown error text
                errorText = GetFormattedTextError(ex, MailApiResource.AttachmentsUnknownError);
            }

            throw new Exception(errorText);
        }
Example #49
0
        public void Loop()
        {
            bool           clientOpen     = true;
            Queue <string> messagesToSend = new Queue <string>();

            var thread = new Thread(() => { while (clientOpen)
                                            {
                                                string input = Console.ReadLine();
                                                messagesToSend.Enqueue(input);
                                            }
                                    });

            thread.IsBackground = true;
            thread.Start();

            while (clientOpen)
            {
                while (client.GetNextMessage(out Telepathy.Message msg))
                {
                    switch (msg.eventType)
                    {
                    case Telepathy.EventType.Connected:
                        Log("Connected to server! Waiting for password status...", "Connected");
                        break;

                    case Telepathy.EventType.Data:

                        string msgContents = (futureMessagesEncrypted) ?
                                             PresharedAESEncryption.AESDecrypt(Convert.FromBase64String(Encoding.UTF8.GetString(msg.data)), aesKey) :
                                             Encoding.UTF8.GetString(msg.data);
                        switch (state)
                        {
                        case ClientState.WaitingForPasswordStatus:
                            if (msgContents == "passwordProtected")
                            {
                                passwordProtected = true;
                            }
                            state = ClientState.WaitingForEncryptionMethod;
                            break;

                        case ClientState.WaitingForEncryptionMethod:
                            if (msgContents == "PRESHARED-AES")
                            {
                                encryption = EncryptionType.PRESHARED_AES;
                                Log("This server has encryption, and a password. Please enter the password...", "Encryption / Password");
                                SendMessage("Yes");
                                state = ClientState.PasswordEnabled;
                            }
                            else if (msgContents == "N/A")
                            {
                                encryption = EncryptionType.N_A;
                                Log("This server has no encryption, and no password. Continuing...", "Encryption");
                                SendMessage("Yes");
                                SendMessage("");
                                state = ClientState.Nickname;
                            }
                            else
                            {
                                Log($"This server wants to use {msgContents} encryption, but this client doesn't support it. Notifying...", "Encryption");
                                SendMessage("Not compatible");
                                state = ClientState.Established;
                            }
                            break;

                        case ClientState.PasswordEnabled:
                            if (msgContents == "V")
                            {
                                Log("Your password was valid! Continuing...", "Valid Password");
                                state = (encryption == EncryptionType.PRESHARED_AES) ? ClientState.FinalizeAESEncryption : ClientState.Nickname;
                                futureMessagesEncrypted = (encryption == EncryptionType.PRESHARED_AES);
                            }
                            else
                            {
                                Log(msgContents, "Invalid Password");
                            }
                            break;

                        case ClientState.FinalizeAESEncryption:
                            aesKey = msgContents;
                            state  = ClientState.Nickname;
                            break;

                        case ClientState.Nickname:
                            if (msgContents == "V")
                            {
                                state = ClientState.Established;
                            }
                            else
                            {
                                Log(msgContents, "Nickname");
                            }
                            break;

                        case ClientState.Established:
                            Log(msgContents, "Message");
                            break;

                        default:
                            break;
                        }
                        break;

                    case Telepathy.EventType.Disconnected:
                        Log("Disconnected from server", "Disconnected");

                        client.Disconnect();

                        Log("Please restart the client in order to connect to a server.", "Connection Closed");
                        break;

                    default:
                        break;
                    }
                }

                while (messagesToSend.Count > 0)
                {
                    SendMessage(messagesToSend.Dequeue());
                }

                Thread.Sleep(100);
            }
        }
Example #50
0
        public MailAccountData UpdateAccount(string name,
                                             string email,
                                             string account,
                                             string password,
                                             int port,
                                             string server,
                                             string smtp_account,
                                             string smtp_password,
                                             int smtp_port,
                                             string smtp_server,
                                             bool smtp_auth,
                                             bool restrict,
                                             EncryptionType incoming_encryption_type,
                                             EncryptionType outcoming_encryption_type,
                                             SaslMechanism auth_type_in,
                                             SaslMechanism auth_type_smtp)
        {
            if (string.IsNullOrEmpty(email))
            {
                throw new ArgumentException();
            }

            var mbox = MailBoxManager.GetMailBox(TenantId, Username, new MailAddress(email));

            if (null == mbox)
            {
                throw new ArgumentException("Mailbox with specified email doesn't exist.");
            }

            if (mbox.IsTeamlab)
            {
                throw new ArgumentException("Mailbox with specified email can't be updated");
            }

            if (string.IsNullOrEmpty(password))
            {
                password = mbox.Password;
            }
            if (string.IsNullOrEmpty(smtp_password))
            {
                smtp_password = mbox.SmtpPassword;
            }

            string errorText;

            mbox.Account      = account;
            mbox.Name         = name;
            mbox.Password     = password;
            mbox.SmtpAccount  = smtp_account;
            mbox.SmtpPassword = smtp_password;
            mbox.Port         = port;
            mbox.Server       = server;
            mbox.SmtpPort     = smtp_port;
            mbox.SmtpServer   = smtp_server;
            mbox.SmtpAuth     = smtp_auth;
            mbox.Restrict     = restrict;
            mbox.BeginDate    = mbox.Restrict ?
                                DateTime.Now.Subtract(new TimeSpan(mbox.MailLimitedTimeDelta)) :
                                mbox.MailBeginTimestamp;
            mbox.IncomingEncryptionType  = incoming_encryption_type;
            mbox.OutcomingEncryptionType = outcoming_encryption_type;
            mbox.AuthenticationTypeIn    = auth_type_in;
            mbox.AuthenticationTypeSmtp  = auth_type_smtp;

            mbox.InServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                    new MailServerSettings
            {
                AccountName        = mbox.Account,
                AccountPass        = mbox.Password,
                AuthenticationType = mbox.AuthenticationTypeIn,
                EncryptionType     = mbox.IncomingEncryptionType,
                Port = mbox.Port,
                Url  = mbox.Server
            },
                                                                    mbox.Imap ? "imap" : "pop3", AuthorizationServiceType.Unknown);
            mbox.SmtpServerId = MailBoxManager.SaveMailServerSettings(mbox.EMail,
                                                                      new MailServerSettings
            {
                AccountName        = mbox.SmtpAccount,
                AccountPass        = mbox.SmtpPassword,
                AuthenticationType = mbox.AuthenticationTypeSmtp,
                EncryptionType     = mbox.OutcomingEncryptionType,
                Port = mbox.SmtpPort,
                Url  = mbox.SmtpServer
            },
                                                                      "smtp", AuthorizationServiceType.Unknown);

            try
            {
                if (!string.IsNullOrEmpty(mbox.RefreshToken) || MailServerHelper.Test(mbox))
                {
                    if (!MailBoxManager.SaveMailBox(mbox))
                    {
                        throw new Exception("Failed to_addresses update account");
                    }
                }

                var accountInfo = new AccountInfo(mbox.MailBoxId, mbox.EMailView, mbox.Name, mbox.Enabled, mbox.QuotaError,
                                                  MailBox.AuthProblemType.NoProblems, new SignatureDto(mbox.MailBoxId, TenantId, "", false),
                                                  false, mbox.EMailInFolder, false, false);

                return(accountInfo.ToAddressData().FirstOrDefault());
            }
            catch (ImapConnectionException exImap)
            {
                errorText = GetFormattedTextError(exImap, ServerType.Imap, exImap is ImapConnectionTimeoutException);
            }
            catch (Pop3ConnectionException exPop3)
            {
                errorText = GetFormattedTextError(exPop3, ServerType.Pop3, exPop3 is Pop3ConnectionTimeoutException);
            }
            catch (SmtpConnectionException exSmtp)
            {
                errorText = GetFormattedTextError(exSmtp, ServerType.Smtp, exSmtp is SmtpConnectionTimeoutException);
            }
            catch (Exception ex)
            {
                errorText = GetFormattedTextError(ex);
            }

            throw new Exception(errorText);
        }
Example #51
0
 public InputAccountBuilder WithEncryptionType(EncryptionType value)
 {
     encryptionType = value; return(this);
 }
Example #52
0
 /// <summary>
 /// Allows adding a new server with the added option of specifying the encryption type if any and whether the server needs any authentication.
 /// </summary>
 /// <param name="host">Hostname/IP Address for server.</param>
 /// <param name="port">Port to be used to connect to server.</param>
 /// <param name="username">Username for authentication.</param>
 /// <param name="password">Password for authentication.</param>
 /// <param name="RequiresAuthentication">true if authentication is needed, false otherwise.</param>
 /// <param name="EncType">Encryption type see EncryptionType enumeration.</param>
 public Server(string host, int port, string username, string password, bool RequiresAuthentication, EncryptionType EncType)
 {
     Host     = host;
     Port     = port;
     Username = username;
     Password = password;
     _requiresAuthentication = RequiresAuthentication;
     _encType = EncType;
 }
 private void DecryptTicket(EncryptionType type, byte[] sessionKey)
 {
     var ticketEncPartRawData = KerberosUtility.Decrypt(
         type,
         sessionKey,
         Response.ticket.enc_part.cipher.ByteArrayValue,
         (int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
     TicketEncPart = new EncTicketPart();
     TicketEncPart.BerDecode(new Asn1DecodingBuffer(ticketEncPartRawData));
     KerberosUtility.OnDumpMessage("KRB5:TicketEncPart",
         "Encrypted Ticket in TGS-REP",
         KerberosUtility.DumpLevel.PartialMessage,
         ticketEncPartRawData);
 }
Example #54
0
 public IntrospectiveValidator(byte[] key, EncryptionType etype)
     : base(new KerberosKey(key: key, etype: etype), ticketCache: null)
 {
 }
 public FunapiMessage(TransportProtocol protocol, string msg_type, object message,
                       EncryptionType enc = EncryptionType.kDefaultEncryption)
 {
     this.protocol = protocol;
     this.enc_type = enc;
     this.msg_type = msg_type;
     this.message = message;
 }
Example #56
0
        public MailBoxData(int tenant, string user, int mailboxId, string name,
                           MailAddress email, string account, string password, string server,
                           EncryptionType encryption, SaslMechanism authentication, bool imap,
                           string smtpAccount, string smtpPassword, string smtpServer,
                           EncryptionType smtpEncryption, SaslMechanism smtpAuthentication,
                           byte oAuthType, string oAuthToken)
        {
            if (string.IsNullOrEmpty(user))
            {
                throw new ArgumentNullException("user");
            }
            if (email == null)
            {
                throw new ArgumentNullException("email");
            }
            if (string.IsNullOrEmpty(account))
            {
                throw new ArgumentNullException("account");
            }
            if (string.IsNullOrEmpty(server))
            {
                throw new ArgumentNullException("server");
            }
            if (!server.Contains(":"))
            {
                throw new FormatException("Invalid server string format is <server:port>");
            }
            if (!smtpServer.Contains(":"))
            {
                throw new FormatException("Invalid smtp server string format is <server:port>");
            }

            TenantId  = tenant;
            UserId    = user;
            MailBoxId = mailboxId;

            Name  = name;
            EMail = email;

            Account        = account;
            Password       = password;
            Server         = server.Split(':')[0];
            Port           = int.Parse(server.Split(':')[1]);
            Encryption     = encryption;
            Authentication = authentication;
            Imap           = imap;

            SmtpAccount        = smtpAccount;
            SmtpPassword       = smtpPassword;
            SmtpServer         = smtpServer.Split(':')[0];
            SmtpPort           = int.Parse(smtpServer.Split(':')[1]);
            SmtpEncryption     = smtpEncryption;
            SmtpAuthentication = smtpAuthentication;

            OAuthType  = oAuthType;
            OAuthToken = oAuthToken;

            MailLimitedTimeDelta = DefaultMailLimitedTimeDelta;
            MailBeginTimestamp   = new DateTime(DefaultMailBeginTimestamp);

            ServerLoginDelay = DefaultServerLoginDelay;
            BeginDate        = MailBeginTimestamp;

            ImapIntervals = new Dictionary <string, ImapFolderUids>();
        }
        public void SendMessage(string msg_type, object message,
                                 EncryptionType encryption = EncryptionType.kDefaultEncryption,
                                 TransportProtocol protocol = TransportProtocol.kDefault,
                                 string expected_reply_type = null, float expected_reply_time = 0f,
                                 TimeoutEventHandler onReplyMissed = null)
        {
            if (protocol == TransportProtocol.kDefault)
                protocol = GetMessageProtocol(msg_type);

            bool transport_reliability = (protocol == TransportProtocol.kTcp && session_reliability_);

            // Invalidates session id if it is too stale.
            if (last_received_.AddSeconds(kFunapiSessionTimeout) < DateTime.Now)
            {
                DebugUtils.Log("Session is too stale. The server might have invalidated my session. Resetting.");
                session_id_ = "";
            }

            FunapiTransport transport = GetTransport(protocol);
            if (transport != null && transport.state == FunapiTransport.State.kEstablished &&
                (transport_reliability == false || unsent_queue_.Count <= 0))
            {
                FunapiMessage fun_msg = null;

                if (transport.Encoding == FunEncoding.kJson)
                {
                    fun_msg = new FunapiMessage(protocol, msg_type, transport.JsonHelper.Clone(message), encryption);

                    // Encodes a messsage type
                    transport.JsonHelper.SetStringField(fun_msg.message, kMsgTypeBodyField, msg_type);

                    // Encodes a session id, if any.
                    if (session_id_.Length > 0)
                    {
                        transport.JsonHelper.SetStringField(fun_msg.message, kSessionIdBodyField, session_id_);
                    }

                    if (transport_reliability)
                    {
                        transport.JsonHelper.SetIntegerField(fun_msg.message, kSeqNumberField, seq_);
                        ++seq_;

                        send_queue_.Enqueue(fun_msg);
                        DebugUtils.DebugLog("{0} send message - msgtype:{1} seq:{2}", protocol, msg_type, seq_ - 1);
                    }
                    else
                    {
                        DebugUtils.DebugLog("{0} send message - msgtype:{1}", protocol, msg_type);
                    }
                }
                else if (transport.Encoding == FunEncoding.kProtobuf)
                {
                    fun_msg = new FunapiMessage(protocol, msg_type, message, encryption);

                    FunMessage pbuf = fun_msg.message as FunMessage;
                    pbuf.msgtype = msg_type;

                    // Encodes a session id, if any.
                    if (session_id_.Length > 0)
                    {
                        pbuf.sid = session_id_;
                    }

                    if (transport_reliability)
                    {
                        pbuf.seq = seq_;
                        ++seq_;

                        send_queue_.Enqueue(fun_msg);
                        DebugUtils.DebugLog("{0} send message - msgtype:{1} seq:{2}", protocol, msg_type, pbuf.seq);
                    }
                    else
                    {
                        DebugUtils.DebugLog("{0} send message - msgtype:{1}", protocol, msg_type);
                    }
                }

                if (expected_reply_type != null && expected_reply_type.Length > 0)
                {
                    AddExpectedReply(fun_msg, expected_reply_type, expected_reply_time, onReplyMissed);
                }

                transport.SendMessage(fun_msg);
            }
            else if (transport != null &&
                     (transport_reliability || transport.state == FunapiTransport.State.kEstablished))
            {
                if (transport.Encoding == FunEncoding.kJson)
                {
                    if (transport == null)
                        unsent_queue_.Enqueue(new FunapiMessage(protocol, msg_type, message, encryption));
                    else
                        unsent_queue_.Enqueue(new FunapiMessage(protocol, msg_type, transport.JsonHelper.Clone(message), encryption));
                }
                else if (transport.Encoding == FunEncoding.kProtobuf)
                {
                    unsent_queue_.Enqueue(new FunapiMessage(protocol, msg_type, message, encryption));
                }

                DebugUtils.Log("SendMessage - '{0}' message queued.", msg_type);
            }
            else
            {
                StringBuilder strlog = new StringBuilder();
                strlog.AppendFormat("SendMessage - '{0}' message skipped.", msg_type);
                if (transport == null)
                    strlog.AppendFormat(" There's no '{0}' transport.", protocol);
                else if (transport.state != FunapiTransport.State.kEstablished)
                    strlog.AppendFormat(" Transport's state is '{0}'.", transport.state);

                DebugUtils.Log(strlog.ToString());
            }
        }
Example #58
0
        protected override void OnKH()
        {
            switch (step)
            {
            case 1:
                encType = resultEncType;
                if (!ReferenceEquals(code, null))
                {
                    Numeric ka = program.GetValue(code.operand1);
                    key    = new NumericArray(ka);
                    length = Config.NumericBits;
                    if (key[0].GetEncType() == EncryptionType.None)
                    {
                        encType = EncryptionType.None;
                        if (key[0].GetEncType() == EncryptionType.None)
                        {
                            encType = EncryptionType.None;
                            if (key[0].GetUnsignedBigInteger() == 0)
                            {
                                keyH = new NumericArray(new Numeric(1, 0));
                            }
                            else
                            {
                                keyH = new NumericArray(new Numeric(0, 0));
                            }
                            // jump to round 3
                            step = 2;
                            Run();
                            break;
                        }
                    }
                }
                parallelism = key.Length;
                //Console.WriteLine("KH: " + key[0]);
                new HammingDistanceOnKH(party, line, this, key, keyH, length).Run();
                break;

            case 2:
                new FastEqualZeroOnKH(party, line, this, keyH, keyH, (int)Math.Ceiling(Math.Log(length + 1, 2))).Run();
                break;

            case 3:
                SetResult(encType, keyH.GetArray());
                break;

            case 4:
                InvokeCaller();
                break;

            default:
                throw new Exception();
                ////System.Diagnostics.Debug.Assert(le >= 2 || le == 0);
                //if (le > 2)
                //{
                //    le = (int)Math.Ceiling(Math.Log(le + 1, 2));
                //    new HammingDistanceOnKH(party, line, this, keyH, keyH, le).Run();
                //}
                //else if (le == 2)
                //{
                //    var OROperand = new Numeric[2 * parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        OROperand[2 * p] = keyH[p] >> 1;
                //        OROperand[2 * p + 1] = keyH[p].ModPow(1);
                //    }
                //    le = 0;
                //    new OROnKH(party, line, this, new NumericArray(OROperand), keyH).Run();
                //}
                //else
                //{
                //    Numeric[] kf = new Numeric[parallelism];
                //    for (int p = 0; p < parallelism; ++p)
                //    {
                //        kf[p] = keyH[p].ModPow(1);
                //        //kf[p].SetEncType(EncryptionType.XOR);
                //    }
                //    SetResult(kf);
                //}
                //break;
            }
        }
        /// <summary>
        /// Get encryption key by the encryption type
        /// </summary>
        /// <param name="encryptionType">The specified encryption type</param>
        /// <returns>Encryption key</returns>
        private byte[] GetEncryptionKeyByType(EncryptionType encryptionType)
        {
            byte[] key;

            if (encryptionType == EncryptionType.AES256_CTS_HMAC_SHA1_96)
            {
                key = ArrayUtility.ConcatenateArrays(Guid.NewGuid().ToByteArray(), Guid.NewGuid().ToByteArray());
            }
            else if (encryptionType == EncryptionType.DES_CBC_CRC || encryptionType == EncryptionType.DES_CBC_MD5)
            {
                key = ArrayUtility.SubArray(Guid.NewGuid().ToByteArray(), ConstValue.BYTE_SIZE);
            }
            else
            {
                key = Guid.NewGuid().ToByteArray();
            }

            return key;
        }
Example #60
0
 protected bool hasEncryption(EncryptionType type)
 {
     return(encryptors_.ContainsKey(type));
 }