Ejemplo n.º 1
1
        public static void TestShims()
        {
            using (var alg = new AesManaged())
            {
                alg.BlockSize = 128;
                Assert.Equal(128, alg.BlockSize);

                var emptyIV = new byte[alg.BlockSize / 8];
                alg.IV = emptyIV;
                Assert.Equal(emptyIV, alg.IV);
                alg.GenerateIV();
                Assert.NotEqual(emptyIV, alg.IV);

                var emptyKey = new byte[alg.KeySize / 8];
                alg.Key = emptyKey;
                Assert.Equal(emptyKey, alg.Key);
                alg.GenerateKey();
                Assert.NotEqual(emptyKey, alg.Key);

                alg.KeySize = 128;
                Assert.Equal(128, alg.KeySize);

                alg.Mode = CipherMode.ECB;
                Assert.Equal(CipherMode.ECB, alg.Mode);

                alg.Padding = PaddingMode.PKCS7;
                Assert.Equal(PaddingMode.PKCS7, alg.Padding);
            }
        }
Ejemplo n.º 2
0
 public static byte[] EncryptUseAes(this byte[] bytes, byte[] key, byte[] iv,
     CipherMode mode = CipherMode.CBC,
     PaddingMode padding = PaddingMode.PKCS7)
 {
     using (var aes = new AesManaged()
     {
         IV = iv,
         Key = key,
         Mode = mode,
         Padding = padding
     })
     {
         return aes.Encrypt(bytes);
     }
 }
Ejemplo n.º 3
0
        public static void EncryptDecryptKnownECB192()
        {
            byte[] plainTextBytes =
                new ASCIIEncoding().GetBytes("This is a sentence that is longer than a block, it ensures that multi-block functions work.");

            byte[] encryptedBytesExpected = new byte[]
            {
                0xC9, 0x7F, 0xA5, 0x5B, 0xC3, 0x92, 0xDC, 0xA6,
                0xE4, 0x9F, 0x2D, 0x1A, 0xEF, 0x7A, 0x27, 0x03,
                0x04, 0x9C, 0xFB, 0x56, 0x63, 0x38, 0xAE, 0x4F,
                0xDC, 0xF6, 0x36, 0x98, 0x28, 0x05, 0x32, 0xE9,
                0xF2, 0x6E, 0xEC, 0x0C, 0x04, 0x9D, 0x12, 0x17,
                0x18, 0x35, 0xD4, 0x29, 0xFC, 0x01, 0xB1, 0x20,
                0xFA, 0x30, 0xAE, 0x00, 0x53, 0xD4, 0x26, 0x25,
                0xA4, 0xFD, 0xD5, 0xE6, 0xED, 0x79, 0x35, 0x2A,
                0xE2, 0xBB, 0x95, 0x0D, 0xEF, 0x09, 0xBB, 0x6D,
                0xC5, 0xC4, 0xDB, 0x28, 0xC6, 0xF4, 0x31, 0x33,
                0x9A, 0x90, 0x12, 0x36, 0x50, 0xA0, 0xB7, 0xD1,
                0x35, 0xC4, 0xCE, 0x81, 0xE5, 0x2B, 0x85, 0x6B,
            };

            byte[] aes192Key = new byte[]
            {
                0xA6, 0x1E, 0xC7, 0x54, 0x37, 0x4D, 0x8C, 0xA5,
                0xA4, 0xBB, 0x99, 0x50, 0x35, 0x4B, 0x30, 0x4D,
                0x6C, 0xFE, 0x3B, 0x59, 0x65, 0xCB, 0x93, 0xE3,
            };

            using (var alg = new AesManaged())
            {
                // The CipherMode and KeySize are different than the default values; this ensures the type
                // forwards the state properly to Aes.
                alg.Mode = CipherMode.ECB;
                alg.Key = aes192Key;

                byte[] encryptedBytes = alg.Encrypt(plainTextBytes);
                Assert.Equal(encryptedBytesExpected, encryptedBytes);

                byte[] decryptedBytes = alg.Decrypt(encryptedBytes);
                Assert.Equal(plainTextBytes, decryptedBytes);
            }
        }
        /// <summary>
        /// Simple Authentication (HMAC) then Decryption (AES) for a secrets UTF8 Message.
        /// </summary>
        /// <param name="encryptedMessage">The encrypted message.</param>
        /// <param name="cryptKey">The crypt key.</param>
        /// <param name="authKey">The auth key.</param>
        /// <param name="nonSecretPayloadLength">Length of the non secret payload.</param>
        /// <returns>Decrypted Message</returns>
        public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] cryptKey, byte[] authKey, int nonSecretPayloadLength = 0)
        {
            //Basic Usage Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("CryptKey needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("AuthKey needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (encryptedMessage == null || encryptedMessage.Length == 0)
            {
                throw new ArgumentException("Encrypted Message Required!", "encryptedMessage");
            }

            using (var hmac = new HMACSHA256(authKey))
            {
                var sentTag = new byte[hmac.HashSize / 8];
                //Calculate Tag
                var calcTag  = hmac.ComputeHash(encryptedMessage, 0, encryptedMessage.Length - sentTag.Length);
                var ivLength = (BlockBitSize / 8);

                //if message length is to small just return null
                if (encryptedMessage.Length < sentTag.Length + nonSecretPayloadLength + ivLength)
                {
                    return(null);
                }

                //Grab Sent Tag
                Array.Copy(encryptedMessage, encryptedMessage.Length - sentTag.Length, sentTag, 0, sentTag.Length);

                //Compare Tag with constant time comparison
                var compare = 0;
                for (var i = 0; i < sentTag.Length; i++)
                {
                    compare |= sentTag[i] ^ calcTag[i];
                }

                //if message doesn't authenticate return null
                if (compare != 0)
                {
                    return(null);
                }

                using (var aes = new AesManaged
                {
                    KeySize = KeyBitSize,
                    BlockSize = BlockBitSize,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.PKCS7
                })
                {
                    //Grab IV from message
                    var iv = new byte[ivLength];
                    Array.Copy(encryptedMessage, nonSecretPayloadLength, iv, 0, iv.Length);

                    using (var decrypter = aes.CreateDecryptor(cryptKey, iv))
                        using (var plainTextStream = new MemoryStream())
                        {
                            using (var decrypterStream = new CryptoStream(plainTextStream, decrypter, CryptoStreamMode.Write))
                                using (var binaryWriter = new BinaryWriter(decrypterStream))
                                {
                                    //Decrypt Cipher Text from Message
                                    binaryWriter.Write(
                                        encryptedMessage,
                                        nonSecretPayloadLength + iv.Length,
                                        encryptedMessage.Length - nonSecretPayloadLength - iv.Length - sentTag.Length
                                        );
                                }
                            //Return Plain Text
                            return(plainTextStream.ToArray());
                        }
                }
            }
        }
Ejemplo n.º 5
0
        private void ProcessAll()
        {
            Dispatcher.Invoke(LogBox.Clear);

            Log(
                string.Format(
                    "{0}{1}Start{1}{0}ExePath = {2}{0}Resources = {3}",
                    Environment.NewLine,
                    Line,
                    _globalVariables.PathToExe,
                    _globalVariables.PathToResources
                    )
                );

            const int totalSteps = 3;

            _visualProgress.SetBarUsual();
            _visualProgress.ShowBar();

            _taskBarManager.SetProgress(0);
            _taskBarManager.SetUsualState();

            void SetStep(int currentStep, string status)
            {
                int percentage = (currentStep - 1) * 100 / totalSteps;

                _visualProgress.SetBarValue(percentage);
                _visualProgress.SetLabelText(status);
                _taskBarManager.SetProgress(percentage);
            }

            #region Инициализация

            SetStep(1, MainResources.StepInitializing);
            _visualProgress.ShowIndeterminateLabel();

            string sourceApkPath      = ViewModel.CurrentApk.Value;
            bool   alternativeSigning = _settings.AlternativeSigning;

            string popupText     = ViewModel.PopupBoxText.Value;
            int    messagesCount = ViewModel.MessagesCount.Value;

            bool needSave;
            bool needMessage;
            {
                bool onlySave        = ViewModel.OnlySave.Value;
                bool savePlusMessage = ViewModel.SavePlusMess.Value;
                bool onlyMessage     = ViewModel.OnlyMess.Value;

                needSave    = onlySave || savePlusMessage;
                needMessage = (savePlusMessage || onlyMessage) && !string.IsNullOrEmpty(popupText) && messagesCount > 0;
            }

            BackupType backupType = ViewModel.BackupType.Value;

            ITempFileProvider   tempFileProvider   = _tempUtils.CreateTempFileProvider();
            ITempFolderProvider tempFolderProvider = _tempUtils.CreateTempFolderProvider();

            string resultApkPath = sourceApkPath.Remove(sourceApkPath.Length - Path.GetExtension(sourceApkPath).Length) + "_mod.apk";
            string pathToSave    = ViewModel.CurrentSave.Value;

            IApktool            apktool     = _apktoolProvider.Get();
            IProcessDataHandler dataHandler = new ProcessDataCombinedHandler(data => Log(data));

            #endregion

            #region Изменение apk

            using (var tempApk = ATempUtils.UseTempFile(tempFileProvider))
            {
                LFile.Copy(sourceApkPath, tempApk.TempFile, true);

                #region Добавление данных

                SetStep(2, MainResources.StepAddingData);

                var aes = new AesManaged {
                    KeySize = 128
                };
                aes.GenerateIV();
                aes.GenerateKey();

                bool backupFilesAdded = false;
                // adding local and external backup files
                if (needSave)
                {
                    using (var internalDataBackup = ATempUtils.UseTempFile(tempFileProvider))
                        using (var externalDataBackup = ATempUtils.UseTempFile(tempFileProvider))
                        {
                            ApkModifer.ParseBackup(
                                pathToBackup: pathToSave,
                                backupType: backupType,
                                resultInternalDataPath: internalDataBackup.TempFile,
                                resultExternalDataPath: externalDataBackup.TempFile,
                                tempFolderProvider: tempFolderProvider
                                );

                            string internalBackup = internalDataBackup.TempFile;
                            string externalBackup = externalDataBackup.TempFile;

                            var fileToAssetsName = new Dictionary <string, string>
                            {
                                { internalBackup, "data.save" },
                                { externalBackup, "extdata.save" }
                            };

                            foreach (var(file, assetsName) in fileToAssetsName.Enumerate())
                            {
                                if (!LFile.Exists(file) || FileUtils.FileLength(file) == 0)
                                {
                                    continue;
                                }

                                using (var tempEncrypted = ATempUtils.UseTempFile(tempFileProvider))
                                {
                                    CommonUtils.EncryptFile(
                                        filePath: file,
                                        outputPath: tempEncrypted.TempFile,
                                        iv: aes.IV,
                                        key: aes.Key
                                        );

                                    ApkModifer.AddFileToZip(
                                        zipPath: tempApk.TempFile,
                                        filePath: tempEncrypted.TempFile,
                                        pathInZip: "assets/" + assetsName,
                                        newEntryCompression: CompressionType.Store
                                        );
                                }

                                backupFilesAdded = true;
                            }
                        }
                }

                // adding smali file for restoring
                if (backupFilesAdded || needMessage)
                {
                    using (var decompiledFolder = ATempUtils.UseTempFolder(tempFolderProvider))
                    {
                        apktool.Baksmali(
                            apkPath: tempApk.TempFile,
                            resultFolder: decompiledFolder.TempFolder,
                            tempFolderProvider: tempFolderProvider,
                            dataHandler: dataHandler
                            );

                        var manifestPath = Path.Combine(decompiledFolder.TempFolder, "AndroidManifest.xml");

                        apktool.ExtractSimpleManifest(
                            apkPath: tempApk.TempFile,
                            resultManifestPath: manifestPath,
                            tempFolderProvider: tempFolderProvider
                            );

                        // have to have smali folders in the same directory as manifest
                        // to find the main smali
                        var manifest = new AndroidManifest(manifestPath);

                        if (manifest.MainSmaliFile == null)
                        {
                            throw new Exception("main smali file not found");
                        }

                        // using this instead of just pasting "folder/smali" as there can be
                        // no smali folder sometimes (smali_1, etc)
                        string smaliDir = manifest.MainSmaliPath.Substring(decompiledFolder.TempFolder.Length + 1);
                        smaliDir = smaliDir.Substring(0, smaliDir.IndexOf(Path.DirectorySeparatorChar));

                        string saveGameDir = Path.Combine(decompiledFolder.TempFolder, smaliDir, "com", "savegame");

                        LDirectory.CreateDirectory(saveGameDir);

                        CommonUtils.GenerateAndSaveSmali(
                            filePath: Path.Combine(saveGameDir, "SavesRestoringPortable.smali"),
                            iv: aes.IV,
                            key: aes.Key,
                            addSave: backupFilesAdded,
                            message: needMessage ? popupText : string.Empty,
                            messagesCount: needMessage ? messagesCount : 0
                            );

                        manifest.MainSmaliFile.AddTextToMethod(FileResources.MainSmaliCall);
                        manifest.MainSmaliFile.Save();

                        using (var folderWithDexes = ATempUtils.UseTempFolder(tempFolderProvider))
                        {
                            apktool.Smali(
                                folderWithSmali: decompiledFolder.TempFolder,
                                resultFolder: folderWithDexes.TempFolder,
                                dataHandler: dataHandler
                                );

                            string[] dexes = LDirectory.GetFiles(folderWithDexes.TempFolder, "*.dex");

                            ApkModifer.AddFilesToZip(
                                zipPath: tempApk.TempFile,
                                filePaths: dexes,
                                pathsInZip: Array.ConvertAll(dexes, Path.GetFileName),
                                newEntryCompression: CompressionType.Store
                                );
                        }
                    }
                }

                #endregion

                #region Подпись

                SetStep(3, MainResources.StepSigning);

                Log(Line);
                Log(MainResources.StepSigning);
                Log(Line);

                apktool.Sign(
                    sourceApkPath: tempApk.TempFile,
                    signedApkPath: resultApkPath,
                    tempFileProvider: tempFileProvider,
                    dataHandler: dataHandler,
                    deleteMetaInf: !alternativeSigning
                    );

                #endregion
            }

            #endregion

            _visualProgress.HideIndeterminateLabel();
            SetStep(4, MainResources.AllDone);
            Log(MainResources.AllDone);
            Log(string.Empty, false);
            Log($"{MainResources.Path_to_file} {resultApkPath}");

            _globalVariables.LatestModdedApkPath = resultApkPath;

            if (_settings.Notifications)
            {
                _notificationManager.Show(
                    title: MainResources.Information_Title,
                    text: MainResources.ModificationCompletedContent
                    );
            }

            string dialogResult = MessBox.ShowDial(
                $"{MainResources.Path_to_file} {resultApkPath}",
                MainResources.Successful,
                MainResources.OK, MainResources.Open, MainResources.Install
                );

            _visualProgress.HideBar();
            _taskBarManager.SetNoneState();

            if (dialogResult == MainResources.Open)
            {
                Process.Start("explorer.exe", $"/select,{resultApkPath}");
            }
            else if (dialogResult == MainResources.Install)
            {
                Dispatcher.Invoke(() => _adbInstallWindowProvider.Get().ShowDialog());
            }
        }
Ejemplo n.º 6
0
        public static byte[] EncryptPayload(String payloadPath, String outFile, String encryptionFile = "", byte[] IV = null, byte[] key = null, bool verbose = false, bool veryVerbose = false)
        {
            byte[] payload          = File.ReadAllBytes(payloadPath);
            byte[] encryptedPayload = new byte[payload.Length];

            using (AesManaged aesAlg = new AesManaged())
            {
                if (IV == null)
                {
                    IV = aesAlg.IV;
                }

                if (key == null)
                {
                    key = aesAlg.Key;
                }

                aesAlg.Padding = PaddingMode.PKCS7;
                aesAlg.Mode    = CipherMode.CBC;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(key, IV);
                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        {
                            //Write all data to the stream.
                            csEncrypt.Write(payload, 0, payload.Length);
                            csEncrypt.FlushFinalBlock();
                            encryptedPayload = msEncrypt.ToArray();
                        }
                    }
            }

            if (!String.IsNullOrEmpty(outFile))
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(outFile))
                {
                    file.WriteLine("===================CRYPTO=============================");
                    file.WriteLine("IMPORTANT INFO, DO NOT LOSE!");
                    file.WriteLine("If you wanna test decryption, you can copy paste the hex (payload,iv,key) straight in cyberchef :)");
                    file.WriteLine("The KEY in ASCII is:{0}", Encoding.Default.GetString(key));
                    file.WriteLine("Key in HEX: {0}", BitConverter.ToString(key));
                    file.WriteLine("The IV in ASCII is: {0}", Encoding.Default.GetString(IV));
                    file.WriteLine("The IV (hex) is: {0}", BitConverter.ToString(IV));
                    file.WriteLine("We are using PKCS7");
                    file.WriteLine("Good luck operator!");
                    file.WriteLine("The encrypted Payload size is: {0} bytes long.", encryptedPayload.Length);
                    //file.WriteLine("\n\n\nEncypted payload (in hex): \n");
                    //file.Write(BitConverter.ToString(encryptedPayload) + "\n");
                    file.Write("=======================================================\n\n\n");
                    file.Close();
                }
            }

            if (verbose || veryVerbose)
            {
                Console.WriteLine("================================================");
                Console.WriteLine("IMPORTANT INFO, DO NOT LOSE!");
                //Console.WriteLine("The KEY in ASCII is:{0}", Encoding.Default.GetString(key));
                Console.WriteLine("Key in HEX: {0}", BitConverter.ToString(key));
                Console.WriteLine("We are using PKCS7");
                // Console.WriteLine("The IV in ASCII is: {0}", Encoding.Default.GetString(IV));
                Console.WriteLine("The IV (hex) is: {0}", BitConverter.ToString(IV));
                Console.WriteLine("The encrypted Payload size is: {0} bytes long.", encryptedPayload.Length);
                if (veryVerbose)
                {
                    Console.WriteLine("Payload in HEX:\n{0}", BitConverter.ToString(encryptedPayload));
                }
                Console.WriteLine("Good luck operator!");
                if (!String.IsNullOrEmpty(outFile))
                {
                    Console.WriteLine("This data is written to the following path: " + outFile);
                }
                Console.WriteLine("================================================");
            }

            if (!String.IsNullOrEmpty(encryptionFile))
            {
                using (StreamWriter file = new StreamWriter(encryptionFile))
                {
                    file.WriteLine(BitConverter.ToString(encryptedPayload));
                }
                Console.WriteLine("Encrypted payload written to: {0}", encryptionFile);
            }
            return(encryptedPayload);
        }
Ejemplo n.º 7
0
        public static void main(string[] args)
        {
            AesManaged aes = new AesManaged();

            Console.WriteLine("AesManaged ");
            KeySizes[] ks = aes.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = aes.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }


            RijndaelManaged rij = new RijndaelManaged();

            Console.WriteLine("RijndaelManaged ");
            ks = rij.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = rij.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }
            TripleDESCryptoServiceProvider tsp = new TripleDESCryptoServiceProvider();

            Console.WriteLine("TripleDESCryptoServiceProvider ");
            ks = tsp.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
            }
            ks = tsp.LegalBlockSizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min block size = " + k.MinSize);
                Console.WriteLine("\tLegal max block size = " + k.MaxSize);
            }


            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.KeySize   = 256;
                rijAlg.BlockSize = 256;
                rijAlg.GenerateKey();
                rijAlg.GenerateIV();
                Console.Out.WriteLine(rijAlg.KeySize + " " + rijAlg.BlockSize + " " + Convert.ToBase64String(rijAlg.IV, Base64FormattingOptions.None) + " " +
                                      Convert.ToBase64String(rijAlg.Key, Base64FormattingOptions.None));
            }


            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();

            des.KeySize   = 192;
            des.BlockSize = 64;
            des.GenerateKey();
            des.GenerateIV();
            Console.Out.WriteLine(des.KeySize + " " + des.BlockSize + " " + Convert.ToBase64String(des.IV, Base64FormattingOptions.None) + " " +
                                  Convert.ToBase64String(des.Key, Base64FormattingOptions.None));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Simple Encryption(AES) then Authentication (HMAC) for a UTF8 Message.
        /// </summary>
        /// <param name="clearMessage">The secret message.</param>
        /// <param name="cryptKey">The crypt key.</param>
        /// <param name="nonEncryptedPayload">(Optional) Non-Secret Payload.</param>
        /// <returns>
        /// Encrypted Message
        /// </returns>
        /// <remarks>
        /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize +  HMac-Tag(32)) * 1.33 Base64
        /// </remarks>
        public static byte[] Encrypt(string clearMessage, byte[] cryptKey,
                                     byte[] nonEncryptedPayload)
        {
            var clearMessageBytes = Encoding.UTF8.GetBytes(clearMessage);

            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException($"Key needs to be {KeyBitSize} bit!", nameof(cryptKey));
            }

            if (clearMessageBytes == null || clearMessageBytes.Length < 1)
            {
                throw new ArgumentException("Secret Message Required!", nameof(clearMessageBytes));
            }


            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesManaged
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                    using (var cipherStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                            {
                                //Encrypt Data
                                binaryWriter.Write(clearMessageBytes);
                            }

                        cipherText = cipherStream.ToArray();
                    }
            }

            //Assemble encrypted message and add authentication
            using (var encryptedStream = new MemoryStream())
            {
                using (var binaryWriter = new BinaryWriter(encryptedStream))
                {
                    //Prepend non-secret payload if any
                    binaryWriter.Write(nonEncryptedPayload);
                    //Prepend IV
                    binaryWriter.Write(iv);
                    //Write Ciphertext
                    binaryWriter.Write(cipherText);
                    binaryWriter.Flush();
                }

                return(encryptedStream.ToArray());
            }
        }
        public static void StartClient(string Username, string Password)
        {
            // Data buffer for incoming data.
            byte[]             bytes = new byte[1024];
            SymmetricAlgorithm aes   = new AesManaged();



            string up = Username + '\n' + HashesClass.computeHash(Password, "MD5");

            // Connect to a remote device.
            try
            {
                // Establish the remote endpoint for the socket.
                // This example uses port 11000 on the local computer.
                IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
                IPAddress   ipAddress  = ipHostInfo.AddressList[0];
                IPEndPoint  remoteEP   = new IPEndPoint(ipAddress, 11000);

                // Create a TCP/IP  socket.
                Socket sender = new Socket(ipAddress.AddressFamily,
                                           SocketType.Stream, ProtocolType.Tcp);

                // Connect the socket to the remote endpoint. Catch any errors.
                try
                {
                    sender.Connect(remoteEP);

                    Console.WriteLine("Socket connected to {0}",
                                      sender.RemoteEndPoint.ToString());

                    // Encode the data string into a byte array.
                    byte[] message = Encoding.ASCII.GetBytes(up);


                    // Send the data through the socket.
                    int bytesSent = sender.Send(message);
                    Console.WriteLine(bytesSent);

                    // Receive the response from the remote device.
                    int bytesRec = sender.Receive(bytes);
                    Console.WriteLine("Echoed test = {0}",
                                      Encoding.ASCII.GetString(bytes, 0, bytesRec));

                    // Release the socket.
                    sender.Shutdown(SocketShutdown.Both);
                    sender.Close();
                }
                catch (ArgumentNullException ane)
                {
                    Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
                }
                catch (SocketException se)
                {
                    Console.WriteLine("SocketException : {0}", se.ToString());
                }
                catch (Exception e)
                {
                    Console.WriteLine("Unexpected exception : {0}", e.ToString());
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
        // Encrypt a file using a public key.
        private static MemoryStream  EncryptFile(byte[] unencryptedData, RSACryptoServiceProvider rsaPublicKey)
        {
            MemoryStream stream = null;

            using (AesManaged aesManaged = new AesManaged())
            {
                // Create instance of AesManaged for
                // symetric encryption of the data.
                aesManaged.KeySize   = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode      = CipherMode.CBC;
                using (ICryptoTransform transform = aesManaged.CreateEncryptor())
                {
                    RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(rsaPublicKey);
                    byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());
                    // Create byte arrays to contain
                    // the length values of the key and IV.
                    byte[] LenK  = new byte[4];
                    byte[] LenIV = new byte[4];
                    int    lKey  = keyEncrypted.Length;
                    LenK = BitConverter.GetBytes(lKey);
                    int lIV = aesManaged.IV.Length;
                    LenIV = BitConverter.GetBytes(lIV);
                    // Write the following to the FileStream
                    // for the encrypted file (outFs):
                    // - length of the key
                    // - length of the IV
                    // - ecrypted key
                    // - the IV
                    // - the encrypted cipher content
                    stream = new MemoryStream();
                    try
                    {
                        stream.Write(LenK, 0, 4);
                        stream.Write(LenIV, 0, 4);
                        stream.Write(keyEncrypted, 0, lKey);
                        stream.Write(aesManaged.IV, 0, lIV);
                        // Now write the cipher text using
                        // a CryptoStream for encrypting.
                        CryptoStream outStreamEncrypted = new CryptoStream(stream, transform, CryptoStreamMode.Write);
                        try
                        {
                            // By encrypting a chunk at
                            // a time, you can save memory
                            // and accommodate large files.
                            int count  = 0;
                            int offset = 0;
                            // blockSizeBytes can be any arbitrary size.
                            int blockSizeBytes = aesManaged.BlockSize / 8;
                            do
                            {
                                if (offset + blockSizeBytes <= unencryptedData.Length)
                                {
                                    count = blockSizeBytes;
                                }
                                else
                                {
                                    count = unencryptedData.Length - offset;
                                }
                                outStreamEncrypted.Write(unencryptedData, offset, count);
                                offset += count;
                            }while (offset < unencryptedData.Length);
                            outStreamEncrypted.FlushFinalBlock();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error : {0}", ex.Message);
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Error : {0}", ex.Message);
                    }
                    stream.Position = 0;
                }
            }
            return(stream);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Encrypt bytes from the stream using a string password.
        /// </summary>
        public static MemoryStream EncryptWithPassword(Stream stream, string password, byte[] nonSecretPayload = null)
        {
            byte[] payload;
            int    payloadIndex;

            if (nonSecretPayload == null)
            {
                payload = BufferCache.Get(SaltBitSize * 2);

                payloadIndex = 0;
            }
            else
            {
                payload = BufferCache.Get((SaltBitSize * 2) + nonSecretPayload.Length);

                Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
                payloadIndex = nonSecretPayload.Length;
            }

            byte[] cryptKey;
            byte[] authKey;
            //Use Random Salt to prevent pre-generated weak password attacks.
            using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize, Iterations)) {
                var salt = generator.Salt;

                // generate the cryptography key
                cryptKey = generator.GetBytes(KeyBitSize);

                // copy the salt
                Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
                payloadIndex += salt.Length;
            }

            //Deriving separate key, might be less efficient than using HKDF,
            //but now compatible with RNEncryptor which had a very similar wireformat and requires less code than HKDF.
            using (var generator = new Rfc2898DeriveBytes(password, SaltBitSize, Iterations)) {
                var salt = generator.Salt;

                // generate the auth key
                authKey = generator.GetBytes(KeyBitSize);

                // create the rest of the non-secret payload
                Array.Copy(salt, 0, payload, payloadIndex, salt.Length);
                payloadIndex += salt.Length;
            }

            byte[] iv;
            byte[] buffer = BufferCache.Get();

            using (var aes = new AesManaged {
                Key = cryptKey,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.Zeros
            }) {
                // use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor())
                    using (var cipherStream = new MemoryStream())
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write)) {
                            // read from the stream
                            int count = stream.Read(buffer, 0, Global.BufferSizeLocal);

                            // while the buffer is filled
                            while (count == Global.BufferSizeLocal)
                            {
                                // write to the crypto stream
                                cryptoStream.Write(buffer, 0, count);

                                // read from the stream
                                count = stream.Read(buffer, 0, Global.BufferSizeLocal);
                            }

                            // write the final buffer
                            cryptoStream.Write(buffer, 0, count);

                            // flush the encryped stream
                            cryptoStream.Flush();

                            cipherStream.Position = 0;

                            // assemble encrypted message and add authentication
                            var encryptedStream = new MemoryStream();

                            // prepend payload
                            encryptedStream.Write(payload, 0, payloadIndex);
                            // prepend IV
                            encryptedStream.Write(iv, 0, iv.Length);

                            // read from the stream
                            count = cipherStream.Read(buffer, 0, Global.BufferSizeLocal);

                            while (count == Global.BufferSizeLocal)
                            {
                                // write to the crypto stream
                                encryptedStream.Write(buffer, 0, count);

                                // read from the stream
                                count = cipherStream.Read(buffer, 0, Global.BufferSizeLocal);
                            }

                            // write the final buffer
                            encryptedStream.Write(buffer, 0, count);

                            BufferCache.Set(buffer);


                            // authenticate all data by postpending a hash of all data
                            encryptedStream.Position = payloadIndex + iv.Length;

                            using (var hmac = new HMACSHA256(authKey)) {
                                // calculate a hash of the entire stream excluding the payload and iv
                                // that can be used to authenticate the received data
                                byte[] tag = hmac.ComputeHash(encryptedStream);

                                // write the tag to the end of the encrypted stream
                                encryptedStream.Write(tag, 0, tag.Length);
                            }

                            // reset the stream position
                            encryptedStream.Position = 0;

                            // return the complete, encrypted stream
                            return(encryptedStream);
                        }
            }
        }
Ejemplo n.º 12
0
        private async void button2_Click(object sender, EventArgs e)
        {
            try
            {
                textBox7.Text = GetRandomAlphanumericString(32);
                SqlConnection con   = new SqlConnection("Data Source=DESKTOP-VDKS12B\\VS;Initial Catalog=SeDaSc;Integrated Security=True");
                string        getki = " SELECT userkey FROM [SeDaSc].[dbo].[access_rights_read] WHERE read_name = '" + comboBox2.Text + "' and group_id='" + comboBox3.Text + "'";
                SqlCommand    re1   = new SqlCommand(getki, con);
                con.Open();
                SqlDataReader obj1 = re1.ExecuteReader();
                if (!(obj1.HasRows))
                {
                    MessageBox.Show("There is no Read Access for the Current User ", "Secure Data Sharing in Cloud", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
                else
                {
                    while (obj1.Read())
                    {
                        textBox8.Text = obj1["userkey"].ToString();
                    }
                }
                con.Close();
                string getkiwri = " SELECT userkey FROM [SeDaSc].[dbo].[access_rights_write] WHERE write_name = '" + comboBox2.Text + "' and group_id='" + comboBox3.Text + "'";
                re1 = new SqlCommand(getkiwri, con);
                con.Open();
                obj1 = re1.ExecuteReader();
                if (!(obj1.HasRows))
                {
                    MessageBox.Show("There is no Write Access for the Current User ", "Secure Data Sharing in Cloud", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    textBox9.Enabled = false;
                }
                else
                {
                    while (obj1.Read())
                    {
                        textBox8.Text = obj1["userkey"].ToString();
                    }
                    textBox9.Enabled = true;
                }
                con.Close();
                FirebaseResponse response = await client.GetTaskAsync("Users/" + comboBox3.Text);

                Data results = response.ResultAs <Data>();
                if (results.cipher != null)
                {
                    textBox6.Text = results.cipher;
                }
                else
                {
                    MessageBox.Show("There is no Data for the Current User ", "Secure Data Sharing in Cloud", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                }
                StringBuilder sb = new StringBuilder();
                StringBuilder xv = new StringBuilder();
                foreach (char c in textBox5.Text.ToCharArray())
                {
                    sb.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
                }
                foreach (char c in textBox8.Text.ToCharArray())
                {
                    xv.Append(Convert.ToString(c, 2).PadLeft(8, '0'));
                }
                string binkey  = sb.ToString();
                string binkey2 = xv.ToString();
                string userkey = "";
                for (int i = 0; i < binkey.Length; i++)
                {
                    char x;
                    char y = binkey[i];
                    char z = binkey2[i];
                    x = (char)(binkey[i] ^ binkey2[i]);
                    if (x == '\0')
                    {
                        x = '0';
                    }
                    else
                    {
                        x = '1';
                    }
                    userkey += x;
                }

                string      temp     = userkey;
                List <Byte> byteList = new List <Byte>();

                for (int i = 0; i < userkey.Length; i += 8)
                {
                    byteList.Add(Convert.ToByte(userkey.Substring(i, 8), 2));
                }
                AesManaged aes = new AesManaged();
                textBox7.Text = Encoding.ASCII.GetString(byteList.ToArray());
                string ciphers = textBox6.Text;
                byte[] bytes   = Encoding.UTF8.GetBytes(ciphers);
                textBox9.Text = results.file.ToString();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Ejemplo n.º 13
0
        private byte[] MakeSecret()
        {
            byte[] secret = new byte[16];
            new Random().NextBytes(secret);
            aes = new AesManaged();
            aes.Key = secret;
            aes.IV = secret;

            return secret;
        }
Ejemplo n.º 14
0
 public static void VerifyDefaults()
 {
     using (var alg = new AesManaged())
     {
         Assert.Equal(128, alg.BlockSize);
         Assert.Equal(256, alg.KeySize);
         Assert.Equal(CipherMode.CBC, alg.Mode);
         Assert.Equal(PaddingMode.PKCS7, alg.Padding);
     }
 }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            if (args == null || args.Length < 1 || (args[0].ToLower() != "e" && args[0].ToLower() != "d"))
            {
                Console.Error.WriteLine("Usage:");
                Console.Error.WriteLine(" To encrypt: AesCrypt.exe e <file path>");
                Console.Error.WriteLine(" To decrypt: AesCrypt.exe d <file path> <iv> <key>");
                return;
            }

            if (args[0].ToLower() == "e")
            {
                // ENCRYPTION

                if (args.Length < 2)
                {
                    Console.Error.WriteLine("Usage: AesCrypt.exe e <file path>");
                }

                string   fileToEncrypt = args[1];
                FileInfo inpFile       = new FileInfo(fileToEncrypt);
                if (!inpFile.Exists)
                {
                    Console.Error.WriteLine("File does not exist");
                    return;
                }

                byte[] fileName = Encoding.UTF8.GetBytes(inpFile.FullName);

                string rootDir    = Path.GetDirectoryName(fileToEncrypt);
                string randomName = Guid.NewGuid().ToString("N");
                string tempName   = Path.Combine(rootDir, randomName);
                string finalHash;

                if (File.Exists(tempName))
                {
                    Console.Error.WriteLine("ERROR: temporary file exists, wtf how does that even happen");
                    return;
                }

                using (FileStream inp = File.Open(fileToEncrypt, FileMode.Open, FileAccess.Read, FileShare.Read))
                    using (FileStream oup = File.Create(tempName))
                        using (AesManaged enc = new AesManaged())
                        {
                            enc.KeySize = 256;
                            enc.Mode    = CipherMode.CBC;

                            enc.GenerateIV();
                            enc.GenerateKey();

                            SHA512Managed originalHash = new SHA512Managed();
                            originalHash.Initialize();

                            SHA512Managed cryptedHash = new SHA512Managed();
                            using (CryptoStream hashStream = new CryptoStream(oup, cryptedHash, CryptoStreamMode.Write))
                                using (CryptoStream cs = new CryptoStream(hashStream, enc.CreateEncryptor(), CryptoStreamMode.Write))
                                {
                                    // crypted file structure: {name length x2}{full file name}{data length x8}{data}{sha512 hash of data x64}

                                    byte[] lenFileName = BitConverter.GetBytes((ushort)fileName.Length);
                                    cs.Write(lenFileName, 0, lenFileName.Length);

                                    cs.Write(fileName, 0, fileName.Length);

                                    byte[] fileSizeBits = BitConverter.GetBytes(inpFile.Length);
                                    cs.Write(fileSizeBits, 0, fileSizeBits.Length);

                                    byte[] data = new byte[64 * 1024];
                                    int    bytesRead;
                                    long   bytesHashed = 0;
                                    do
                                    {
                                        // pull data from original file
                                        bytesRead = inp.Read(data, 0, data.Length);

                                        // send it to crypted stream
                                        cs.Write(data, 0, bytesRead);

                                        // also hash it for decryption verification purposes
                                        bytesHashed += originalHash.TransformBlock(data, 0, bytesRead, data, 0);
                                    } while (bytesRead > 0);

                                    // write original hash into crypted file so we can verify it after decryption
                                    originalHash.TransformFinalBlock(data, 0, 0);
                                    cs.Write(originalHash.Hash, 0, originalHash.Hash.Length);
                                }

                            finalHash = Base32.ToBase32String(cryptedHash.Hash);

                            string iv  = Convert.ToBase64String(enc.IV);
                            string key = Convert.ToBase64String(enc.Key);

                            Console.Out.WriteLine("{0} {1} {2}", finalHash, iv, key);
                        }

                File.Move(tempName, Path.Combine(rootDir, finalHash));
            }
            else
            {
                // DECRYPTION

                if (args.Length < 4)
                {
                    Console.Error.WriteLine("Usage: AesCrypt.exe d <file path> <iv> <key>");
                    return;
                }

                FileInfo encFile = new FileInfo(args[1]);
                if (!encFile.Exists)
                {
                    Console.Error.WriteLine("File does not exist");
                    return;
                }

                byte[] iv = Convert.FromBase64String(args[2]);
                if (iv == null || iv.Length < 1)
                {
                    Console.Error.WriteLine("ERROR: invalid iv");
                    return;
                }
                byte[] key = Convert.FromBase64String(args[3]);
                if (key == null || key.Length < 1)
                {
                    Console.Error.WriteLine("ERROR: invalid key");
                    return;
                }

                using (FileStream inp = encFile.OpenRead())
                    using (AesManaged aes = new AesManaged())
                    {
                        aes.KeySize = 256;
                        aes.Mode    = CipherMode.CBC;

                        aes.IV  = iv;
                        aes.Key = key;

                        using (CryptoStream cs = new CryptoStream(inp, aes.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            // crypted file structure: {name length x4}{full file name}{data length x8}{data}{sha512 hash of data x64}

                            byte[] nameLengthBits = new byte[2];
                            if (cs.Read(nameLengthBits, 0, 2) != 2)
                            {
                                Console.Error.WriteLine("ERROR: Failed reading file name size");
                                return;
                            }
                            ushort nameLength = BitConverter.ToUInt16(nameLengthBits, 0);

                            byte[] originalName = new byte[nameLength];
                            if (cs.Read(originalName, 0, nameLength) != nameLength)
                            {
                                Console.Error.WriteLine("ERROR: Failed reading file name");
                                return;
                            }
                            string fileName = Encoding.UTF8.GetString(originalName);

                            byte[] dataLengthBits = new byte[8];
                            if (cs.Read(dataLengthBits, 0, dataLengthBits.Length) != dataLengthBits.Length)
                            {
                                Console.Error.WriteLine("ERROR: Failed reading data length");
                                return;
                            }
                            long dataLength = BitConverter.ToInt64(dataLengthBits, 0);

                            string outputFileName = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(fileName));
                            if (File.Exists(outputFileName))
                            {
                                Console.Error.WriteLine("ERROR: '{0}' already exists, exiting", outputFileName);
                                return;
                            }

                            Console.Out.WriteLine("Decrypting what was originally called '{0}' ({1:N0} bytes)", fileName, dataLength);
                            byte[] decryptedHash;
                            long   totalRead = 0;
                            using (FileStream outputStream = new FileStream(outputFileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
                                using (SHA512Managed hasher = new SHA512Managed())
                                {
                                    byte[] buffer         = new byte[ReadBufferSize];
                                    long   bytesRemaining = dataLength;
                                    while (bytesRemaining > 0)
                                    {
                                        int readingThisRound = ReadBufferSize < bytesRemaining ? ReadBufferSize : (int)bytesRemaining;
                                        int bytesRead        = cs.Read(buffer, 0, readingThisRound);
                                        totalRead += bytesRead;

                                        // dump decrypted data to file
                                        outputStream.Write(buffer, 0, bytesRead);

                                        // run it through the grinder for verification later
                                        int hashProgress = hasher.TransformBlock(buffer, 0, bytesRead, buffer, 0);
                                        Debug.Assert(hashProgress == bytesRead, "Hash calculation out of whack with file IO, wtf is going on");

                                        bytesRemaining -= bytesRead;
                                    }

                                    hasher.TransformFinalBlock(buffer, 0, 0);
                                    decryptedHash = hasher.Hash;
                                }

                            byte[] originalHashBits = new byte[64];
                            if (cs.Read(originalHashBits, 0, originalHashBits.Length) != originalHashBits.Length)
                            {
                                Console.Error.WriteLine("ERROR: Failed reading verification hash, encrypted file is corrupted!");
                                return;
                            }

                            if (originalHashBits.SequenceEqual(decryptedHash))
                            {
                                Console.Out.WriteLine("Successfully decrypted '{0}'", outputFileName);
                            }
                            else
                            {
                                Console.Out.WriteLine("Decryption FAIL");
                            }
                        }
                    }
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Decrypt with password. The stream must be navigatable.
        /// </summary>
        public static Stream DecryptWithPassword(Stream stream, string password, int nonSecretPayloadLength = 0)
        {
            const int ivLength = BlockBitSize / 8;

            var cryptSalt = new byte[SaltBitSize];
            var authSalt  = new byte[SaltBitSize];

            var streamStartPosition = stream.Position;

            // grab Salt from Non-Secret Payload
            if (nonSecretPayloadLength != 0)
            {
                stream.Position = streamStartPosition + nonSecretPayloadLength;
            }
            stream.Read(cryptSalt, 0, SaltBitSize);
            stream.Read(authSalt, 0, SaltBitSize);

            // grab IV from message
            var iv = new byte[ivLength];

            stream.Read(iv, 0, ivLength);


            byte[] cryptKey;
            byte[] authKey;

            // generate crypt key
            using (var generator = new Rfc2898DeriveBytes(password, cryptSalt, Iterations)) {
                cryptKey = generator.GetBytes(KeyBitSize);
            }
            // generate auth key
            using (var generator = new Rfc2898DeriveBytes(password, authSalt, Iterations)) {
                authKey = generator.GetBytes(KeyBitSize);
            }

            using (var hmac = new HMACSHA256(authKey)) {
                int sentTagLength = hmac.HashSize / 8;

                // if message length is to small just return null
                if (stream.Length - streamStartPosition < sentTagLength + nonSecretPayloadLength + ivLength)
                {
                    throw new CryptographicException("Insufficient bytes in stream.");
                }

                // get the number of encrypted bytes that constitute the message
                int count = (int)(stream.Length -
                                  streamStartPosition -
                                  sentTagLength -
                                  nonSecretPayloadLength -
                                  ivLength -
                                  SaltBitSize - SaltBitSize);

                byte[] tagContent = BufferCache.Get(count);

                // read the bytes required for the tag hash
                count = stream.Read(tagContent, 0, count);

                // calculate the tag hash
                byte[] calcTag = hmac.ComputeHash(tagContent, 0, count);

                // read sent tag
                stream.Read(tagContent, 0, sentTagLength);

                // compare tag with constant time comparison
                var compare = 0;
                for (var i = 0; i < sentTagLength; ++i)
                {
                    compare |= tagContent[i] ^ calcTag[i];
                }

                BufferCache.Set(tagContent);

                // if message doesn't authenticate, throw
                if (compare != 0)
                {
                    throw new CryptographicException("Data hash was not correct.");
                }

                using (var aes = new AesManaged {
                    Key = cryptKey,
                    IV = iv,
                    BlockSize = BlockBitSize,
                    Mode = CipherMode.CBC,
                    Padding = PaddingMode.Zeros
                }) {
                    // create a memory stream for the decrypted bytes
                    var decrypted = new MemoryStream();

                    using (var decrypter = aes.CreateDecryptor()) {
                        var decrypterStream = new CryptoStream(decrypted, decrypter, CryptoStreamMode.Write);

                        byte[] buffer = BufferCache.Get();

                        // move to the start of the encrypted data
                        stream.Position = streamStartPosition +
                                          nonSecretPayloadLength +
                                          SaltBitSize + SaltBitSize +
                                          ivLength;

                        // determine the bytes to be written to the decrypter stream
                        int remaining = (int)(stream.Length - stream.Position - sentTagLength);

                        // read the first buffer from the stream
                        count = stream.Read(buffer, 0, remaining > Global.BufferSizeLocal ? Global.BufferSizeLocal : remaining);

                        // while the buffer is full
                        while (count == Global.BufferSizeLocal)
                        {
                            // decrement the remaining bytes
                            remaining -= count;

                            // write the buffer
                            decrypterStream.Write(buffer, 0, count);

                            // read a new buffer
                            count = stream.Read(buffer, 0, Global.BufferSizeLocal);
                        }

                        // if the stream ended prematurely, throw
                        if (count != remaining)
                        {
                            throw new EndOfStreamException();
                        }

                        // write final buffer
                        decrypterStream.Write(buffer, 0, count);

                        BufferCache.Set(buffer);

                        // flush the decryption stream
                        decrypterStream.FlushFinalBlock();

                        // set the decrpted memory stream position
                        decrypted.Position = 0;

                        // return the decrypted stream
                        return(decrypted);
                    }
                }
            }
        }
Ejemplo n.º 17
0
        private async static Task File(string inFile, string outFile, RSACryptoServiceProvider key)
        {
            using (AesManaged aesManaged = new AesManaged())
            {
                // Create instance of AesManaged for
                // symetric encryption of the data.
                aesManaged.KeySize   = 256;
                aesManaged.BlockSize = 128;
                aesManaged.Mode      = CipherMode.CBC;
                using (ICryptoTransform transform = aesManaged.CreateEncryptor())
                {
                    RSAPKCS1KeyExchangeFormatter keyFormatter = new RSAPKCS1KeyExchangeFormatter(key);
                    byte[] keyEncrypted = keyFormatter.CreateKeyExchange(aesManaged.Key, aesManaged.GetType());

                    // Create byte arrays to contain
                    // the length values of the key and IV.
                    byte[] LenK  = new byte[4];
                    byte[] LenIV = new byte[4];

                    int lKey = keyEncrypted.Length;
                    LenK = BitConverter.GetBytes(lKey);
                    int lIV = aesManaged.IV.Length;
                    LenIV = BitConverter.GetBytes(lIV);

                    // Write the following to the FileStream
                    // for the encrypted file (outFs):
                    // - length of the key
                    // - length of the IV
                    // - ecrypted key
                    // - the IV
                    // - the encrypted cipher content
                    using (FileStream outFs = new FileStream(outFile, FileMode.Create))
                    {
                        await outFs.WriteAsync(LenK, 0, 4);

                        await outFs.WriteAsync(LenIV, 0, 4);

                        await outFs.WriteAsync(keyEncrypted, 0, lKey);

                        await outFs.WriteAsync(aesManaged.IV, 0, lIV);

                        // Now write the cipher text using
                        // a CryptoStream for encrypting.
                        using (CryptoStream outStreamEncrypted = new CryptoStream(outFs, transform, CryptoStreamMode.Write))
                        {
                            // By encrypting a chunk at
                            // a time, you can save memory
                            // and accommodate large files.
                            int count  = 0;
                            int offset = 0;

                            // blockSizeBytes can be any arbitrary size.
                            int    blockSizeBytes = aesManaged.BlockSize / 8;
                            byte[] data           = new byte[blockSizeBytes];
                            int    bytesRead      = 0;

                            using (FileStream inFs = new FileStream(inFile, FileMode.Open))
                            {
                                do
                                {
                                    count = await inFs.ReadAsync(data, 0, blockSizeBytes);

                                    offset += count;
                                    await outStreamEncrypted.WriteAsync(data, 0, count);

                                    bytesRead += blockSizeBytes;
                                }while (count > 0);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
        internal AesDecryptionResult DecryptWithMemoryStream(byte[] encryptedData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC,
                                                             PaddingMode paddingMode          = PaddingMode.PKCS7)
        {
            if (encryptedData == null || encryptedData.Length == 0)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_InputRequired
                });
            }

            _key = key ?? _key;
            _IV  = IV ?? _IV;

            if (_key == null)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullKeyError
                });
            }

            if (_IV == null)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullIVError
                });
            }

            byte[] decryptedData = null;

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    if (aesManaged.ValidKeySize((_key.Length * 8)))
                    {
                        aesManaged.Key = _key;
                    }
                    else
                    {
                        return(new AesDecryptionResult()
                        {
                            Success = false,
                            Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})."
                        });
                    }

                    aesManaged.IV      = _IV;
                    aesManaged.Mode    = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var decryptor = aesManaged.CreateDecryptor(_key, _IV))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Write))
                            {
                                using (var bw = new BinaryWriter(cs))
                                {
                                    bw.Write(encryptedData);
                                }
                            }

                            decryptedData = ms.ToArray();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_ExceptionError}\n{ex.ToString()}"
                });
            }

            return(new AesDecryptionResult()
            {
                Success = true,
                Message = MessageStrings.Decryption_DecryptSuccess,
                DecryptedDataBytes = decryptedData,
                DecryptedDataString = System.Text.Encoding.UTF8.GetString(decryptedData),
                Key = _key,
                IV = _IV,
                AesCipherMode = (AesCipherMode)cipherMode,
                PaddingMode = paddingMode
            });
        }
    /// <summary>
    /// Encrypts a JSON representation of a UserData object using AES128-CBC with a 16-bit SHA1 salted hash key.
    /// Returns a Base64 String containing the encrypted JSON pre-pended with the initialization vector (IV) used in the encryption.
    /// </summary>
    /// <param name="user_data">The UserData object to be encrypted.</param>
    /// <returns></returns>
    protected static string EncryptData(UserData user_data)
    {
        // Using byte arrays instead of strings
            byte[] encrypted;
            byte[] saltedHash;
            byte[] bIV = new byte[16];  // 16-byte initialization vector as a byte array.
            byte[] bJsonUserData;
            /* Uncomment to enable decrypting for debugging/testing
            byte[] decrypted = null;
             */

            // Encode the user_data object into a JSON string
            JavaScriptSerializer s = new JavaScriptSerializer();
            string json_data = s.Serialize(user_data);
            bJsonUserData = Encoding.ASCII.GetBytes(json_data);

            // Generate a random initialization vector
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            rng.GetBytes(bIV);

            // Use an AesManaged object to do the encryption
            using (AesManaged aesAlg = new AesManaged())
            {
                aesAlg.IV = bIV;
                aesAlg.KeySize = 128;

                // Create the 16-byte salted hash
                SHA1 sha1 = SHA1.Create();
                saltedHash = sha1.ComputeHash(Encoding.ASCII.GetBytes(api_key + site_key), 0, (api_key + site_key).Length);
                // Trim saltedHash to 16 bytes.
                Array.Resize(ref saltedHash, 16);

                // Use salted has as the AES key.
                aesAlg.Key = saltedHash;

                // Encrypt using the AES Managed object
                ICryptoTransform encryptor = aesAlg.CreateEncryptor();
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        csEncrypt.Write(bJsonUserData, 0, bJsonUserData.Length);
                        csEncrypt.FlushFinalBlock();
                    }
                    encrypted = msEncrypt.ToArray();
                }

                /*
                 * Uncomment to enable decrypting for debugging/testing
                 *
                // Decrypt using AES Managed object
                ICryptoTransform decryptor = aesAlg.CreateDecryptor();
                using (MemoryStream msDecrypt = new MemoryStream())
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write))
                    {
                        csDecrypt.Write(encrypted, 0, encrypted.Length);
                        csDecrypt.FlushFinalBlock();
                    }
                    decrypted = msDecrypt.ToArray();
                }

                string decryptedString = Encoding.ASCII.GetString(decrypted);
                 */
            }

            // Pre-pend the encrypted data with the IV.
            byte[] ivPlusEncrypted = bIV.Concat(encrypted).ToArray();

            // Return the Base64-encoded encrypted data
            string encryptedBase64 = Convert.ToBase64String(ivPlusEncrypted, Base64FormattingOptions.None);
            return encryptedBase64;
    }
Ejemplo n.º 20
0
        internal AesEncryptionResult EncryptWithFileStream(string sourceFilePath, string encryptedFilePath, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC,
                                                           PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteSourceFile            = false, int kBbufferSize = 4)
        {
            if (!File.Exists(sourceFilePath))
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    //Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                    Message = $"{MessageStrings.Common_FileNotFound} \"{sourceFilePath}\"."
                });
            }

            if (string.IsNullOrWhiteSpace(encryptedFilePath))
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Encryption_EncryptedFilePathError
                });
            }

            var destinationDirectory = Path.GetDirectoryName(encryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                });
            }

            _key = key ?? _key;
            _IV  = IV ?? _IV;

            var pathsEqual = encryptedFilePath.Equals(sourceFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    if (_key == null)
                    {
                        aesManaged.GenerateKey();
                        _key = aesManaged.Key;
                    }
                    else
                    {
                        if (aesManaged.ValidKeySize((_key.Length * 8)))
                        {
                            aesManaged.Key = _key;
                        }
                        else
                        {
                            return(new AesEncryptionResult()
                            {
                                Success = false,
                                Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})."
                            });
                        }
                    }

                    if (_IV == null || _IV.Length == 0)
                    {
                        aesManaged.GenerateIV();
                        _IV = aesManaged.IV;
                    }
                    else
                    {
                        aesManaged.IV = _IV;
                    }

                    aesManaged.Mode    = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var encryptor = aesManaged.CreateEncryptor(_key, _IV))
                    {
                        using (var sourceFs = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            using (var encryptedFs = File.Open((pathsEqual ? encryptedFilePath + "_tmpcrypt" : encryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                            {
                                using (var cs = new CryptoStream(encryptedFs, encryptor, CryptoStreamMode.Write))
                                {
                                    //plain.CopyTo(cs);

                                    var buffer = new byte[kBbufferSize * 1024];
                                    int read;
                                    var percentageDone = 0;

                                    while ((read = sourceFs.Read(buffer, 0, buffer.Length)) > 0)
                                    {
                                        cs.Write(buffer, 0, read);

                                        var tmpPercentageDone = (int)(sourceFs.Position * 100 / sourceFs.Length);

                                        if (tmpPercentageDone != percentageDone)
                                        {
                                            percentageDone = tmpPercentageDone;

                                            RaiseOnEncryptionProgress(percentageDone, (percentageDone != 100 ? $"Encrypting ({percentageDone}%)..." : $"Encrypted ({percentageDone}%)."));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                    File.Move(encryptedFilePath + "_tmpcrypt", encryptedFilePath);
                }

                if (deleteSourceFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(sourceFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(sourceFilePath);
                }

                //var message = $"File \"{sourceFilePath}\" successfully encrypted to \"{encryptedFilePath}\".";
                var message = string.Format(MessageStrings.Encryption_FileEncryptSuccess, sourceFilePath, encryptedFilePath);
                message += (deleteSourceFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, sourceFilePath)}" : "");

                return(new AesEncryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                });
            }
            catch (Exception ex)
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}"
                });
            }
        }
Ejemplo n.º 21
0
        private static void TryECMA376()
        {
            byte[] salt = new byte[] { 0x30, 0x3A, 0x39, 0x9E, 0x02, 0xB6, 0x66, 0x71, 0xA9, 0xEA, 0xDB, 0x17, 0x0C, 0xA6, 0xDF, 0x24 };
            byte[] pwd  = Encoding.Unicode.GetBytes("123");
            byte[] tmp  = H(salt, pwd);
            for (int i = 0; i < 50000; i++)
            {
                byte[] tmpI = BitConverter.GetBytes(i);
                tmp = H(tmpI, tmp);
            }
            tmp = H(tmp, BitConverter.GetBytes(0));

            SHA1Managed sha = new SHA1Managed();

            byte[] XorBuff = new byte[64];
            for (int i = 0; i < XorBuff.Length; i++)
            {
                XorBuff[i] = 0x36;
            }

            for (int i = 0; i < tmp.Length; i++)
            {
                XorBuff[i] ^= tmp[i];
            }

            tmp = sha.ComputeHash(XorBuff);

            byte[] key = new byte[16];
            Array.Copy(tmp, key, 16);

            byte[] pwdVerifier     = new byte[] { 0x0A, 0x3A, 0xD5, 0x44, 0x17, 0xAB, 0x9B, 0x26, 0xA7, 0xFC, 0x65, 0xFE, 0x2F, 0x77, 0xDD, 0xA0 };
            byte[] pwdVerifierHash = new byte[] { 0x29, 0x0E, 0x48, 0xC6, 0x26, 0xA8, 0x72, 0x3B, 0xA2, 0xCF, 0x3F, 0x6A, 0x9B, 0x3A, 0x94, 0xB8, 0x59, 0x7A, 0x8E, 0xCE, 0xB5, 0x55, 0xE9, 0x15, 0x06, 0x89, 0xCD, 0x9C, 0xDA, 0x6C, 0x39, 0x31 };

            AesManaged aes = new AesManaged();

            aes.Mode    = CipherMode.ECB;
            aes.KeySize = 128;
            aes.Key     = key;
            aes.Padding = PaddingMode.None;
            ICryptoTransform ict  = aes.CreateDecryptor();
            ICryptoTransform ict2 = aes.CreateDecryptor();

            byte[] pwdVerifierDec;
            byte[] pwdVerifierHashDec;
            pwdVerifierDec     = ict.TransformFinalBlock(pwdVerifier, 0, pwdVerifier.Length);
            pwdVerifierHashDec = ict.TransformFinalBlock(pwdVerifierHash, 0, pwdVerifierHash.Length);
            //pwdVerifierDec = new byte[16];
            //pwdVerifierHashDec = new byte[32];
            //ict.TransformBlock(pwdVerifier, 0, pwdVerifier.Length, pwdVerifierDec, 0);
            //ict2.TransformBlock(pwdVerifierHash, 0, 32, pwdVerifierHashDec, 0);
            //ict2.TransformBlock(pwdVerifierHash, 16, 16, pwdVerifierHashDec, 16);

            pwdVerifierDec = sha.ComputeHash(pwdVerifierDec);

            for (int i = 0; i < pwdVerifierDec.Length; i++)
            {
                if (pwdVerifierDec[i] != pwdVerifierHashDec[i])
                {
                    Console.WriteLine("Oh, NO!!!!!!!!!!!!!!!");
                    return;
                }
            }
            Console.WriteLine("Yahooooooooooooo~~~~~");

            FileStream fs = File.OpenRead("C:\\Users\\Administrator\\Desktop\\加密\\EncryptedPackage");

            byte[] encPak = new byte[fs.Length];
            fs.Read(encPak, 0, encPak.Length);
            byte[] decPak = new byte[fs.Length];
            fs.Close();
            decPak = ict2.TransformFinalBlock(encPak, 8, encPak.Length - 8);
            FileStream fso = File.Create("C:\\Users\\Administrator\\Desktop\\加密\\yeah.zip");

            fso.Write(decPak, 0, decPak.Length);
            fso.Close();
        }
Ejemplo n.º 22
0
        internal AesDecryptionResult DecryptWithFileStream(string encryptedFilePath, string decryptedFilePath, byte[] key, byte[] IV, CipherMode cipherMode = CipherMode.CBC,
                                                           PaddingMode paddingMode = PaddingMode.PKCS7, bool deleteEncryptedFile = false, int kBbufferSize = 4, long startPosition = 0, long endPosition = 0)
        {
            if (!File.Exists(encryptedFilePath))
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_EncryptedFileNotFound} \"{encryptedFilePath}\"."
                });
            }

            if (string.IsNullOrWhiteSpace(decryptedFilePath))
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_DecryptedFilePathError
                });
            }

            var destinationDirectory = Path.GetDirectoryName(decryptedFilePath);

            if (!Directory.Exists(destinationDirectory))
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_DestinationDirectoryNotFound} \"{destinationDirectory}\"."
                });
            }

            _key = key ?? _key;
            _IV  = IV ?? _IV;

            if (_key == null)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullKeyError
                });
            }

            if (_IV == null)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Decryption_NullIVError
                });
            }

            if (endPosition < startPosition)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = string.Format(MessageStrings.Decryption_EndPositionLessThanStartError, endPosition, startPosition)
                });
            }

            var pathsEqual = decryptedFilePath.Equals(encryptedFilePath, StringComparison.InvariantCultureIgnoreCase);

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    aesManaged.Key     = _key;
                    aesManaged.IV      = _IV;
                    aesManaged.Mode    = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var decryptedFs = File.Open((pathsEqual ? decryptedFilePath + "_tmpdecrypt" : decryptedFilePath), FileMode.Create, FileAccess.Write, FileShare.None))
                    {
                        using (var encryptedFs = File.Open(encryptedFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            encryptedFs.Position = startPosition;

                            using (var decryptor = aesManaged.CreateDecryptor(_key, _IV))
                            {
                                using (var cs = new CryptoStream(decryptedFs, decryptor, CryptoStreamMode.Write))
                                {
                                    //encrypted.CopyTo(cs);

                                    var  buffer            = new byte[kBbufferSize * 1024];
                                    var  totalBytesToRead  = ((endPosition == 0 ? encryptedFs.Length : endPosition) - startPosition);
                                    var  totalBytesNotRead = totalBytesToRead;
                                    long totalBytesRead    = 0;
                                    var  percentageDone    = 0;

                                    while (totalBytesNotRead > 0)
                                    {
                                        var bytesRead = encryptedFs.Read(buffer, 0, (int)Math.Min(buffer.Length, totalBytesNotRead));

                                        if (bytesRead > 0)
                                        {
                                            cs.Write(buffer, 0, bytesRead);

                                            totalBytesRead    += bytesRead;
                                            totalBytesNotRead -= bytesRead;
                                            var tmpPercentageDone = (int)(totalBytesRead * 100 / totalBytesToRead);

                                            if (tmpPercentageDone != percentageDone)
                                            {
                                                percentageDone = tmpPercentageDone;

                                                RaiseOnDecryptionProgress(percentageDone, (percentageDone != 100 ? $"Decrypting ({percentageDone}%)..." : $"Decrypted ({percentageDone}%)."));
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                if (pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                    File.Move(decryptedFilePath + "_tmpdecrypt", decryptedFilePath);
                }

                if (deleteEncryptedFile && !pathsEqual)
                {
                    CommonMethods.ClearFileAttributes(encryptedFilePath); // set "Normal" FileAttributes to avoid erros while trying to delete the file below
                    File.Delete(encryptedFilePath);
                }

                var message = string.Format(MessageStrings.Decryption_FileDecryptSuccess, encryptedFilePath, decryptedFilePath);
                message += (deleteEncryptedFile && !pathsEqual ? $"\n{string.Format(MessageStrings.Encryption_FileDeleted, encryptedFilePath)}" : "");

                return(new AesDecryptionResult()
                {
                    Success = true,
                    Message = message,
                    Key = _key,
                    IV = _IV,
                    AesCipherMode = (AesCipherMode)cipherMode,
                    PaddingMode = paddingMode
                });
            }
            catch (Exception ex)
            {
                return(new AesDecryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Decryption_ExceptionError}\n{ex.ToString()}"
                });
            }
        }
Ejemplo n.º 23
0
    //public byte[] ImageToByte(var img)
    //{
    //    ImageConverter converter = new ImageConverter();
    //    return (byte[])converter.ConvertTo(img, typeof(byte[]));
    //}

    protected void Button1_Click(object sender, EventArgs e)
    {
        //txtArt.Text = "49/02/657/17";
        //txtLabNum.Text = "1011805939";
        //txtArtSiteCode.Text = "159";

        //ARTNumber:49/02/657/17#LabNumber:1011805939#FacilityARTCode:159#

        QrCodeEncodingOptions options = new QrCodeEncodingOptions();

        options = new QrCodeEncodingOptions
        {
            DisableECI   = true,
            CharacterSet = "UTF-8",
            Width        = 250,
            Height       = 250,
        };
        var writer = new BarcodeWriter();

        writer.Format  = BarcodeFormat.QR_CODE;
        writer.Options = options;

        if (String.IsNullOrWhiteSpace(txtArt.Text) || String.IsNullOrEmpty(txtArt.Text))
        {
            Image1.ImageUrl = null;
            //MessageBox.Show("Text not found", "Oops!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            string str = string.Format("ARTNumber:{0}#LabNumber:{1}#FacilityARTCode:{2}",
                                       txtArt.Text.Trim(), txtLabNum.Text.Trim(), txtArtSiteCode.Text.Trim());

            //Ssymmetric encrypt
            //str = EncryptText(Encoding.UTF8.GetBytes(Encoding.UTF8.GetBytes(publicKey), str).ToString();
            //str = Crypto.RSA.Encrypt(str, publicKey, publicKey.Length);

            //Symmetric
            SymmetricAlgorithm aes = new AesManaged();
            //aes.Key = System.Text.Encoding.ASCII.GetBytes("LHrp5lJWt9LjIfpfDX1ppojT8lA4t0eS");
            aes.Key = System.Text.Encoding.ASCII.GetBytes("4WDbnOXpNiyzFcOOx0qpMftfeYS1xAxa");
            //str = EncryptText(aes, str).ToString();

            //string decryptedText = DecryptData(aes, Encoding.ASCII.GetBytes(str));

            var qr = new ZXing.BarcodeWriter();
            qr.Options = options;
            qr.Format  = ZXing.BarcodeFormat.QR_CODE;
            var result = new Bitmap(qr.Write(str));

            ImageConverter converter = new ImageConverter();
            byte[]         arr       = (byte[])converter.ConvertTo(result, typeof(byte[]));
            Image1.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(arr);
            //Image = (Image)result;
            //txtArt.Text = txtLabNum.Text = txtArtSiteCode.Text = string.Empty;
        }

        #region Symmetric
        //// Create a new instance of the AES algorithm
        //SymmetricAlgorithm aes = new AesManaged();

        //byte[] key = aes.Key; // Key propery contains the key of the aes algorithm you can create your own

        //Console.WriteLine("Enter your message here to encrypt:");
        //string message = Console.ReadLine();

        //// Call the encryptText method to encrypt the a string and save the result to a file
        //EncryptText(aes, message, "encryptedData.dat");

        //// Call the decryptData method to get the encrypted text from the file and print it
        ////Console.WriteLine("Decrypted message: {0}", DecryptData(aes, "encryptedData.dat"));
        //#endregion

        //#region Asymmetric
        //RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        //// Get the public keyy
        //string publicKey = rsa.ToXmlString(false); // false to get the public key
        //string privateKey = rsa.ToXmlString(true); // true to get the private key

        //// Call the encryptText method
        //EncryptText(publicKey, "Hello from C# Corner", "encryptedData.dat");

        // Call the decryptData method and print the result on the screen
        //Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));
        #endregion

        #region Asymmetric
        // Create an instance of the RSA algorithm class
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        // Get the public key
        //string publicKey = rsa.ToXmlString(false); // false to get the public key
        //string privateKey = rsa.ToXmlString(true); // true to get the private key

        //string publicKey = "<RSAKeyValue><Modulus>sDW7Ll/LHrp5lJWt9LjIfpfDX1ppojTelErotud4sAafaMg0pA4t0eSvE2+XTu83+tgHKDDUfc483DkGxfEoR1AJNs9utiHiKcRIN/YBk8suxQNJvpUg6oYrqtf5EYkC8+DzfbzAo7BCk7aGkElyNfefDu6oGSbiDZ4KE6RE+CU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        //string privateKey = "<RSAKeyValue><Modulus>sDW7Ll/LHrp5lJWt9LjIfpfDX1ppojTelErotud4sAafaMg0pA4t0eSvE2+XTu83+tgHKDDUfc483DkGxfEoR1AJNs9utiHiKcRIN/YBk8suxQNJvpUg6oYrqtf5EYkC8+DzfbzAo7BCk7aGkElyNfefDu6oGSbiDZ4KE6RE+CU=</Modulus><Exponent>AQAB</Exponent><P>4WDbnOXpNiyzFcOOx0qpMftfeYS1xAxarINJMXbepvbVKlvhZqJrbw/6TMLXAQhWxokTt1cH3SCKs/szwWc/9w==</P><Q>yCawUnlmATg4orOjs2FF6zHxTTv06FsCv14TpyvkYdzSzzPpNVFULXyUFiraQ+ehH3oUW9BKEXCQdq5CO9j5ww==</Q><DP>SwxUtM8+NCL4U1P2NFihNJqO9UkCudCfVPi2o7kAdTqWSu+jg+iru6TnZS4wKBDdzGiS3yck4DZY2YvZdRpriw==</DP><DQ>My3hbFVqhelQYho5Q8cdz9RHdY5dQ4TyIOj3cYnBrlx+80i820tekPsICtsOUMrL4nae+hM6vVbhOde5TABhbQ==</DQ><InverseQ>cNSU9f4ifrUKMRih3G8ZDwQSfjj9b9zNZuwWRDq4rAOTOac+2gb36yGAu4lzMkRm+kIH4KONJXhhkTx2bno1qg==</InverseQ><D>jEBIGxIt9uhPix9T1TwagQBEhinNeEkCfB/feG1mlxy+VsU7ePS8LZsKarrgQPiQovy9PZUYHIZB1LsjE/vtpPpxrNMoDy9GvlLjbKyNL0U8bQsdxBXxUkkBqXE5fcPzYUPsDBBoZIT31OeD/sZ07/hOEYLWzjqZ21BQL0tXsEU=</D></RSAKeyValue>";

        // Call the encryptText method
        //byte[] encryptedData = EncryptText(publicKey, "Hello from C# Corner");
        //string decryptedData = DecryptData(privateKey, encryptedData);

        // Call the decryptData method and print the result on the screen
        //Console.WriteLine("Decrypted message: {0}", DecryptData(privateKey, "encryptedData.dat"));
        #endregion
    }
Ejemplo n.º 24
0
        internal AesEncryptionResult EncryptWithMemoryStream(byte[] sourceData, byte[] key = null, byte[] IV = null, CipherMode cipherMode = CipherMode.CBC,
                                                             PaddingMode paddingMode       = PaddingMode.PKCS7)
        {
            if (sourceData == null || sourceData.Length == 0)
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    Message = MessageStrings.Encryption_InputRequired
                });
            }

            _key = key ?? _key;
            _IV  = IV ?? _IV;

            byte[] encryptedData = null;

            try
            {
                using (var aesManaged = new AesManaged())
                {
                    if (_key == null)
                    {
                        aesManaged.GenerateKey();
                        _key = aesManaged.Key;
                    }
                    else
                    {
                        if (aesManaged.ValidKeySize((_key.Length * 8)))
                        {
                            aesManaged.Key = _key;
                        }
                        else
                        {
                            return(new AesEncryptionResult()
                            {
                                Success = false,
                                Message = $"{MessageStrings.Common_InvalidKeySizeError} ({(_key.Length * 8)})."
                            });
                        }
                    }

                    if (_IV == null)
                    {
                        aesManaged.GenerateIV();
                        _IV = aesManaged.IV;
                    }
                    else
                    {
                        aesManaged.IV = _IV;
                    }

                    aesManaged.Mode    = cipherMode;
                    aesManaged.Padding = paddingMode;

                    using (var encryptor = aesManaged.CreateEncryptor(_key, _IV))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
                            {
                                using (var bw = new BinaryWriter(cs))
                                {
                                    bw.Write(sourceData);
                                }
                            }

                            encryptedData = ms.ToArray();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(new AesEncryptionResult()
                {
                    Success = false,
                    Message = $"{MessageStrings.Encryption_ExceptionError}\n{ex.ToString()}"
                });
            }

            return(new AesEncryptionResult()
            {
                Success = true,
                Message = MessageStrings.Encryption_EncryptSuccess,
                EncryptedDataBytes = encryptedData,
                EncryptedDataBase64String = Convert.ToBase64String(encryptedData),
                Key = _key,
                IV = _IV,
                AesCipherMode = (AesCipherMode)cipherMode,
                PaddingMode = paddingMode
            });
        }
Ejemplo n.º 25
0
 public EncrptHandler()
 {
     this.aesM = new AesManaged();
 }
Ejemplo n.º 26
0
 public void CBC_Allowed()
 {
     using (var aes = new AesManaged()) {
         aes.Mode = CipherMode.CBC;
     }
 }
Ejemplo n.º 27
0
        /// <summary>対称アルゴリズム暗号化サービスプロバイダ生成</summary>
        /// <param name="esa">EnumSymmetricAlgorithm</param>
        /// <param name="cm">CipherMode</param>
        /// <param name="pm">PaddingMode</param>
        /// <returns>SymmetricAlgorithm</returns>
        private SymmetricAlgorithm CreateSymmetricAlgorithm(EnumSymmetricAlgorithm esa, CipherMode cm, PaddingMode pm)
        {
            #region Constructor
            SymmetricAlgorithm sa = null;

            #region Aes
            if (esa.HasFlag(EnumSymmetricAlgorithm.AES_CSP))
            {
                // AesCryptoServiceProviderサービスプロバイダ
                sa = AesCryptoServiceProvider.Create(); // devps(1703)
            }
            else if (esa.HasFlag(EnumSymmetricAlgorithm.AES_M))
            {
                // AesManagedサービスプロバイダ
                sa = AesManaged.Create(); // devps(1703)
            }
#if NET45 || NET46
#else
            else if (esa.HasFlag(EnumSymmetricAlgorithm.AES_CNG))
            {
                // AesCngサービスプロバイダ
                sa = AesCng.Create(); // devps(1703)
            }
#endif
            #endregion

            #region TripleDES
            else if (esa.HasFlag(EnumSymmetricAlgorithm.TDES_CSP))
            {
                // TripleDESCryptoServiceProviderサービスプロバイダ
                sa = TripleDESCryptoServiceProvider.Create(); // devps(1703)
            }

#if NET45 || NET46
#else
            else if (esa.HasFlag(EnumSymmetricAlgorithm.TDES_CNG))
            {
                // TripleDESCngサービスプロバイダ
                sa = TripleDESCng.Create(); // devps(1703)
            }
#endif
            #endregion

            #region Others
            else if (esa.HasFlag(EnumSymmetricAlgorithm.DES_CSP))
            {
                // DESCryptoServiceProviderサービスプロバイダ
                sa = DESCryptoServiceProvider.Create(); // devps(1703)
            }

            else if (esa.HasFlag(EnumSymmetricAlgorithm.RC2_CSP))
            {
                // RC2CryptoServiceProviderサービスプロバイダ
                sa = RC2CryptoServiceProvider.Create(); // devps(1703)
            }

            else if (esa.HasFlag(EnumSymmetricAlgorithm.Rijndael_M))
            {
                // RijndaelManagedサービスプロバイダ
                sa = RijndaelManaged.Create(); // devps(1703)
            }
            #endregion

            else
            {
                throw new ArgumentException(
                          PublicExceptionMessage.ARGUMENT_INCORRECT, "EnumSymmetricAlgorithm esa");
            }
            #endregion

            #region Options
            // cmが設定されている場合。
            if (cm != 0)
            {
                sa.Mode = cm;
            }

            // pmが設定されている場合。
            if (pm != 0)
            {
                sa.Padding = pm;
            }
            #endregion

            return(sa);
        }
Ejemplo n.º 28
0
 public void ECB_Allowed()
 {
     using (var aes = new AesManaged()) {
         aes.Mode = CipherMode.ECB;
     }
 }
        /// <summary>
        /// Simple Encryption(AES) then Authentication (HMAC) for a UTF8 Message.
        /// </summary>
        /// <param name="secretMessage">The secret message.</param>
        /// <param name="cryptKey">The crypt key.</param>
        /// <param name="authKey">The auth key.</param>
        /// <param name="nonSecretPayload">(Optional) Non-Secret Payload.</param>
        /// <returns>
        /// Encrypted Message
        /// </returns>
        /// <remarks>
        /// Adds overhead of (Optional-Payload + BlockSize(16) + Message-Padded-To-Blocksize +  HMac-Tag(32)) * 1.33 Base64
        /// </remarks>
        public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] cryptKey, byte[] authKey, byte[] nonSecretPayload = null)
        {
            //User Error Checks
            if (cryptKey == null || cryptKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "cryptKey");
            }

            if (authKey == null || authKey.Length != KeyBitSize / 8)
            {
                throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "authKey");
            }

            if (secretMessage == null || secretMessage.Length < 1)
            {
                throw new ArgumentException("Secret Message Required!", "secretMessage");
            }

            //non-secret payload optional
            nonSecretPayload = nonSecretPayload ?? new byte[] { };

            byte[] cipherText;
            byte[] iv;

            using (var aes = new AesManaged
            {
                KeySize = KeyBitSize,
                BlockSize = BlockBitSize,
                Mode = CipherMode.CBC,
                Padding = PaddingMode.PKCS7
            })
            {
                //Use random IV
                aes.GenerateIV();
                iv = aes.IV;

                using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                    using (var cipherStream = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var binaryWriter = new BinaryWriter(cryptoStream))
                            {
                                //Encrypt Data
                                binaryWriter.Write(secretMessage);
                            }

                        cipherText = cipherStream.ToArray();
                    }
            }

            //Assemble encrypted message and add authentication
            using (var hmac = new HMACSHA256(authKey))
                using (var encryptedStream = new MemoryStream())
                {
                    using (var binaryWriter = new BinaryWriter(encryptedStream))
                    {
                        //Prepend non-secret payload if any
                        binaryWriter.Write(nonSecretPayload);
                        //Prepend IV
                        binaryWriter.Write(iv);
                        //Write Ciphertext
                        binaryWriter.Write(cipherText);
                        binaryWriter.Flush();

                        //Authenticate all data
                        var tag = hmac.ComputeHash(encryptedStream.ToArray());
                        //Postpend tag
                        binaryWriter.Write(tag);
                    }
                    return(encryptedStream.ToArray());
                }
        }
Ejemplo n.º 30
0
    public void ImportFile()
    {
        extensions = new string[] { "ced" };
        var filePath = FileBrowser.OpenSingleFile("Open case file", Application.persistentDataPath, extensions);

        if (string.IsNullOrWhiteSpace(filePath))
        {
            GlobalData.fileName = "[Import] Canceled";
            Debug.Log("[Import] Canceled");
            Cursor.visible = false;
            return;
        }

        XmlDocument xmlDoc = new XmlDocument();

        try {
            string s = File.ReadAllText(filePath);
            print(s);
            xmlDoc.LoadXml(s); //This loads the locally saved file
        } catch (Exception) {
            string           text    = "";
            AesManaged       aes     = new AesManaged();
            ICryptoTransform decrypt = aes.CreateDecryptor(Encoding.UTF8.GetBytes(GlobalData.encryptionKey), Encoding.UTF8.GetBytes(GlobalData.encryptionIV));
            using (FileStream fs = new FileStream(filePath, FileMode.Open)) {
                using (CryptoStream cs = new CryptoStream(fs, decrypt, CryptoStreamMode.Read)) {
                    using (StreamReader sr = new StreamReader(cs)) {
                        text = sr.ReadToEnd();
                    }
                }
            }
            //xmlDoc.LoadXml(DecryptStringFromBytes_Aes(GetBytesFromHex(s)));
            try {
                xmlDoc.LoadXml(text);
            } catch (XmlException xmlError) {
                Debug.LogWarning(xmlError.Message);
                return;
            }
        }

        XmlDocument subXmlDoc = new XmlDocument();

        subXmlDoc.LoadXml(xmlDoc.DocumentElement.ChildNodes[0].OuterXml);
        string menuText = subXmlDoc.GetElementsByTagName("menu")[0].InnerText;

        string[] menuSplit = menuText.Split(new string[] { "--" }, StringSplitOptions.None);
        menuSplit[0] = GlobalData.accountId.ToString();
        menuSplit[1] = "[CHECKFORDUPLICATE]" + menuSplit[1];
        bool addCase = true;

        if (File.Exists(GameObject.Find("GaudyBG").GetComponent <ServerControls>().GetLocalSavesFolderPath() + menuSplit[1]))
        {
            addCase = false;
        }
        //Change the record number to avoid local conflicts or maybe remove that check for the menu
        menuText = string.Join("--", menuSplit);
        MenuCase m = new MenuCase(menuSplit);
        string   savePathNoExtension = GameObject.Find("GaudyBG").GetComponent <ServerControls>().GetLocalSavesFolderPath() + m.filename.Remove(m.filename.Length - ".ced".Length);

        //Save local menu preview
        File.WriteAllText(savePathNoExtension + " menu.txt", menuText);
        //Save .ced
        File.WriteAllBytes(savePathNoExtension + ".ced", EncryptStringToBytes_Aes(xmlDoc.DocumentElement.ChildNodes[1].OuterXml));
        //Save .cei
        File.WriteAllBytes(savePathNoExtension + ".cei", EncryptStringToBytes_Aes(xmlDoc.DocumentElement.ChildNodes[2].OuterXml));

        if (addCase)
        {
            GameObject.Find("GaudyBG").GetComponent <ServerControls>().AddCase(m, true);
        }
        else
        {
            GameObject.Find("GaudyBG").GetComponent <LoginManager>().ShowMessage("Reimported case");
        }
    }
Ejemplo n.º 31
0
        public void PreAuthenticate(IRequest req, IResponse res)
        {
            if (req.OperationName != null && IgnoreForOperationTypes.Contains(req.OperationName))
            {
                return;
            }

            var bearerToken = req.GetBearerToken()
                              ?? req.GetCookieValue(Keywords.TokenCookie);

            if (bearerToken != null)
            {
                var parts = bearerToken.Split('.');
                if (parts.Length == 3)
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    var header         = parts[0];
                    var payload        = parts[1];
                    var signatureBytes = parts[2].FromBase64UrlSafe();

                    var headerJson   = header.FromBase64UrlSafe().FromUtf8Bytes();
                    var payloadBytes = payload.FromBase64UrlSafe();

                    var headerData = headerJson.FromJson <Dictionary <string, string> >();

                    var bytesToSign = string.Concat(header, ".", payload).ToUtf8Bytes();

                    var algorithm = headerData["alg"];

                    //Potential Security Risk for relying on user-specified algorithm: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
                    if (RequireHashAlgorithm && algorithm != HashAlgorithm)
                    {
                        throw new NotSupportedException("Invalid algoritm '{0}', expected '{1}'".Fmt(algorithm, HashAlgorithm));
                    }

                    if (!VerifyPayload(algorithm, bytesToSign, signatureBytes))
                    {
                        return;
                    }

                    var payloadJson = payloadBytes.FromUtf8Bytes();
                    var jwtPayload  = JsonObject.Parse(payloadJson);

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
                else if (parts.Length == 5) //Encrypted JWE Token
                {
                    if (RequireSecureConnection && !req.IsSecureConnection)
                    {
                        throw HttpError.Forbidden(ErrorMessages.JwtRequiresSecureConnection);
                    }

                    if (PrivateKey == null || PublicKey == null)
                    {
                        throw new NotSupportedException("PrivateKey is required to DecryptPayload");
                    }

                    var jweHeaderBase64Url  = parts[0];
                    var jweEncKeyBase64Url  = parts[1];
                    var ivBase64Url         = parts[2];
                    var cipherTextBase64Url = parts[3];
                    var tagBase64Url        = parts[4];

                    var sentTag    = tagBase64Url.FromBase64UrlSafe();
                    var aadBytes   = (jweHeaderBase64Url + "." + jweEncKeyBase64Url).ToUtf8Bytes();
                    var iv         = ivBase64Url.FromBase64UrlSafe();
                    var cipherText = cipherTextBase64Url.FromBase64UrlSafe();

                    var jweEncKey        = jweEncKeyBase64Url.FromBase64UrlSafe();
                    var cryptAuthKeys256 = RsaUtils.Decrypt(jweEncKey, PrivateKey.Value, UseRsaKeyLength);

                    var authKey  = new byte[128 / 8];
                    var cryptKey = new byte[128 / 8];
                    Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
                    Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

                    using (var hmac = new HMACSHA256(authKey))
                        using (var encryptedStream = new MemoryStream())
                        {
                            using (var writer = new BinaryWriter(encryptedStream))
                            {
                                writer.Write(aadBytes);
                                writer.Write(iv);
                                writer.Write(cipherText);
                                writer.Flush();

                                var calcTag = hmac.ComputeHash(encryptedStream.ToArray());

                                if (!calcTag.EquivalentTo(sentTag))
                                {
                                    return;
                                }
                            }
                        }

                    JsonObject jwtPayload;
                    using (var aes = new AesManaged
                    {
                        KeySize = 128,
                        BlockSize = 128,
                        Mode = CipherMode.CBC,
                        Padding = PaddingMode.PKCS7
                    })
                        using (var decryptor = aes.CreateDecryptor(cryptKey, iv))
                            using (var ms = MemoryStreamFactory.GetStream(cipherText))
                                using (var cryptStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                                {
                                    var jwtPayloadBytes = cryptStream.ReadFully();
                                    jwtPayload = JsonObject.Parse(jwtPayloadBytes.FromUtf8Bytes());
                                }

                    var session = CreateSessionFromPayload(req, jwtPayload);
                    req.Items[Keywords.Session] = session;
                }
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Initializes the Security Manager by attempting to decrypt the keyFile
        /// </summary>
        /// <param name="keyFileLocation">Location of the keyFile</param>
        /// <param name="key">supplied encryption key (Base64) given at program start</param>
        /// <param name="iv">supplied encryption iv (Base64) given at program start</param>
        /// <param name="userFileLocation">Location of the userFile encrypted by keyFile</param>
        /// <param name="emailUserFileLocation">Location of the userFile for the email sender, also encrypted by keyFile</param>
        /// <exception cref="DecryptionException">Throws if @keyFileLocation cannot be decrypted</exception>
        /// <exception cref="IOException">Throws if @keyFileLocation cannot be read</exception>
        public SecurityManager(string keyFileLocation, string key, string iv, string userFileLocation, string emailUserFileLocation)
        {
            if (key == null || iv == null || keyFileLocation == null || userFileLocation == null || emailUserFileLocation == null)
            {
                throw new ArgumentNullException();
            }

            if (!File.Exists(keyFileLocation))
            {
                throw new FileNotFoundException("keyFile not found");
            }
            if (!File.Exists(userFileLocation))
            {
                throw new FileNotFoundException("userFile not found");
            }
            if (!isValidLength(key) || !isValidLength(iv))
            {
                throw new ArgumentException("Either Key or IV is an improper length");
            }
            string keyFileENC = keyFileENC = File.ReadAllText(keyFileLocation);             //Encrypted base64

            string[] keyLines = null;
            var      aes      = new AesManaged();

            try {
                //Try to decrypt keyFile
                aes.Key     = Convert.FromBase64String(key);
                aes.IV      = Convert.FromBase64String(iv);
                aes.Padding = PaddingMode.Zeros;
                aes.Mode    = CipherMode.CBC;
                var    decryptor = aes.CreateDecryptor();
                var    cipher    = Convert.FromBase64String(keyFileENC);
                string plaintext = encoder.GetString(decryptor.TransformFinalBlock(cipher, 0, cipher.Length));
                keyLines  = plaintext.Split('\n');
                plaintext = null;
            }
            catch {
                throw new DecryptionException();
            }
            if (keyLines != null)
            {
                if (isValidKeyFile(keyLines))
                {
                    for (int i = 0; i < keyLines.Length; i++)
                    {
                        if (i == 0 || i == keyLines.Length - 1)
                        {
                            continue;
                        }
                        string[] keyValuePair = keyLines[i].Split('=');
                        if (keyValuePair[0] == "iv")
                        {
                            string fixIv = string.Empty;
                            for (int x = 1; x < keyValuePair.Length; x++)
                            {
                                if (keyValuePair[x] == "")
                                {
                                    fixIv = fixIv + '=';
                                }
                                else
                                {
                                    fixIv = fixIv + keyValuePair[x];
                                }
                            }
                            this.iv = fixIv;
                        }
                        if (keyValuePair[0] == "key")
                        {
                            string fixKey = String.Empty;
                            for (int x = 1; x < keyValuePair.Length; x++)
                            {
                                if (keyValuePair[x] == "")
                                {
                                    fixKey = fixKey + '=';
                                }
                                else
                                {
                                    fixKey = fixKey + keyValuePair[1];
                                }
                            }
                            this.key = fixKey;
                        }
                    }
                }
                else
                {
                    throw new Exception("Either Decrypted an invalid keyfile or supplied key/iv is wrong");
                }
                keyLines     = null;                //Destroy
                aes.IV       = Convert.FromBase64String(this.iv);
                aes.Key      = Convert.FromBase64String(this.key);
                this.aes     = aes;                 //store AES Object
                this.aes.IV  = Convert.FromBase64String(this.iv);
                this.aes.Key = Convert.FromBase64String(this.key);

                //Create UserManager with supplied userFileLocation and decrypted keyFile
                string[] userLines;
                try {
                    string userFileENC = File.ReadAllText(userFileLocation);
                    var    decryptor   = this.aes.CreateDecryptor();
                    var    cipher      = Convert.FromBase64String(userFileENC);
                    string plaintext   = encoder.GetString(decryptor.TransformFinalBlock(cipher, 0, cipher.Length));
                    userLines   = plaintext.Split('\n');
                    plaintext   = null;
                    userFileENC = null;
                }
                catch {
                    throw new DecryptionException();
                }
                try {
                    int  securityValue = -1;
                    User defaultUser   = User.parseUserFile(userLines, out securityValue);
                    this.userManager = new UserManager(defaultUser, securityValue, this);
                    keyLines         = null;

                    /*User defaultUser = new User(name, pass, email, out securityValue);
                     * this.userManager = new UserManager(defaultUser, securityValue, this);*/
                }
                catch {
                    throw new Exception("Either Decrypted an invalid userFile or keyFile contains incorrect key/iv");
                }

                /*if (isValidUserFile(userLines)) {
                 *  string name = null, email = null, pass = null;
                 *  foreach (string line in userLines) {
                 *      string[] split = line.Split('=');
                 *      if (split[0].Trim() == "username") {
                 *          name = split[1].Trim();
                 *      }
                 *      else if (split[0].Trim() == "email") {
                 *          email = split[1].Trim();
                 *      }
                 *      else if (split[0].Trim() == "pass") {
                 *          pass = split[1].Trim();
                 *      }
                 *  }
                 *  int securityValue = 0;
                 *  User defaultUser = new User(name, pass, email, out securityValue);
                 *  this.userManager = new UserManager(defaultUser, securityValue, this);
                 *
                 *  //Try and destroy any remaining data
                 *  name = null;
                 *  email = null;
                 *  pass = null;
                 *  securityValue = int.MinValue;
                 *  keyLines = null;
                 *  keyFileENC = null;
                 * }
                 * else {
                 *  throw new Exception("Either Decrypted an invalid userFile or keyFile contains incorrect key/iv");
                 * }*/
                //Create the mailer Object
                //read userFile
                string[] emailLines;
                try {
                    string emailENC  = File.ReadAllText(emailUserFileLocation);
                    var    decryptor = this.aes.CreateDecryptor();
                    var    cipher    = Convert.FromBase64String(emailENC);
                    string plaintext = encoder.GetString(decryptor.TransformFinalBlock(cipher, 0, cipher.Length));
                    emailLines = plaintext.Split('\n');
                    plaintext  = null;
                    emailENC   = null;
                }
                catch {
                    throw new DecryptionException();
                }
                int  mailSecValue = -1;
                User mailUser     = User.parseUserFile(emailLines, out mailSecValue);

                /*if (isValidUserFile(emailLines)) {
                 *  string name = null, email = null, pass = null;
                 *  foreach (string line in userLines) {
                 *      string[] split = line.Split('=');
                 *      if (split[0].Trim() == "username") {
                 *          name = split[1].Trim();
                 *      }
                 *      else if (split[0].Trim() == "email") {
                 *          email = split[1].Trim();
                 *      }
                 *      else if (split[0].Trim() == "pass") {
                 *          pass = split[1].Trim();
                 *      }
                 *  }
                 *  int securityValue = 0;
                 *  User defaultUser = new User(name, pass, email, out securityValue);
                 *  this.userManager = new UserManager(defaultUser, securityValue, this);
                 *
                 *  //Try and destroy any remaining data
                 *  name = null;
                 *  email = null;
                 *  pass = null;
                 *  securityValue = int.MinValue;
                 *  keyLines = null;
                 *  keyFileENC = null;
                 * }*/
                //destroy sensitive info
                emailLines = null;

                this.mailer = new Mailer(mailUser, mailSecValue);
            }
            else
            {
                throw new DecryptionException();
            }
        }
Ejemplo n.º 33
0
        static void Main(string[] args)
        {
#if !DEBUG
            if (args.Length < 1)
            {
                Console.WriteLine("FARC Pack");
                Console.WriteLine("=========");
                Console.WriteLine("Packer/unpacker for .FARC files.\n");
                Console.WriteLine("Usage:");
                Console.WriteLine("    FarcPack [options] [source] [destination]");
                Console.WriteLine("    Source can be either FARC or directory.");
                Console.WriteLine("    Destination can be left empty.\n");
                Console.WriteLine("Options:");
                Console.WriteLine("    -a, -alignment         Set alignment for output FARC.");
                Console.WriteLine("                           16 by default.\n");
                Console.WriteLine("    -c, --compress         Compress files in output FARC.");
                Console.WriteLine("                           Disabled by default.");
                Console.ReadLine();
                return;
            }
#endif
            string sourcePath      = null;
            string destinationPath = null;

            bool compress  = false;
            uint alignment = 16;

            for (int i = 0; i < args.Length; i++)
            {
                string arg = args[i];

                Func <string, string, bool> compare = (a, b) => arg.Equals(a, StringComparison.OrdinalIgnoreCase) || arg.Equals(b, StringComparison.OrdinalIgnoreCase);
                alignment = compare("-a", "-alignment") ? uint.Parse(args[++i]) : alignment;

                compress = compare("-c", "-compress") || compress;

                if (sourcePath == null && !compare("-c", "-compress") && !compare("-a", "-alignment"))
                {
                    sourcePath = arg;
                }


                else if (destinationPath == null && !compare("-c", "-compress") && !compare("-a", "-alignment"))
                {
                    destinationPath = arg;
                }
            }

#if DEBUG
            sourcePath = @"C:\Users\waelw.WAELS-PC\Desktop\farc\vr_cmn";
#endif

            if (sourcePath == null)
            {
                throw new ArgumentException("You must provide a source.", nameof(sourcePath));
            }

            var serial = new BinarySerializer();

            if (sourcePath.EndsWith(".farc", StringComparison.OrdinalIgnoreCase))
            {
                destinationPath = destinationPath ?? Path.ChangeExtension(sourcePath, null);
#if USE_NEW
                var archive = new FarcArchiveBin();
                using (var file = File.Open(sourcePath, FileMode.Open))
                {
                    archive = serial.Deserialize <FarcArchiveBin>(file);
                    archive.Unpack(destinationPath);
                }
#else
                var archive = new FarcArchive();
                archive.Load(sourcePath);

                using (Stream source = File.OpenRead(sourcePath))
                {
                    foreach (var entry in archive)
                    {
                        using (Stream entrySource = new SubStream(source, entry.Position, entry.Length))
                            using (Stream destination = File.Create(Path.Combine(destinationPath, entry.FileName)))
                            {
                                if (archive.IsEncrypted)
                                {
                                    using (AesManaged aes = new AesManaged
                                    {
                                        KeySize = 128,
                                        Key = FarcArchive.FarcEncryptionKeyBytes,
                                        BlockSize = 128,
                                        Mode = CipherMode.ECB,
                                        Padding = PaddingMode.Zeros,
                                        IV = new byte[16],
                                    })
                                        using (CryptoStream cryptoStream = new CryptoStream(
                                                   entrySource,
                                                   aes.CreateDecryptor(),
                                                   CryptoStreamMode.Read))
                                        {
                                            if (archive.IsCompressed && entry.Length != entry.CompressedLength)
                                            {
                                                using (GZipStream gzipStream = new GZipStream(cryptoStream, CompressionMode.Decompress))
                                                {
                                                    gzipStream.CopyTo(destination);
                                                }
                                            }

                                            else
                                            {
                                                cryptoStream.CopyTo(destination);
                                            }
                                        }
                                }

                                else if (archive.IsCompressed && entry.Length != entry.CompressedLength)
                                {
                                    using (GZipStream gzipStream = new GZipStream(entrySource, CompressionMode.Decompress))
                                    {
                                        gzipStream.CopyTo(destination);
                                    }
                                }

                                else
                                {
                                    entrySource.CopyTo(destination);
                                }
                            }
                    }
                }
#endif
            }

            else if (File.GetAttributes(sourcePath).HasFlag(FileAttributes.Directory))
            {
#if USE_NEW
                var archive = new FarcArchiveBin();
                archive.Alignment = (int)alignment;
#else
                var archive = new FarcArchive();
                archive.Alignment = alignment;
#endif
                archive.IsCompressed = compress;
#if DEBUG
                archive.Alignment = 64;
#endif
                destinationPath = destinationPath ?? sourcePath + ".farc";

                foreach (string fileName in Directory.GetFiles(sourcePath))
                {
#if USE_NEW
                    archive.Add(new FarcEntryBin(fileName));
#else
                    archive.Add(new FarcEntry
                    {
                        FileName = Path.GetFileName(fileName),
                        FilePath = new FileInfo(fileName)
                    });
#endif
                }

#if USE_NEW
                archive.Flush();
                using (var save = File.Create(destinationPath))
                {
                    serial.Serialize(save, archive);
                }
#else
                archive.Save(destinationPath);
#endif
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// 文字列を複合化します。
        /// </summary>
        /// <param name="data">複合化する文字列</param>
        /// <param name="password">パスワード</param>
        /// <returns>複合化した文字列</returns>
        /// <exception cref="ArgumentException">複合化する文字が空 or 先頭にsaltとIVが含まれていない or 複合化に失敗</exception>
        public static string DecryptString(string data, string password)
        {
            // 入力チェック (空チェック)
            if (String.IsNullOrWhiteSpace(data))
            {
                throw new ArgumentException("複合化する文字が空です。");
            }

            // 複合化する文字をbyte配列に変換する。
            var bytes = System.Convert.FromBase64String(data);

            // 入力チェック (レングスチェック)
            if (bytes.Length < 16 * 2)
            {
                throw new ArgumentException("複合化する文字はアルゴリズムの条件を満たしていません。");
            }

            // 引数のデータからsaltとIV、複合化する文字列を取得する。
            var salt     = bytes.Take(16).ToArray();
            var IV       = bytes.Skip(16).Take(16).ToArray();
            var byteData = bytes.Skip(16 * 2).ToArray();

            // 複合に用いるICryptoTransformを生成するブロック
            using (AesManaged aes = new AesManaged())
            {
                aes.BlockSize = 128;                // BlockSize = 16bytes
                aes.KeySize   = 128;                // KeySize = 16bytes
                aes.Mode      = CipherMode.CBC;     // CBC mode
                aes.Padding   = PaddingMode.PKCS7;  // Padding mode is "PKCS7".

                //入力されたパスワードをベースに擬似乱数を新たに生成
                Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, salt);

                // 生成した擬似乱数から16バイト切り出したデータをパスワードにする
                byte[] bufferKey = deriveBytes.GetBytes(16);

                // AESにキーとIVを設定する。
                aes.Key = bufferKey;
                aes.IV  = IV;

                // 複合処理用インスタンスを生成し、文字列を複合化する
                using (ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                {
                    // byte配列を暗号化→文字列に変換して返却
                    string decryptString = null;

                    try
                    {
                        decryptString = System.Text.Encoding.UTF8.GetString(decryptor.TransformFinalBlock(byteData, 0, byteData.Length));
                    }
                    catch (Exception ex)
                    {
                        // 複合化で例外が発生する→パスワードが異なる。
                        throw new ArgumentException("パスワードが違います。", ex);
                    }

                    // saltとIV、複合化した文字を取得する。
                    var decryptSalt = String.Concat(decryptString.Take(24));
                    var decryptIV   = String.Concat(decryptString.Skip(24).Take(24));
                    var decryptData = String.Concat(decryptString.Skip(24 * 2));

                    // 入力チェック (複合化した文字内に含まれるsaltとIVが生のsaltとIVと一致しない)
                    if (!salt.SequenceEqual(System.Convert.FromBase64String(decryptSalt)) ||
                        !IV.SequenceEqual(System.Convert.FromBase64String(decryptIV)))
                    {
                        throw new ArgumentException("パスワードが違います。");
                    }

                    // 結果を返却
                    return(decryptData);
                }
            }
        }
Ejemplo n.º 35
0
        static void Main(string[] args)
        {
            if (args.Length >= 2)
            {
                try
                {
                    var file_bytes = File.ReadAllBytes(args[1]);

                    switch (args[0])
                    {
                    case "hash_sha512":
                        var hash_file = HashAlgorithmSHA512.HashArray(file_bytes);
                        File.WriteAllBytes(args[0] + "_file", hash_file);
                        break;

                    case "aes":
                        if (args.Length == 4)
                        {
                            var key_bytes        = File.ReadAllBytes(args[2]);
                            var iv_bytes         = File.ReadAllBytes(args[3]);
                            var decr_by_aes_file = SymmetricAlgorithmAES.DecryptData(file_bytes, key_bytes, iv_bytes);
                            File.WriteAllBytes(args[0] + "_file", decr_by_aes_file);
                        }
                        else
                        {
                            using (var myAes = new AesManaged())
                            {
                                myAes.GenerateKey();
                                myAes.GenerateIV();
                                var encr_by_aes_file = SymmetricAlgorithmAES.EncryptData(file_bytes, myAes.Key, myAes.IV);
                                File.WriteAllBytes(args[0] + "_file", encr_by_aes_file);
                                File.WriteAllBytes(args[0] + "_key", myAes.Key);
                                File.WriteAllBytes(args[0] + "_iv", myAes.IV);
                            }
                        }
                        break;

                    case "rsa":
                        if (args.Length == 3)
                        {
                            string xml_string       = File.ReadLines(args[2]).Skip(0).First();
                            var    decr_by_rsa_file = AsymmetricAlgorithmRSA.DecryptData(file_bytes, xml_string);
                            File.WriteAllBytes(args[0] + "_file", decr_by_rsa_file);
                        }
                        else
                        {
                            using (var RSA = new RSACryptoServiceProvider())
                            {
                                string xml_string       = RSA.ToXmlString(true);
                                var    encr_by_rsa_file = AsymmetricAlgorithmRSA.EncryptData(file_bytes, xml_string);
                                File.WriteAllBytes(args[0] + "_file", encr_by_rsa_file);
                                File.WriteAllText(args[0] + "_xml_string", xml_string);
                            }
                        }
                        break;

                    default:
                        break;
                    }
                }
                catch (IOException e)
                {
                    Console.WriteLine("Error: File not found", e);
                }
            }
        }
Ejemplo n.º 36
0
        /// <summary>
        /// Use this constructor to perform encryption/decryption with custom options.
        /// See AESCryptOptions documentation for details.
        /// </summary>
        /// <param name="passPhrase">
        /// Passphrase (in string format) from which a pseudo-random password will be derived. The derived password will be used to generate the encryption key.
        /// </param>
        /// <param name="initVector">
        /// Initialization vector (IV). This value is required to encrypt the first block of plaintext data. IV must be exactly 16 ASCII characters long.
        /// </param>
        /// <param name="options">
        /// A set of customized (or default) options to use for the encryption/decryption: see AESCryptOptions documentation for details.
        /// </param>
        public AESCrypt(string passPhrase, string initVector, AESCryptOptions options)
        {
            // store the options object locally.
            this.Options = options;

            // Checks for the correct (or null) size of cryptographic key.
            if (Options.FixedKeySize.HasValue &&
                Options.FixedKeySize != 128 &&
                Options.FixedKeySize != 192 &&
                Options.FixedKeySize != 256)
            {
                throw new NotSupportedException("ERROR: options.FixedKeySize must be NULL (for auto-detect) or have a value of 128, 192 or 256");
            }

            // Initialization vector converted to a byte array.
            byte[] initVectorBytes = null;

            // Salt used for password hashing (to generate the key, not during
            // encryption) converted to a byte array.
            byte[] saltValueBytes = null;

            // Get bytes of initialization vector.
            if (initVector == null)
            {
                initVectorBytes = new byte[0];
            }
            else
            {
                initVectorBytes = Encoding.UTF8.GetBytes(initVector);
            }

            // Gets the KeySize
            int keySize = (Options.FixedKeySize.HasValue)
                ? Options.FixedKeySize.Value
                : GetAESKeySize(passPhrase);

            // Get bytes of password (hashing it or not)
            byte[] keyBytes = null;
            if (Options.PasswordHash == AESPasswordHash.None)
            {
                // Convert passPhrase to a byte array
                keyBytes = System.Text.Encoding.UTF8.GetBytes(passPhrase);
            }
            else
            {
                // Get bytes of password hash salt
                if (Options.PasswordHashSalt == null)
                {
                    saltValueBytes = new byte[0];
                }
                else
                {
                    saltValueBytes = Encoding.UTF8.GetBytes(options.PasswordHashSalt);
                }

                // Generate password, which will be used to derive the key.
                PasswordDeriveBytes password = new PasswordDeriveBytes(
                    passPhrase,
                    saltValueBytes,
                    Options.PasswordHash.ToString().ToUpper().Replace("-", ""),
                    Options.PasswordHashIterations);

                // Convert key to a byte array adjusting the size from bits to bytes.
                keyBytes = password.GetBytes(keySize / 8);
            }

            // Initialize AES key object.
            AesManaged symmetricKey = new AesManaged();

            // Sets the padding mode
            symmetricKey.Padding = Options.PaddingMode;

            // Use the unsafe ECB cypher mode (not recommended) if no IV has been provided, otherwise use the more secure CBC mode.
            symmetricKey.Mode = (initVectorBytes.Length == 0)
                ? CipherMode.ECB
                : CipherMode.CBC;

            // Create the encryptor and decryptor objects, which we will use for cryptographic operations.
            encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
            decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        }
Ejemplo n.º 37
0
    public Aes128CounterMode(byte[] counter)
    {
        if (counter == null) throw new ArgumentNullException("counter");
        if (counter.Length != 16)
            throw new ArgumentException(String.Format("Counter size must be same as block size (actual: {0}, expected: {1})",
                counter.Length, 16));

        _aes = new AesManaged
        {
            Mode = CipherMode.ECB,
            Padding = PaddingMode.None
        };

        _counter = counter;
    }
Ejemplo n.º 38
0
 public void SetSecret( byte[] buffer )
 {
     aes = new AesManaged();
     aes.Key = buffer;
     aes.IV = buffer;
 }