Exemplo n.º 1
0
        /// <summary>
        /// Create a new instance of the <see cref="EncryptionManager"/> class
        /// </summary>
        /// <param name="encryptionCertificate">
        /// The certificate that contains the secrets used for encryption. Note that
        /// the private key must be present in this certificate in order for decryption
        /// to be performed.
        /// </param>
        /// <param name="mode">The mode (encryption/decryption) of the encryption manager</param>
        /// <param name="outputStream">The stream where the transformed content will be written</param>
        /// <param name="sourceFileSize"></param>
        public EncryptionManager(
            X509Certificate2 encryptionCertificate,
            EncryptionMode mode,
            Stream outputStream,
            long sourceFileSize)
        {
            Pre.ThrowIfArgumentNull(encryptionCertificate, nameof(encryptionCertificate));
            Pre.ThrowIfArgumentNull(outputStream, nameof(outputStream));

            Pre.ThrowIfTrue(mode == EncryptionMode.None, "Encryption mode cannot be None");

            this.encryptionCertificate = encryptionCertificate;
            this.Mode           = mode;
            this.sourceFileSize = sourceFileSize;
            this.outputStream   = outputStream;

            this.sha1 = new SHA1Cng();
            this.md5  = new MD5Cng();

            // Any valid encrypted file will have a minimum size (to include the header and minimal
            // encrypted content). Ensure that the source file is at least this size.
            if (mode == EncryptionMode.Decrypt)
            {
                Pre.Assert(sourceFileSize >= MinimumEncryptedFileSize, "sourceFileSize >= minimumEncryptedFileSize");
            }

            this.Initialize();
        }
Exemplo n.º 2
0
        public virtual List <T> DeserializeList(byte[] value, EncryptionMode mode)
        {
            List <T> retval = default(List <T>);

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                retval = DeserializeListClear(value);
                break;

            case EncryptionMode.Encryption:
                retval = DeserializeList(value, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (MXDevice.Encryption.Required)
                {
                    retval = DeserializeList(value, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                }
                else
                {
                    retval = DeserializeListClear(value);
                }
                break;
            }

            return(retval);
        }
Exemplo n.º 3
0
        public virtual byte[] SerializeObjectToBytes(T obj, EncryptionMode mode)
        {
            byte[] bytes = null;

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                bytes = SerializeObjectToBytesClear(obj);
                break;

            case EncryptionMode.Encryption:
                bytes = SerializeObjectToBytes(obj, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (MXDevice.Encryption.Required)
                {
                    bytes = SerializeObjectToBytes(obj, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                }
                else
                {
                    bytes = SerializeObjectToBytesClear(obj);
                }
                break;
            }

            return(bytes);
        }
Exemplo n.º 4
0
        public virtual string SerializeObject(T obj, EncryptionMode mode)
        {
            string retval = null;

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                retval = SerializeObjectClear(obj);
                break;

            case EncryptionMode.Encryption:
                retval = SerializeObject(obj, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (MXDevice.Encryption.Required)
                {
                    retval = SerializeObject(obj, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                }
                else
                {
                    retval = SerializeObjectClear(obj);
                }
                break;
            }

            return(retval);
        }
Exemplo n.º 5
0
        public virtual T DeserializeObject(string value, EncryptionMode mode)
        {
            T retval = default(T);

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                retval = DeserializeObjectClear(value);
                break;

            case EncryptionMode.Encryption:
                retval = DeserializeObject(value, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (MXDevice.Encryption.Required)
                {
                    retval = DeserializeObject(value, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                }
                else
                {
                    retval = DeserializeObjectClear(value);
                }
                break;
            }

            return(retval);
        }
Exemplo n.º 6
0
        public void SerializeObjectToFile(T obj, string filename, EncryptionMode mode)
        {
            DateTime dtMetric = DateTime.UtcNow;

            MXDevice.File.Save(filename, JsonConvert.SerializeObject(obj, Formatting.None), mode);
            MXDevice.Log.Metric(string.Format("SerializerJson.SerializeObjectToFile(2): File {0}  Time: {1} milliseconds", filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds));
        }
Exemplo n.º 7
0
        public virtual string SerializeList(List <T> list, EncryptionMode mode)
        {
            string retval = null;

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                retval = SerializeListClear(list);
                break;

            case EncryptionMode.Encryption:
                retval = SerializeList(list, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (MXDevice.Encryption.Required)
                {
                    retval = SerializeList(list, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                }
                else
                {
                    retval = SerializeListClear(list);
                }
                break;
            }

            return(retval);
        }
Exemplo n.º 8
0
        public ProtocolBase(Protocol protocol, FtpCommad cmd)
        {
            string server   = ConfigurationManager.AppSettings["FtpServer"];
            int    port     = int.Parse(ConfigurationManager.AppSettings["FtpPort"]);
            string user     = ConfigurationManager.AppSettings["FtpUser"];
            string password = ConfigurationManager.AppSettings["FtpPassword"];
            string path     = ConfigurationManager.AppSettings["FtpPart"];

            switch (protocol)
            {
            case Protocol.Ftp:
                _ftp = new ProtocolFTP(server, port, user, password, path);
                break;

            case Protocol.Ftps:
                EncryptionMode encryptionMode = (EncryptionMode)Enum.Parse(typeof(EncryptionMode), ConfigurationManager.AppSettings["FtpEncryption"], true);
                _ftp = new ProtocolFTPS(server, port, user, password, path, encryptionMode);
                break;

            case Protocol.Sftp:
                string privateKeyPath = ConfigurationManager.AppSettings["FtpPrivateKeyPath"];
                string passphrase     = ConfigurationManager.AppSettings["FtpPassphrase"];
                _ftp = new ProtocolSFTP(server, port, user, password, path, privateKeyPath, passphrase);
                break;
            }

            _cmd          = cmd;
            _retryCount   = int.Parse(ConfigurationManager.AppSettings["FtpRetry"]);
            _retryTimeout = int.Parse(ConfigurationManager.AppSettings["FtpTimeout"]);
        }
            private void Initialize(string passphrase, Encoding _encoding, PaddingMode _paddingMode = PaddingMode.PKCS7, CipherMode _cipherMode = CipherMode.CBC, int _keySize = 256, int _blockSize = 128, EncryptionMode _encryptionMode = EncryptionMode.FileStream)
            {
                if (passphrase.Length < 16)
                    throw new Exception("The minimum Length for passphrase is 16, but it is recommended to be more than 32 characters");

                encoding = _encoding;
                paddingMode = _paddingMode;
                cipherMode = _cipherMode;
                keySize = _keySize;
                blockSize = _blockSize;
                encryptionMode = _encryptionMode;

                //byte[] passwordKey = encodeDigest(passphrase);
                var salt = passphrase.Substring(0, 16);
                var iv = passphrase.Length >= 32 ? passphrase.Substring(16, 16) : salt;
                byte[] key = encoding.GetBytes(salt); //encodeDigest(salt);
                //File.WriteAllLines(@"X:\Amin\EncryptDecrypt\Ali Test\New Way\key Byte Array.txt", key.Select(x => x.ToString()).ToArray());
                byte[] IV = encoding.GetBytes(iv);  //encodeDigest(iv);
                //File.WriteAllLines(@"X:\Amin\EncryptDecrypt\Ali Test\New Way\IV Byte Array.txt", IV.Select(x => x.ToString()).ToArray());

                //var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
                //AES.Key = key.GetBytes(AES.KeySize / 8);
                //AES.IV = key.GetBytes(AES.BlockSize / 8);

                RijndaelManaged rijndael = new RijndaelManaged();//AesManaged//RijndaelManaged
                rijndael.Padding = paddingMode;
                rijndael.Mode = cipherMode;
                if (keySize > 0)
                    rijndael.KeySize = keySize;
                if (blockSize > 0)
                    rijndael.BlockSize = blockSize;
                encryptor = rijndael.CreateEncryptor(key, IV);
                decryptor = rijndael.CreateDecryptor(key, IV);
            }
Exemplo n.º 10
0
        /// <summary>
        /// 对指定的字节数组,根据加密模式进行加密
        /// </summary>
        /// <param name="byteSource"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static byte[] EncryptBytes(byte[] byteSource, EncryptionMode mode)
        {
            byte[] byteResult;
            int    type = (int)mode / 1000;

            switch (type)
            {
            case 2:
                var sha256 = new SHA256Managed();
                byteResult = sha256.ComputeHash(byteSource);
                break;

            case 3:
                var sha512 = new SHA512Managed();
                byteResult = sha512.ComputeHash(byteSource);
                break;

            default:
                throw new ArgumentException(string.Format("EncryptionMode invalid"), "mode");
            }
            int version = ((int)mode / 10) % 100;

            if (version > 0)
            {
                int aesMode = 1 * 1000 + version * 10 + ((int)mode % 10);
                byteResult = ClientAESEncryption.EncryptBytes(byteResult, (EncryptionMode)aesMode);
            }
            return(byteResult);
        }
Exemplo n.º 11
0
        /// <summary>This version of DecryptData takes the encrypted message, password
        /// and IV as strings and decrypts the message, returning the plain text as a string.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param>
        public static string DecryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool messageAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // Dont do any work is the message is empty
            if (message.Length <= 0)
            {
                return("");
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            // Was message supplied in Hex or as simple string
            if (messageAsHex)
            {
                messageData = HexToBytes(message);
            }
            else
            {
                messageData = encoderUnicode.GetBytes(message);
            }

            // Convert key and IV to byte arrays
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return the decrypted plain test as a string
            return(encoderUnicode.GetString(DecryptData(messageData, passwordData,
                                                        vectorData, blockSize, keySize, cryptMode)));
        }
Exemplo n.º 12
0
        /// <summary>This version of EncryptData takes the message, password
        /// and IV as strings and encrypts the message, returning the encrypted text as a string.
        /// </summary>
        /// <param name="message">The plain text message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param>
        public static string EncryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool returnAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // If message is empty dont bother doing any work
            if (message.Length <= 0)
            {
                return("");
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            // Convert message, key and IV to byte arrays
            messageData  = encoderUnicode.GetBytes(message);
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return encrypted message as string (hex version of bytes if required)
            if (returnAsHex)
            {
                return(BytesToHex(EncryptData(messageData, passwordData,
                                              vectorData, blockSize, keySize, cryptMode)));
            }
            else
            {
                return(encoderUnicode.GetString(EncryptData(messageData, passwordData,
                                                            vectorData, blockSize, keySize, cryptMode)));
            }
        }
Exemplo n.º 13
0
        public virtual byte[] Read(string filename, EncryptionMode mode)
        {
            DateTime dtMetric = DateTime.UtcNow;

            if (!Exists(filename))
                return null;

            byte[] bytes = null;

            switch (mode)
            {
                case EncryptionMode.NoEncryption:
                    bytes = ReadClear(filename);
                    break;
                case EncryptionMode.Encryption:
                    bytes = Read(filename, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                    break;
                case EncryptionMode.Default:
                    if (MXDevice.Encryption.Required)
                        bytes = Read(filename, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                    else
                        bytes = ReadClear(filename);
                    break;
            }

            MXDevice.Log.Metric(string.Format("BaseFile.Read: Mode: {0} File: {1} Time: {2} milliseconds", mode, filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds));

            return bytes;
        }
Exemplo n.º 14
0
 public CityServerListener(EncryptionMode EncMode)
     : base(EncMode)
 {
     m_ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
     CityServers = new BlockingCollection<CityInfo>();
     PotentialLogins = new BlockingCollection<NetworkClient>();
 }
Exemplo n.º 15
0
        public void GetNonce(ReadOnlySpan <byte> source, Span <byte> target, EncryptionMode encryptionMode)
        {
            if (target.Length != Interop.SodiumNonceSize)
            {
                throw new ArgumentException($"Invalid nonce buffer size. Target buffer for the nonce needs to have a capacity of {Interop.SodiumNonceSize} bytes.", nameof(target));
            }

            switch (encryptionMode)
            {
            case EncryptionMode.XSalsa20_Poly1305:
                source.Slice(0, 12).CopyTo(target);
                return;

            case EncryptionMode.XSalsa20_Poly1305_Suffix:
                source.Slice(source.Length - Interop.SodiumNonceSize).CopyTo(target);
                return;

            case EncryptionMode.XSalsa20_Poly1305_Lite:
                source.Slice(source.Length - 4).CopyTo(target);
                return;

            default:
                throw new ArgumentException("Unsupported encryption mode.", nameof(encryptionMode));
            }
        }
        /// <summary>
        /// Initializes the encryptor for encryption
        /// </summary>
        /// <param name="document"></param>
        /// <param name="mode"></param>
        public RC4Encryptor(PdfDocument document, EncryptionMode mode)
        {
            Mode = mode;

            Initialize(document, document.SecurityHandler);

            if (mode == EncryptionMode.Encrypt)
            {
                var version  = document.SecuritySettings.DocumentSecurityLevel == PdfDocumentSecurityLevel.Encrypted128Bit ? 2 : 1;
                var revision = document.SecuritySettings.DocumentSecurityLevel == PdfDocumentSecurityLevel.Encrypted128Bit ? 3 : 2;
                var length   = document.SecuritySettings.DocumentSecurityLevel == PdfDocumentSecurityLevel.Encrypted128Bit ? 128 : 40;

                vValue    = version;
                keyLength = keySize = length / 8;
                rValue    = revision;

                PrepareEncryptionKeys(document.SecuritySettings.SecurityHandler._ownerPassword,
                                      document.SecuritySettings.SecurityHandler._userPassword,
                                      (int)document.SecuritySettings.SecurityHandler.Permission, false);

                document.SecurityHandler.Elements.Clear();
                document.SecurityHandler.Elements.SetInteger(PdfSecurityHandler.Keys.V, version);
                document.SecurityHandler.Elements.SetInteger(PdfSecurityHandler.Keys.Length, keyLength * 8);
                document.SecurityHandler.Elements.SetInteger(PdfStandardSecurityHandler.Keys.R, revision);
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.O, PdfEncoders.RawEncoding.GetString(ownerValue));
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.U, PdfEncoders.RawEncoding.GetString(userValue));
                document.SecurityHandler.Elements.SetName(PdfSecurityHandler.Keys.Filter, "/Standard");
            }
        }
Exemplo n.º 17
0
        public override byte[] Read(string filename, EncryptionMode mode)
        {
            byte[] bytes = null;

            switch (mode)
            {
            case EncryptionMode.NoEncryption:
                bytes = ReadClear(filename);
                break;

            case EncryptionMode.Encryption:
                bytes = Read(filename, Device.Encryption.Key, Device.Encryption.Salt);
                break;

            case EncryptionMode.Default:
                if (Device.Encryption.Required)
                {
                    bytes = Read(filename, Device.Encryption.Key, Device.Encryption.Salt);
                }
                else
                {
                    bytes = ReadClear(filename);
                }
                break;
            }
            return(bytes);
        }
Exemplo n.º 18
0
        /// <summary>
        /// 对指定的字节数组,根据加密模式进行加密
        /// </summary>
        /// <param name="byteSource"></param>
        /// <param name="mode"></param>
        /// <returns></returns>
        public static byte[] EncryptBytes(byte[] byteSource, EncryptionMode mode)
        {
            byte[] byteKey;
            byte[] byteIV;
            switch (mode)
            {
            case EncryptionMode.None:
            case EncryptionMode.AES256V00Hex:
            case EncryptionMode.AES256V00B64:
                byteKey = new byte[0];
                byteIV  = new byte[0];
                break;

            case EncryptionMode.AES256V01Hex:
            case EncryptionMode.AES256V01B64:
                byteKey = Encoding.ASCII.GetBytes(ClientKeys.VCT_KEY256_LOW1);
                byteIV  = Encoding.ASCII.GetBytes(ClientIVs.VCT_ENCRYPTION_AES_IVEC_LOW);
                break;

            case EncryptionMode.AES256V04Hex:
            case EncryptionMode.AES256V04B64:
                byteKey = Encoding.ASCII.GetBytes(ClientKeys.VCT_KEY256_NORMAL1);
                byteIV  = Encoding.ASCII.GetBytes(ClientIVs.VCT_ENCRYPTION_AES_IVEC_LOW);
                break;

            default:
                throw new ArgumentException(string.Format("EncryptionMode invalid"), "mode");
            }
            return(EncryptBytes(byteSource, byteKey, byteIV));
        }
Exemplo n.º 19
0
        /// <summary>
        /// 对指定字符串,根据加密模式和编码方式进行解密
        /// </summary>
        /// <param name="strSource"></param>
        /// <param name="mode"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string DecryptString(string strSource, EncryptionMode mode, Encoding encoding)
        {
            int mod = (int)mode % 10;

            byte[] byteSource;
            switch (mod)
            {
            case 1:
                byteSource = ClientEncryptionUtils.Hex2Byte(strSource);
                break;

            case 2:
                byteSource = Convert.FromBase64String(strSource);
                break;

            default:
                throw new ArgumentException(string.Format("EncryptionMode invalid"), "mode");
            }

            byte[] byteResult = DecryptBytes(byteSource, mode);
            string strTemp    = encoding.GetString(byteResult);

            strTemp = strTemp.TrimEnd('\0');
            return(strTemp);
        }
        /// <summary>
        /// Initializes the encryptor for encryption
        /// </summary>
        /// <param name="document"></param>
        /// <param name="mode"></param>
        public AESEncryptor(PdfDocument document, EncryptionMode mode)
        {
            Mode = mode;

            Initialize(document, document.SecurityHandler);

            if (mode == EncryptionMode.Encrypt)
            {
                PrepareEncryptionKeys(document.SecuritySettings.SecurityHandler._ownerPassword,
                                      document.SecuritySettings.SecurityHandler._userPassword,
                                      (int)document.SecuritySettings.SecurityHandler.Permission, false);

                document.SecurityHandler.Elements.Clear();
                document.SecurityHandler.Elements.SetName(PdfSecurityHandler.Keys.Filter, "/Standard");
                document.SecurityHandler.Elements.SetInteger(PdfSecurityHandler.Keys.V, 5);
                document.SecurityHandler.Elements.SetInteger(PdfSecurityHandler.Keys.Length, 256);
                document.SecurityHandler.Elements.SetInteger(PdfStandardSecurityHandler.Keys.R, 6);
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.O, PdfEncoders.RawEncoding.GetString(ownerValue));
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.U, PdfEncoders.RawEncoding.GetString(userValue));
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.UE, PdfEncoders.RawEncoding.GetString(ueValue));
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.OE, PdfEncoders.RawEncoding.GetString(oeValue));
                document.SecurityHandler.Elements.SetString(PdfStandardSecurityHandler.Keys.Perms, PdfEncoders.RawEncoding.GetString(permsValue));

                var cfDict     = new PdfDictionary(doc);
                var filterDict = new PdfDictionary(doc);
                filterDict.Elements.SetName(PdfSecurityHandler.Keys.CFM, "/AESV3");
                filterDict.Elements.SetInteger(PdfSecurityHandler.Keys.Length, 256);
                filterDict.Elements.SetName("/AuthEvent", "DocOpen");
                cfDict.Elements["/StdCF"] = filterDict;
                document.SecurityHandler.Elements[PdfSecurityHandler.Keys.CF] = cfDict;
                document.SecurityHandler.Elements.SetName(PdfSecurityHandler.Keys.StrF, "/StdCF");
                document.SecurityHandler.Elements.SetName(PdfSecurityHandler.Keys.StmF, "/StdCF");
            }
        }
Exemplo n.º 21
0
        public static String Decrypt(String textToDecrypt, EncryptionMode enc, object[] keys)
        {
            switch (enc)
            {
            case EncryptionMode.GREEK:
                return(Decrypt(new OldGreek(), textToDecrypt, keys));

            case EncryptionMode.CAESAR:
                return(Decrypt(new Caesar(), textToDecrypt, keys));

            case EncryptionMode.PLAYFAIR:
                return(Decrypt(new Playfair(), textToDecrypt, keys));

            case EncryptionMode.ADFGVX:
                return(Decrypt(new ADFGVX(), textToDecrypt, keys));

            case EncryptionMode.HOMOPHONIC:
                return(Decrypt(new Homophonic(), textToDecrypt, keys));

            case EncryptionMode.ENIGMA:
                return(Decrypt(new Enigma(), textToDecrypt, keys));

            case EncryptionMode.DES:
                return(Decrypt(new DES(), textToDecrypt, keys));

            case EncryptionMode.RSA:
                return(Decrypt(new RSA(), textToDecrypt, keys));
            }
            return(textToDecrypt);
        }
Exemplo n.º 22
0
        public void LoadSettings()
        {
            var settingsVersion = ((int?)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "SettingsVersion", 0)).GetValueOrDefault(0);
            userId = new SecureString().AppendChars(System.Security.Principal.WindowsIdentity.GetCurrent().User.Value);

            switch (settingsVersion)
            {
                case 1:
                    AccountWindowTop = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountWindowTop", AccountWindowTop));
                    AccountWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountWindowLeft", AccountWindowLeft));
                    PatternWindowTop = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "PatternWindowTop", PatternWindowTop));
                    PatternWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "PatternWindowLeft", PatternWindowLeft));
                    StartupPrompt = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "StartupPrompt", 1)) == 1;
                    EncryptionVersion = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "EncryptionVersion", 1));
                    EncryptionMode = (EncryptionMode)((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "EncryptionMode", EncryptionMode.Basic));
                    encryptedData = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountData", null);
                    break;

                case 0:
                    var patternEnabled = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternEnabled", 0)) == 1;
                    PatternWindowTop = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternWindowTop", PatternWindowTop));
                    PatternWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternWindowLeft", PatternWindowLeft));
                    StartupPrompt = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "StartupPrompt", 1)) == 1;
                    EncryptionMode = patternEnabled ? EncryptionMode.Pattern : EncryptionMode.Basic;
                    encryptedData = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "encAccounts", null);
                    Migrate(0);
                    break;
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Serializes the object to file.
        /// </summary>
        /// <param name="obj">The object to serialize.</param>
        /// <param name="filename">The filename of the serialized object.</param>
        /// <param name="mode">The encryption mode for the serialization.</param>
        public void SerializeObjectToFile(T obj, string filename, EncryptionMode mode)
        {
            DateTime dtMetric = DateTime.UtcNow;

            Device.File.Save(filename, ToJson(obj), mode);
            Device.Log.Metric(string.Format("SerializerOdata.SerializeObjectToFile(2): File {0}  Time: {1} milliseconds", filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds));
        }
Exemplo n.º 24
0
        public void LoadSettings()
        {
            var settingsVersion = ((int?)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "SettingsVersion", 0)).GetValueOrDefault(0);

            userId = new SecureString().AppendChars(System.Security.Principal.WindowsIdentity.GetCurrent().User.Value);

            switch (settingsVersion)
            {
            case 1:
                AccountWindowTop  = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountWindowTop", AccountWindowTop));
                AccountWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountWindowLeft", AccountWindowLeft));
                PatternWindowTop  = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "PatternWindowTop", PatternWindowTop));
                PatternWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "PatternWindowLeft", PatternWindowLeft));
                StartupPrompt     = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "StartupPrompt", 1)) == 1;
                EncryptionVersion = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "EncryptionVersion", 1));
                EncryptionMode    = (EncryptionMode)((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "EncryptionMode", EncryptionMode.Basic));
                encryptedData     = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Authentiqr.NET", "AccountData", null);
                break;

            case 0:
                var patternEnabled = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternEnabled", 0)) == 1;
                PatternWindowTop  = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternWindowTop", PatternWindowTop));
                PatternWindowLeft = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "PatternWindowLeft", PatternWindowLeft));
                StartupPrompt     = ((int)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "StartupPrompt", 1)) == 1;
                EncryptionMode    = patternEnabled ? EncryptionMode.Pattern : EncryptionMode.Basic;
                encryptedData     = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\LCGoogleApps", "encAccounts", null);
                Migrate(0);
                break;
            }
        }
Exemplo n.º 25
0
        public Ftp(XElement xe, Workflow wf) : base(xe, wf)
        {
            string   server   = this.GetSetting("server");
            int      port     = int.Parse(this.GetSetting("port"));
            string   user     = this.GetSetting("user");
            string   password = this.GetSetting("password");
            string   path     = this.GetSetting("path");
            Protocol protocol = (Protocol)Enum.Parse(typeof(Protocol), this.GetSetting("protocol"), true);

            switch (protocol)
            {
            case Protocol.FTP:
                _plugin = new PluginFTP(this, server, port, user, password, path);
                break;

            case Protocol.FTPS:
                EncryptionMode encryptionMode = (EncryptionMode)Enum.Parse(typeof(EncryptionMode), this.GetSetting("encryption"), true);
                _plugin = new PluginFTPS(this, server, port, user, password, path, encryptionMode);
                break;

            case Protocol.SFTP:
                string privateKeyPath = this.GetSetting("privateKeyPath", string.Empty);
                string passphrase     = this.GetSetting("passphrase", string.Empty);
                _plugin = new PluginSFTP(this, server, port, user, password, path, privateKeyPath, passphrase);
                break;
            }
            this._cmd          = (FtpCommad)Enum.Parse(typeof(FtpCommad), this.GetSetting("command"), true);
            this._retryCount   = int.Parse(this.GetSetting("retryCount", "3"));
            this._retryTimeout = int.Parse(this.GetSetting("retryTimeout", "1500"));
        }
 public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode)
 {
     this.m_blockSize      = blockSize;
     this.m_encryptionMode = encryptionMode;
     this.m_paddingMode    = paddingMode;
     this.m_provider       = provider.Duplicate();
     this.m_key            = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
 }
 public CapiSymmetricAlgorithm(int blockSize, int feedbackSize, SafeCspHandle provider, SafeCapiKeyHandle key, byte[] iv, CipherMode cipherMode, PaddingMode paddingMode, EncryptionMode encryptionMode)
 {
     this.m_blockSize = blockSize;
     this.m_encryptionMode = encryptionMode;
     this.m_paddingMode = paddingMode;
     this.m_provider = provider.Duplicate();
     this.m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
 }
Exemplo n.º 28
0
 public int CalculatePacketSize(int encryptedLength, EncryptionMode encryptionMode)
 {
     return(encryptionMode switch
     {
         EncryptionMode.XSalsa20_Poly1305 => HeaderSize + encryptedLength,
         EncryptionMode.XSalsa20_Poly1305_Suffix => HeaderSize + encryptedLength + Interop.SodiumNonceSize,
         EncryptionMode.XSalsa20_Poly1305_Lite => HeaderSize + encryptedLength + 4,
         _ => throw new ArgumentException("Unsupported encryption mode.", nameof(encryptionMode)),
     });
Exemplo n.º 29
0
        public async ValueTask <byte[]?> E(string?value, EncryptionMode encryptionMode, string?secondaryPassword)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }
            var value2 = Encoding.UTF8.GetBytes(value);

            return(await EB(value2, encryptionMode, secondaryPassword));
        }
Exemplo n.º 30
0
        byte[]? Concat(byte[]?value, EncryptionMode encryptionMode)
        {
            if (value == null || !value.Any())
            {
                return(null);
            }
            var r = BitConverter.GetBytes((int)encryptionMode).Concat(value).ToArray();

            return(r);
        }
 /// <summary>
 /// Create a new instance with a default buffer length of 128KB.
 /// </summary>
 /// <param name="stream">When encrypting, the stream to write the ciphertext to. When decrypting, the stream to read the ciphertext from.</param>
 /// <param name="key">The encryption key.</param>
 /// <param name="encryptionMode">Whether the stream will be used for encryption or decryption.</param>
 /// <param name="leaveOpen">Whether to leave the <paramref name="stream"/> open.</param>
 public XChaChaBufferedStream(
     Stream stream,
     XChaChaKey key,
     EncryptionMode encryptionMode,
     bool leaveOpen = false)
     : base(stream, key, encryptionMode, leaveOpen)
 {
     this.plaintextBuffer  = new RentedArray(DefaultPlaintextBufferLength);
     this.ciphertextBuffer = new RentedArray(CalculateCiphertextLength(DefaultPlaintextBufferLength));
 }
Exemplo n.º 32
0
        public WinFileEncryption(IEnumerable <string> fileList, EncryptionMode mode)
        {
            InitializeComponent();

            var vm = new MainViewModel(DialogCoordinator.Instance);

            vm.FileList = fileList;
            vm.Mode     = mode;

            DataContext = vm;
        }
        /// <summary>
        /// Initializes a client that listens for data.
        /// </summary>
        /// <param name="ClientSocket">The client's socket.</param>
        /// <param name="Server">The Listener instance calling this constructor.</param>
        /// <param name="ReceivePulse">Should this client receive a pulse at a regular interval?</param>
        public NetworkClient(Socket ClientSocket, Listener Server, EncryptionMode EMode)
        {
            m_Sock = ClientSocket;
            m_Listener = Server;
            m_RecvBuf = new byte[11024];

            m_EMode = EMode;

            m_Sock.BeginReceive(m_RecvBuf, 0, m_RecvBuf.Length, SocketFlags.None,
                new AsyncCallback(ReceiveCallback), m_Sock);
        }
Exemplo n.º 34
0
        /// <summary>
        /// Initializes a client that listens for data.
        /// </summary>
        /// <param name="ClientSocket">The client's socket.</param>
        /// <param name="Server">The Listener instance calling this constructor.</param>
        /// <param name="ReceivePulse">Should this client receive a pulse at a regular interval?</param>
        public NetworkClient(Socket ClientSocket, Listener Server, EncryptionMode EMode)
        {
            m_Sock     = ClientSocket;
            m_Listener = Server;
            m_RecvBuf  = new byte[11024];

            m_EMode = EMode;

            m_Sock.BeginReceive(m_RecvBuf, 0, m_RecvBuf.Length, SocketFlags.None,
                                new AsyncCallback(ReceiveCallback), m_Sock);
        }
Exemplo n.º 35
0
 /// <summary>
 /// 创建一个会话实例
 /// </summary>
 /// <param name="tcpClient">The TcpClient</param>
 public MediaSession(TcpClient tcpClient)
 {
     mMsgEncoding    = MessageEncoding.None;
     mEncryptionMode = EncryptionMode.None;
     mReceiveBuffer  = new byte[mMaxBufferSize];
     mBufferedData   = new byte[mMaxBufferSize];
     mBufferedSize   = 0;
     mLastActiveTime = DateTime.Now;
     mSessionID      = Guid.NewGuid().ToString();
     mTcpClient      = tcpClient;
     mRemoteEndpoint = tcpClient.Client.RemoteEndPoint.ToString();
     mIsSSL          = true;
 }
        public NetworkClient(string IP, int Port, EncryptionMode EMode, bool KeepAlive)
        {
            m_Sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            if(KeepAlive)
                m_Sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

            m_IP = IP;
            m_Port = Port;

            m_EMode = EMode;

            m_RecvBuf = new byte[11024];
        }
Exemplo n.º 37
0
        /// <summary>
        /// Initializes a new instance of Listener.
        /// </summary>
        public Listener(EncryptionMode Mode)
        {
            m_ListenerSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            m_LoginClients = new SynchronizedCollection<NetworkClient>();

            m_EMode = Mode;
            /*switch (Mode)
            {
                case EncryptionMode.AESCrypto:
                    m_AesCryptoService = new AesCryptoServiceProvider();
                    m_AesCryptoService.GenerateIV();
                    m_AesCryptoService.GenerateKey();
                    break;
            }*/
        }
Exemplo n.º 38
0
 public CapiSymmetricAlgorithm(int blockSize,
                               int feedbackSize,
                               SafeCspHandle provider,
                               SafeCapiKeyHandle key,
                               byte[] iv,
                               CipherMode cipherMode,
                               PaddingMode paddingMode,
                               EncryptionMode encryptionMode) {
     Contract.Requires(0 < blockSize && blockSize % 8 == 0);
     Contract.Requires(0 <= feedbackSize);
     Contract.Requires(provider != null && !provider.IsInvalid && !provider.IsClosed);
     Contract.Requires(key != null && !key.IsInvalid && !key.IsClosed);
     Contract.Ensures(m_provider != null && !m_provider.IsInvalid && !m_provider.IsClosed);
     
     m_blockSize = blockSize;
     m_encryptionMode = encryptionMode;
     m_paddingMode = paddingMode;
     m_provider = provider.Duplicate();
     m_key = SetupKey(key, ProcessIV(iv, blockSize, cipherMode), cipherMode, feedbackSize);
 }
Exemplo n.º 39
0
 public void SetPattern(SecureString pattern)
 {
     this.EncryptionMode = EncryptionMode.Pattern;
     this.pattern = pattern;
 }
Exemplo n.º 40
0
        /// <summary>This version of EncryptData takes the message, password 
        /// and IV as strings and encrypts the message, returning the encrypted text as a string.
        /// </summary>
        /// <param name="message">The plain text message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param>
        public static string EncryptData(string message, string password,
            string initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode, bool returnAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // If message is empty dont bother doing any work
            if (message.Length <= 0)
                return "";

            //System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); //MTreat

            // Convert message, key and IV to byte arrays
            //messageData = encoderUnicode.GetBytes(message); //MTreat
            //passwordData = encoderUnicode.GetBytes(password); //MTreat
            //vectorData = encoderUnicode.GetBytes(initialisationVector); //MTreat

            System.Text.ASCIIEncoding encoderASCII = new System.Text.ASCIIEncoding(); //MTreat

            // Convert message, key and IV to byte arrays
            messageData = encoderASCII.GetBytes(message); //MTreat
            passwordData = encoderASCII.GetBytes(password); //MTreat
            vectorData = encoderASCII.GetBytes(initialisationVector); //MTreat

            // Return encrypted message as string (hex version of bytes if required)
            if (returnAsHex)
                return BytesToHex(EncryptData(messageData, passwordData,
                    vectorData, blockSize, keySize, cryptMode));
            else
                //return encoderUnicode.GetString(EncryptData(messageData, passwordData, //MTreat
                //    vectorData, blockSize, keySize, cryptMode)); //MTreat
                return encoderASCII.GetString(EncryptData(messageData, passwordData, //MTreat
                    vectorData, blockSize, keySize, cryptMode)); //MTreat
        }
 public byte[] Read( string fileName, EncryptionMode mode )
 {
     return null;
 }
 public string ReadString( string fileName, EncryptionMode mode )
 {
     return null;
 }
Exemplo n.º 43
0
    /// <summary>
    /// Sends this app's appId and appVersion to identify this application server side.
    /// This is an async request which triggers a OnOperationResponse() call.
    /// </summary>
    /// <remarks>
    /// This operation makes use of encryption, if that is established before.
    /// See: EstablishEncryption(). Check encryption with IsEncryptionAvailable.
    /// This operation is allowed only once per connection (multiple calls will have ErrorCode != Ok).
    /// </remarks>
    /// <param name="appId">Your application's name or ID to authenticate. This is assigned by Photon Cloud (webpage).</param>
    /// <param name="appVersion">The client's version (clients with differing client appVersions are separated and players don't meet).</param>
    /// <param name="authValues">Optional authentication values. The client can set no values or a UserId or some parameters for Custom Authentication by a server.</param>
    /// <param name="regionCode">Optional region code, if the client should connect to a specific Photon Cloud Region.</param>
    /// <param name="encryptionMode"></param>
    /// <param name="expectedProtocol"></param>
    /// <returns>If the operation could be sent (has to be connected).</returns>
    public virtual bool OpAuthenticateOnce(string appId, string appVersion, AuthenticationValues authValues, string regionCode, EncryptionMode encryptionMode, ConnectionProtocol expectedProtocol)
    {
        if (this.DebugOut >= DebugLevel.INFO)
            {
                this.Listener.DebugReturn(DebugLevel.INFO, "OpAuthenticate()");
            }

            var opParameters = new Dictionary<byte, object>();

            // shortcut, if we have a Token
            if (authValues != null && authValues.Token != null)
            {
                opParameters[ParameterCode.Secret] = authValues.Token;
                return this.OpCustom(OperationCode.AuthenticateOnce, opParameters, true, (byte)0, false);   // we don't have to encrypt, when we have a token (which is encrypted)
            }

            if (encryptionMode == EncryptionMode.DatagramEncryption && expectedProtocol != ConnectionProtocol.Udp)
            {
                Debug.LogWarning("Expected protocol set to UDP, due to encryption mode DatagramEncryption. Changing protocol in PhotonServerSettings from: " + PhotonNetwork.PhotonServerSettings.Protocol);
                PhotonNetwork.PhotonServerSettings.Protocol = ConnectionProtocol.Udp;
                expectedProtocol = ConnectionProtocol.Udp;
            }

            opParameters[ParameterCode.ExpectedProtocol] = (byte)expectedProtocol;
            opParameters[ParameterCode.EncryptionMode] = (byte)encryptionMode;

            opParameters[ParameterCode.AppVersion] = appVersion;
            opParameters[ParameterCode.ApplicationId] = appId;

            if (!string.IsNullOrEmpty(regionCode))
            {
                opParameters[ParameterCode.Region] = regionCode;
            }

            if (authValues != null)
            {
                if (!string.IsNullOrEmpty(authValues.UserId))
                {
                    opParameters[ParameterCode.UserId] = authValues.UserId;
                }

                if (authValues.AuthType != CustomAuthenticationType.None)
                {
                    opParameters[ParameterCode.ClientAuthenticationType] = (byte)authValues.AuthType;
                    if (!string.IsNullOrEmpty(authValues.Token))
                    {
                        opParameters[ParameterCode.Secret] = authValues.Token;
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(authValues.AuthGetParameters))
                        {
                            opParameters[ParameterCode.ClientAuthenticationParams] = authValues.AuthGetParameters;
                        }
                        if (authValues.AuthPostData != null)
                        {
                            opParameters[ParameterCode.ClientAuthenticationData] = authValues.AuthPostData;
                        }
                    }
                }
            }

            return this.OpCustom(OperationCode.AuthenticateOnce, opParameters, true, (byte)0, this.IsEncryptionAvailable);
    }
Exemplo n.º 44
0
        /// <summary>This version of DecryptData takes the encrypted message, password 
        /// and IV as byte arrays and decrypts the message, returning the plain text as 
        /// a byte array.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        public static byte[] DecryptData(byte[] message, byte[] password,
            byte[] initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode)
        {
            byte[] messageData, keyBlock, vectorBlock, dataBlock;
            int messageLength, encodedLength, nb, nk;

            // Dont do any work if message is empty
            encodedLength = message.Length;
            if (encodedLength <= 0)
                return message;

            // Set up arrays based on block size
            switch (blockSize)
            {
                case BlockSize.Block128:
                    nb = 4;
                    break;
                case BlockSize.Block192:
                    nb = 6;
                    break;
                default:	// assume 256
                    nb = 8;
                    break;
            }

            vectorBlock = new byte[nb * 4];
            dataBlock = new byte[nb * 4];

            for (int i = 0; i < (nb * 4); i++)
            {
                vectorBlock[i] = 0;
                dataBlock[i] = 0;
            }

            // Set up array based on key size
            switch (keySize)
            {
                case KeySize.Key128:
                    nk = 4;
                    break;
                case KeySize.Key192:
                    nk = 6;
                    break;
                default:	// assume 256
                    nk = 8;
                    break;
            }

            keyBlock = new byte[nk * 4];

            for (int i = 0; i < (nk * 4); i++)
            {
                keyBlock[i] = 0;
            }

            // Key will be zero padded, or trimmed to correct size
            for (int i = 0; (i < password.Length) && (i < (nk * 4)); i++)
                keyBlock[i] = password[i];

            // Vector will be zero padded, or trimmed to correct size
            for (int i = 0; (i < initialisationVector.Length) && (i < (nb * 4)); i++)
                vectorBlock[i] = initialisationVector[i];

            // Prepare the key and tables using the Rijndael fuinctions
            gentables();
            gkey(nb, nk, keyBlock);

            // Decrypt a block at a time
            for (int i = 0; i < encodedLength; i += (nb * 4))
            {
                Array.Copy(message, i, dataBlock, 0, (nb * 4));

                decrypt(dataBlock);

                // If CBC mode we need to do some extra XORing
                if (cryptMode == EncryptionMode.ModeCBC)
                {
                    for (int j = 0; j < (nb * 4); j++)
                        dataBlock[j] ^= vectorBlock[j];

                    Array.Copy(message, i, vectorBlock, 0, (nb * 4));
                }

                Array.Copy(dataBlock, 0, message, i, (nb * 4));
            }

            // Message length was originally put on front of message, so retrieve it
            messageLength = (int)message[0] | (((int)message[1]) << 8) |
                (((int)message[2]) << 16) | (((int)message[3]) << 24);

            // Get the original message from the clear text
            messageData = new byte[messageLength];
            Array.Copy(message, 4, messageData, 0, messageLength);

            return messageData;
        }
Exemplo n.º 45
0
        /// <summary>This version of DecryptData takes the encrypted message, password 
        /// and IV as strings and decrypts the message, returning the plain text as a string.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param>
        public static string DecryptData(string message, string password,
            string initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode, bool messageAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // Dont do any work is the message is empty
            if (message.Length <= 0)
                return "";

            //System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); //MTreat
            System.Text.ASCIIEncoding encoderASCII = new System.Text.ASCIIEncoding();  //MTreat

            // Was message supplied in Hex or as simple string
            if (messageAsHex)
                messageData = HexToBytes(message);
            else
                //messageData = encoderUnicode.GetBytes(message); //MTreat
                messageData = encoderASCII.GetBytes(message); //MTreat

            // Convert key and IV to byte arrays
            //passwordData = encoderUnicode.GetBytes(password); //MTreat
            //vectorData = encoderUnicode.GetBytes(initialisationVector); //MTreat
            passwordData = encoderASCII.GetBytes(password); //MTreat
            vectorData = encoderASCII.GetBytes(initialisationVector); //MTreat

            // Return the decrypted plain test as a string
            //return encoderUnicode.GetString(DecryptData(messageData, passwordData, //MTreat
            //  vectorData, blockSize, keySize, cryptMode)); //MTreat
            return encoderASCII.GetString(DecryptData(messageData, passwordData, //MTreat
                vectorData, blockSize, keySize, cryptMode)); //MTreat
        }
Exemplo n.º 46
0
 public virtual void Save(string filename, byte[] contents, EncryptionMode mode)
 {
     switch (mode)
     {
         case EncryptionMode.NoEncryption:
             SaveClear(filename, contents);
             break;
         case EncryptionMode.Encryption:
             Save(filename, contents, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
             break;
         case EncryptionMode.Default:
             if (MXDevice.Encryption.Required)
                 Save(filename, contents, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
             else
                 SaveClear(filename, contents);
             break;
     }
 }
 public void Save( string fileName, Stream contents, EncryptionMode mode )
 {
 }
Exemplo n.º 48
0
        public virtual string ReadString(string filename, EncryptionMode mode)
        {
            DateTime dtMetric = DateTime.UtcNow;

            if (!Exists(filename))
                return null;

            string text = null;

            switch (mode)
            {
                case EncryptionMode.NoEncryption:
                    text = ReadStringClear(filename);
                    break;
                case EncryptionMode.Encryption:
                    text = ReadString(filename, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                    break;
                case EncryptionMode.Default:
                    if (MXDevice.Encryption.Required)
                        text = ReadString(filename, MXDevice.Encryption.Key, MXDevice.Encryption.Salt);
                    else
                        text = ReadStringClear(filename);
                    break;
            }
            MXDevice.Log.Metric(string.Format("BasicFile.ReadString: Mode: {0}  File: {1} Time: {2} milliseconds", mode, filename, DateTime.UtcNow.Subtract(dtMetric).TotalMilliseconds));

            return text;
        }
Exemplo n.º 49
0
 public void SetPassword(SecureString password)
 {
     this.EncryptionMode = EncryptionMode.Password;
     this.password = password;
 }
 public void Save( string fileName, byte[] contents, EncryptionMode mode )
 {
 }
Exemplo n.º 51
0
        // -------------------------------------------------------------------------------------
        // The code below are utility functions for calling the Rijndael code above
        // -------------------------------------------------------------------------------------
        /// <summary>This version of EncryptData takes the message, password 
        /// and IV as byte arrays and encrypts the message, returning the encrypted text 
        /// as a byte array.
        /// 
        /// NOTE: In this implementation I add four bytes to the start of the message and
        /// use that space to store the length of the message. Then the sister DecryptData
        /// function knows where to trim the message before returning it. Not all
        /// encryption routines will use this method. The only parts specified in the
        /// Rijndael standard are for use of the gentables, gkey, encrypt and decrypt
        /// functions. So if you have some data encrypted with another implementation
        /// of Rijndael, or you are encypting data that will be decrypted with another
        /// implementation, then you will need to know how they are recording the length of
        /// the message (if at all), and if you are encrypting/decrypting strings whether
        /// they based it on Ascii or Unicode (or some other character set).
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        public static byte[] EncryptData(byte[] message, byte[] password,
            byte[] initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode)
        {
            byte[] messageData, keyBlock, vectorBlock, dataBlock;
            int messageLength, encodedLength, nb, nk;

            // Dont do any work if message is empty
            messageLength = message.Length;
            if (messageLength <= 0)
                return message;

            // Set up arrays based on block size
            switch (blockSize)
            {
                case BlockSize.Block128:
                    nb = 4;
                    break;
                case BlockSize.Block192:
                    nb = 6;
                    break;
                default:	// assume 256
                    nb = 8;
                    break;
            }

            vectorBlock = new byte[nb * 4];
            dataBlock = new byte[nb * 4];

            for (int i = 0; i < (nb * 4); i++)
            {
                vectorBlock[i] = 0;
                dataBlock[i] = 0;
            }

            // Set up array based on key size
            switch (keySize)
            {
                case KeySize.Key128:
                    nk = 4;
                    break;
                case KeySize.Key192:
                    nk = 6;
                    break;
                default:	// assume 256
                    nk = 8;
                    break;
            }

            keyBlock = new byte[nk * 4];

            for (int i = 0; i < (nk * 4); i++)
            {
                keyBlock[i] = 0;
            }

            // Key will be zero padded, or trimmed to correct size
            for (int i = 0; (i < password.Length) && (i < (nk * 4)); i++)
                keyBlock[i] = password[i];

            // Vector will be zero padded, or trimmed to correct size
            for (int i = 0; (i < initialisationVector.Length) && (i < (nb * 4)); i++)
                vectorBlock[i] = initialisationVector[i];

            // Prepare the key and tables using the Rijndael fuinctions
            gentables();
            gkey(nb, nk, keyBlock);

            // Add 4 bytes to message to store message length, then make sure the length
            // is a Mod of the block size
            encodedLength = messageLength + 4;

            if ((encodedLength % (nb * 4)) != 0)
                encodedLength += ((nb * 4) - (encodedLength % (nb * 4)));

            messageData = new byte[encodedLength];

            // Put message length on front of message
            messageData[0] = (byte)messageLength;
            messageData[1] = (byte)(messageLength >> 8);
            messageData[2] = (byte)(messageLength >> 16);
            messageData[3] = (byte)(messageLength >> 24);

            Array.Copy(message, 0, messageData, 4, messageLength);

            // Zero pad the end of the array
            for (int i = (messageLength + 4); i < encodedLength; i++)
                messageData[i] = 0;

            // Loop through the message encrypting it a block at a time
            for (int i = 0; i < encodedLength; i += (nb * 4))
            {
                Array.Copy(messageData, i, dataBlock, 0, (nb * 4));

                // Do some XORing if in CBC mode
                if (cryptMode == EncryptionMode.ModeCBC)
                    for (int j = 0; j < (nb * 4); j++)
                        dataBlock[j] ^= vectorBlock[j];

                encrypt(dataBlock);

                if (cryptMode == EncryptionMode.ModeCBC)
                    Array.Copy(dataBlock, 0, vectorBlock, 0, dataBlock.Length);

                Array.Copy(dataBlock, 0, messageData, i, (nb * 4));
            }

            return messageData;
        }