public static string DecryptPrivateKey(byte[] content, byte[] password) { var _initialVector = new byte[8]; Array.Copy(content, 0, _initialVector, 0, 8); byte[] decrypted; var decryptedByteCount = 0; using (var tripleDES = TripleDES.Create()) { tripleDES.Key = password; tripleDES.IV = _initialVector; tripleDES.Mode = CipherMode.ECB; tripleDES.CreateEncryptor(tripleDES.Key, tripleDES.IV); try { using (var decryptor = tripleDES.CreateDecryptor(tripleDES.Key, tripleDES.IV)) using (var from = new MemoryStream(content)) { from.Read(_initialVector, 0, 8); using (var reader = new CryptoStream(from, decryptor, CryptoStreamMode.Read)) { decrypted = new byte[content.Length]; decryptedByteCount = reader.Read(decrypted, 0, decrypted.Length); } } } catch (Exception e) { return(String.Empty); } tripleDES.Clear(); } return(Encoding.UTF8.GetString(decrypted, 0, decryptedByteCount)); }
void BindSubAccount() { stbTaoBaoAccount.SkinTxt.Text = _subAccount.TaoBaoAccount; stbTaoBaoPassword.SkinTxt.Text = TripleDES.Decrypt3DES(_subAccount.Password); stbTaoBaoPayPassword.SkinTxt.Text = TripleDES.Decrypt3DES(_subAccount.PayPassword); stbHomePage.SkinTxt.Text = _subAccount.HomePage; scbTaoBaoLevel.SelectedIndex = (_subAccount.Level ?? 1) - 1; scbConsumptionLevel.SelectedIndex = (_subAccount.ConsumptionLevel ?? 1) - 1; scbProvince.Text = _subAccount.Province; scbCity.Text = _subAccount.City; scbDistrict.Text = _subAccount.District; stbAge.SkinTxt.Text = _subAccount.Age.HasValue ? _subAccount.Age.Value.ToString() : string.Empty; if (_subAccount.Sex.HasValue) { scbSex.SelectedIndex = _subAccount.Sex.Value ? 0 : 1; } if (_subAccount.UpperLimitAmount.HasValue) { stbUpperLimitAmount.SkinTxt.Text = _subAccount.UpperLimitAmount.Value.ToString(); } if (_subAccount.UpperLimitNumber.HasValue) { stbUpperLimitNumber.SkinTxt.Text = _subAccount.UpperLimitNumber.Value.ToString(); } if (_subAccount.Commission.HasValue) { stbCommission.SkinTxt.Text = _subAccount.Commission.Value.ToString(); } stbShippingAddress.SkinTxt.Text = _subAccount.ShippingAddress; scbRealName.Checked = _subAccount.IsRealName; scbBindingMobile.Checked = _subAccount.IsBindingMobile; scbEnabled.Checked = _subAccount.IsEnabled; }
public async Task TestWithNullUserRequestAsync() { // arrange var obj = new { username = "******", password = "******" }; var repository = new Mock <IRepository>(); var settings = new ApplicationSettings(); var validationService = new Mock <ValidationService>(repository.Object, settings); var administrationService = new Mock <AdministrationService>(repository.Object, validationService.Object); var mailService = new Mock <MailService>(repository.Object); var credentials = JObject.FromObject(obj); string q; using (var algorithm = TripleDES.Create()) { var ciphertext = CryptoUtilities.Encrypt(credentials.ToString(), algorithm.Key, algorithm.IV); q = 1 + ":" + ciphertext; } dynamic model = JObject.FromObject(new { q }); var accountService = new AccountService(repository.Object, validationService.Object, administrationService.Object, mailService.Object); // act var exception = await TestUtilities.ThrowsAsync <ServiceException>(async() => await accountService.ActivateAsync(model)); // assert Assert.Equal(ServiceReason.InvalidUserRequest, exception.Reason); repository.Verify(x => x.GetAsync <UserRequest>(It.IsAny <int>()), Times.Once); }
public oEncrypt(string inputtedData, string password, string filename) { string encryptedData; //Turn password to byte[] byte[] buffer = Encoding.UTF8.GetBytes(password); //Copy to key Array.Copy(buffer, 0, _key, 0, buffer.Length); //Turn Data to byte[] byte[] data = Encoding.UTF8.GetBytes(inputtedData); using (MemoryStream memoryStream = new MemoryStream()) { TripleDES tripleDes = TripleDES.Create(); tripleDes.Key = _key; tripleDes.Mode = CipherMode.ECB; using ( CryptoStream crytoStream = new CryptoStream(memoryStream, tripleDes.CreateEncryptor(), CryptoStreamMode.Write)) { crytoStream.Write(data, 0, data.Length); crytoStream.FlushFinalBlock(); byte[] cipherBytes = memoryStream.ToArray(); byte[] newBuffer = new byte[cipherBytes.Length + 4]; Array.Copy(cipherBytes, 0, newBuffer, 0, cipherBytes.Length); Array.Copy(Crc32.Compute(cipherBytes), 0, newBuffer, cipherBytes.Length, 4); encryptedData = Convert.ToBase64String(newBuffer); } tripleDes.Clear(); } using (StreamWriter writer = new StreamWriter(Environment.CurrentDirectory + "\\" + filename)) { writer.Write(encryptedData); } }
public bool DecryptData(string inputtedData, string password) { _result = null; //Get Encrypted data and convert to byte[] byte[] encryptedData = Convert.FromBase64String(inputtedData); //Get actual data byte[] realData = new byte[encryptedData.Length - 4]; Array.Copy(encryptedData, 0, realData, 0, realData.Length); //Get checksum byte[] checksum = new byte[4]; Array.Copy(encryptedData, realData.Length, checksum, 0, checksum.Length); byte[] check = Crc32.Compute(realData); //compare the new computed data to the version on the encrypted data if (!check.SequenceEqual(checksum)) { return(false); } //If all is valid Get password byte[] buffer = Encoding.UTF8.GetBytes(password); Array.Copy(buffer, 0, _key, 0, buffer.Length); //Get ready to decrypt TripleDES tripleDes = TripleDES.Create(); tripleDes.Key = _key; tripleDes.Mode = CipherMode.ECB; ICryptoTransform icryptoTransform = tripleDes.CreateDecryptor(); byte[] resultArray = icryptoTransform.TransformFinalBlock(realData, 0, realData.Length); _result = Encoding.UTF8.GetString(resultArray); tripleDes.Clear(); return(true); }
private static byte[] Secure(char[] pass) { // TODO: string secret = Environment.GetEnvironmentVariable("userCryptoPassword"); byte[] salt = new byte[8]; using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) { crypto.GetBytes(salt); } Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(pass.ToString(), salt); TripleDES tripleDES = TripleDES.Create(); tripleDES.Key = key.GetBytes(16); CryptoStream encrypt = new CryptoStream ( new MemoryStream(), tripleDES.CreateEncryptor(), CryptoStreamMode.Write ); throw new NotImplementedException("WIP"); }
public static byte[] GenerateDESKey( int keySizeInBits, byte[] senderEntropy, out byte[] receiverEntropy) { int length = ValidateKeySizeInBytes(keySizeInBits); byte[] numArray = new byte[length]; int num = 0; while (num <= 20) { receiverEntropy = new byte[length]; _random.GetNonZeroBytes(receiverEntropy); byte[] combinedKey = ComputeCombinedKey(senderEntropy, receiverEntropy, keySizeInBits); ++num; if (!TripleDES.IsWeakKey(combinedKey)) { return(combinedKey); } } throw new CryptographicException("Failed to generate DES key"); }
/// <summary> /// Decrypt string, ecncrypted with 3DES algorythm /// </summary> /// <param name="source">encrypted value</param> /// <returns>decrypted value</returns> public XVar Decrypt(XVar source) { if (String.IsNullOrEmpty(source)) { return(source); } try { byte[] key = Encoding.ASCII.GetBytes(this.key); //24characters byte[] encodedText = (byte[])MVCFunctions.hex2byte(source).Value; TripleDES des = TripleDES.Create(); des.Key = key; des.Mode = CipherMode.CBC; des.IV = Encoding.ASCII.GetBytes(RunnerCiphererDES.INITIALISATION_VECTOR); ICryptoTransform ic = des.CreateDecryptor(); byte[] decodedText = ic.TransformFinalBlock(encodedText, 0, encodedText.Length); return(UTF8Encoding.UTF8.GetString(decodedText)); } catch (Exception ex) { return(source); } }
private static byte[] DecryptPbdk2(byte[] encryptedPkcs8, byte[] salt, byte[] IV, SecureString securePassword, int iterations) { byte[] psBytes = SecureStringUtils.Decrypt(securePassword); var rfc2898DeriveBytes = new Rfc2898DeriveBytes(psBytes, salt, iterations); var decAlg = TripleDES.Create(); decAlg.Key = rfc2898DeriveBytes.GetBytes(24); decAlg.IV = IV; using (var memoryStream = new MemoryStream()) { using (var decrypt = new CryptoStream(memoryStream, decAlg.CreateDecryptor(), CryptoStreamMode.Write)) { decrypt.Write(encryptedPkcs8, 0, encryptedPkcs8.Length); decrypt.Flush(); // decrypt.Close(); // this is REQUIRED ? } return(memoryStream.ToArray()); } }
public SQLServerCryptoAlgorithm(SQLServerCryptoVersion sqlCryptoVersion) { Version = sqlCryptoVersion; switch (Version) { case SQLServerCryptoVersion.V1: Hash = SHA1.Create(); Symmetric = TripleDES.Create(); KeySize = 16; break; case SQLServerCryptoVersion.V2: Hash = SHA256.Create(); Symmetric = Aes.Create(); KeySize = 32; break; default: throw new Exception("Unsupported SQLServerCryptoVersion"); } Symmetric.Padding = PaddingMode.PKCS7; Symmetric.Mode = CipherMode.CBC; }
public Crypt(string NewPass) { //Usa saltos para evitar atack de dicionário var pdb = new PasswordDeriveBytes(NewPass, SALTBYTEARRAY); //-------------------------- /*Encoder tipo DES*/ //DES.Create(); //-------------------------- /*Encoder tipo RC2*/ //RC2.Create(); //-------------------------- /*Encoder tipo Rijndael*/ //Rijndael.Create(); //-------------------------- /*Encoder tipo Triple-DES*/ //TripleDES.Create(); //-------------------------- var algo = TripleDES.Create(); //-------------------------- MKEY = pdb.GetBytes(algo.KeySize / 8); MIV = pdb.GetBytes(algo.BlockSize / 8); }
private void button2_Click(object sender, RoutedEventArgs e) //3DES Dekriptiraj { try { TripleDES tDES = new TripleDES(textBox1.Text); if (!String.IsNullOrEmpty(textBox.Text)) { MessageBox.Show("Dekriptiram..."); tDES.TripleDES_Dekripcija(textBox.Text); GC.Collect(); MessageBox.Show("Izbrana datoteka dekriptirana z 3DES algoritmom!"); } else { MessageBox.Show("Datoteka ni bila izbrana!"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } }
public static string DecryptConnectionString(this string EncryptedConnection) { if (string.IsNullOrEmpty(EncryptedConnection)) { return("Input Can not be Null or Empty"); } string UnHashedConnectionString; TripleDES Triple_Des = TripleDES.Create(); Triple_Des.Key = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 }; Triple_Des.IV = new byte[] { 8, 7, 6, 5, 4, 3, 2, 1 }; using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(EncryptedConnection))) { using (CryptoStream cs = new CryptoStream(ms, Triple_Des.CreateDecryptor(), CryptoStreamMode.Read)) { using (StreamReader srDecrypt = new StreamReader(cs)) { UnHashedConnectionString = srDecrypt.ReadToEnd(); } } } return(UnHashedConnectionString); }
public override void init(int mode, byte[] key, byte[] iv) { if (mode != ENCRYPT_MODE && mode != DECRYPT_MODE) { throw new ArgumentOutOfRangeException(); } ms = new PipedMemoryStream(); desm = TripleDES.Create(); desm.KeySize = BlockSize * 8; desm.Padding = PaddingMode.None; ICryptoTransform ict; if (mode == ENCRYPT_MODE) { ict = desm.CreateEncryptor(key, iv); } else { ict = desm.CreateDecryptor(key, iv); } cs = new CryptoStream(ms, ict, CryptoStreamMode.Write); }
/// <summary> /// Performs either an encryption or decrytion /// </summary> /// <param name="plain">Unencrypted byte array /// <param name="password">Password to be used /// <param name="iterations">Number of iterations hash algorithm uses /// <param name="cryptproc">Process to be performed /// <returns>Results of process in the form of a byte array</returns> private static byte[] CryptBytes(byte[] plain, string password, int iterations, CryptProc cryptproc) { //Create our key from the password provided PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, SALT, "SHA512", iterations); //We'll be using 3DES TripleDES des = TripleDES.Create(); des.Key = pdb.GetBytes(24); des.IV = pdb.GetBytes(8); MemoryStream memstream = new MemoryStream(); ICryptoTransform cryptor = (cryptproc == CryptProc.ENCRYPT) ? des.CreateEncryptor() : des.CreateDecryptor(); CryptoStream cryptostream = new CryptoStream(memstream, cryptor, CryptoStreamMode.Write); cryptostream.Write(plain, 0, plain.Length); //write finished product to our MemoryStream cryptostream.Close(); return(memstream.ToArray()); }
/// <summary> /// Creates a key used to encrypt messages. /// </summary> /// <returns>The encryption key</returns> private EncryptionKey GetEncryptionKey() { // We generated a symmetric key using triple DES and stored the // key in the configuration file for this application. string keyData = ConfigurationSettings.AppSettings["symmetricKey"]; if (keyData == null) { throw new ApplicationException("Symmetric key not found."); } byte[] keyBytes = Convert.FromBase64String(keyData); SymmetricEncryptionKey key = new SymmetricEncryptionKey(TripleDES.Create(), keyBytes); KeyInfoName keyName = new KeyInfoName(); keyName.Value = "WSDK Sample Symmetric Key"; key.KeyInfo.AddClause(keyName); return(key); }
public void OverrideStream(Stream stream, byte[] keyIV, out Stream sread, out Stream swrite) { Console.WriteLine("OverrideStream : " + this.Key + " : " + BitConverter.ToString(keyIV)); var tdes = TripleDES.Create(); tdes.Key = keyIV.AsSpan().Slice(0, 24).ToArray(); tdes.IV = keyIV.AsSpan().Slice(24, 8).ToArray(); sread = Crypto.BlockCryptoStream.CreateDecryptReader(stream, tdes); swrite = Crypto.BlockCryptoStream.CreateEncryptWriter(stream, tdes); //throw new NotSupportedException(); //swrite = stream; //sread = stream; //TODO: not flush as expected , do it later. //var tdes = TripleDES.Create(); //tdes.Key = keyIV.AsSpan().Slice(0, 24).ToArray(); //tdes.IV = keyIV.AsSpan().Slice(24, 8).ToArray(); //sread = new CryptoStream(stream, tdes.CreateDecryptor(), CryptoStreamMode.Read); //swrite = new CryptoStream(stream, tdes.CreateEncryptor(), CryptoStreamMode.Write); }
public static string EncryptTripleDES(string key, string data) { data = data.Trim(); byte[] keydata = Encoding.ASCII.GetBytes(key); string md5String = BitConverter.ToString(new MD5CryptoServiceProvider().ComputeHash(keydata)).Replace("-", "").ToLower(); byte[] tripleDesKey = Encoding.ASCII.GetBytes(md5String.Substring(0, 24)); TripleDES tripdes = TripleDESCryptoServiceProvider.Create(); tripdes.Mode = CipherMode.ECB; tripdes.Key = tripleDesKey; tripdes.GenerateIV(); MemoryStream ms = new MemoryStream(); CryptoStream encStream = new CryptoStream(ms, tripdes.CreateEncryptor(), CryptoStreamMode.Write); encStream.Write(Encoding.ASCII.GetBytes(data), 0, Encoding.ASCII.GetByteCount(data)); encStream.FlushFinalBlock(); byte[] cryptoByte = ms.ToArray(); ms.Close(); encStream.Close(); return(Convert.ToBase64String(cryptoByte, 0, cryptoByte.GetLength(0)).Trim()); }
static string des3CbcDecryptFromBase64(byte[] key, string data) { string decryptedtext; String[] parts = data.Split(':'); using (TripleDES desAlg = TripleDES.Create()) { desAlg.Key = key; byte[] IV = Base64Decoding(parts[0]); string encryptedData = parts[1]; byte[] cipherText = Base64Decoding(encryptedData); desAlg.IV = IV; desAlg.Mode = CipherMode.CBC; ICryptoTransform decryptor = desAlg.CreateDecryptor(desAlg.Key, desAlg.IV); using (var msDecrypt = new MemoryStream(cipherText)) { using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) { using (var srDecrypt = new StreamReader(csDecrypt)) { decryptedtext = srDecrypt.ReadToEnd(); } } } } return(decryptedtext); }
public static void TripleDESRoundTripANSIX923ECB(int keySize, string expectedCipherHex, string keyHex) { byte[] key = keyHex.HexToByteArray(); using (TripleDES alg = TripleDESFactory.Create()) { alg.Key = key; Assert.Equal(keySize, alg.KeySize); alg.Padding = PaddingMode.ANSIX923; alg.Mode = CipherMode.ECB; byte[] plainText = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray(); byte[] cipher = alg.Encrypt(plainText); byte[] expectedCipher = expectedCipherHex.HexToByteArray(); Assert.Equal <byte>(expectedCipher, cipher); byte[] decrypted = alg.Decrypt(cipher); byte[] expectedDecrypted = "77a8b2efb45addb38d7ef3aa9e6ab5d71957445ab8".HexToByteArray(); Assert.Equal <byte>(plainText, decrypted); } }
/// <summary> /// 默认密钥和矢量的3DES解密 /// </summary> /// <param name="Value"></param> /// <returns></returns> public static string Decrypt3DES(string Value) { string sKey = "xhVs6DRXLfUGxw+AhtfQdpQGoa+8SA9d"; //32个字符 string sIV = "4vHKRj3yfzU="; //12个字符 SymmetricAlgorithm mCSP = TripleDES.Create(); ICryptoTransform ct; MemoryStream ms; CryptoStream cs; byte[] byt; mCSP.Key = Convert.FromBase64String(sKey); mCSP.IV = Convert.FromBase64String(sIV); mCSP.Mode = System.Security.Cryptography.CipherMode.ECB; mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7; ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV); byt = Convert.FromBase64String(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return(Encoding.UTF8.GetString(ms.ToArray())); }
/// <summary> /// Descriptografar uma string /// </summary> /// <param name="encryptedMessage">String Criptografado</param> /// <param name="key">Chave usada para Descriptografar </param> /// <returns>String desriptografar</returns> public static string Decryptor(string encryptedMessage, string key) { if (encryptedMessage == null) { throw new ArgumentNullException("encryptedMessage"); } if (key == null) { throw new ArgumentNullException("key"); } TripleDES tripleDes = TripleDES.Create(); tripleDes.IV = Encoding.ASCII.GetBytes(key); tripleDes.Key = Encoding.ASCII.GetBytes("passwordDR0wSS@P6660juht"); tripleDes.Mode = CipherMode.CBC; tripleDes.Padding = PaddingMode.Zeros; ICryptoTransform crypto = tripleDes.CreateDecryptor(); byte[] decodedInput = StringToByteArray(encryptedMessage); byte[] decryptedBytes = crypto.TransformFinalBlock(decodedInput, 0, decodedInput.Length); return(Encoding.ASCII.GetString(decryptedBytes)); }
public static void EncryptWithLargeOutputBuffer(bool blockAlignedOutput) { using (TripleDES alg = TripleDESFactory.Create()) using (ICryptoTransform xform = alg.CreateEncryptor()) { // 8 blocks, plus maybe three bytes int outputPadding = blockAlignedOutput ? 0 : 3; byte[] output = new byte[alg.BlockSize + outputPadding]; // 2 blocks of 0x00 byte[] input = new byte[alg.BlockSize / 4]; int outputOffset = 0; outputOffset += xform.TransformBlock(input, 0, input.Length, output, outputOffset); byte[] overflow = xform.TransformFinalBlock(Array.Empty <byte>(), 0, 0); Buffer.BlockCopy(overflow, 0, output, outputOffset, overflow.Length); outputOffset += overflow.Length; Assert.Equal(3 * (alg.BlockSize / 8), outputOffset); string outputAsHex = output.ByteArrayToHex(); Assert.NotEqual(new string('0', outputOffset * 2), outputAsHex.Substring(0, outputOffset * 2)); Assert.Equal(new string('0', (output.Length - outputOffset) * 2), outputAsHex.Substring(outputOffset * 2)); } }
/// <summary> /// Decrypts the PBD k2. /// </summary> /// <param name="edata">The edata.</param> /// <param name="salt">The salt.</param> /// <param name="IV">The IV vector</param> /// <param name="secpswd">The password.</param> /// <param name="iterations">The iterations.</param> /// <returns>Un-encrypted key</returns> /// <exception cref="System.ApplicationException">Problem in decrypting of PKCS #8 (Encrypted) Private key</exception> private byte[] DecryptPBDK2(byte[] edata, byte[] salt, byte[] IV, SecureString secpswd, int iterations) { IntPtr unmanagedPswd = IntPtr.Zero; byte[] psbytes = new byte[secpswd.Length]; unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); try { Rfc2898DeriveBytes kd = new Rfc2898DeriveBytes(psbytes, salt, iterations); TripleDES decAlg = TripleDES.Create(); decAlg.Key = kd.GetBytes(24); decAlg.IV = IV; byte[] cleartext = null; using (MemoryStream memoryStream = new MemoryStream()) { using (CryptoStream decrypt = new CryptoStream(memoryStream, decAlg.CreateDecryptor(), CryptoStreamMode.Write)) { decrypt.Write(edata, 0, edata.Length); decrypt.Flush(); decrypt.Close(); // this is REQUIRED. } cleartext = memoryStream.ToArray(); } return(cleartext); } catch (Exception e) { throw new ApplicationException("Problem in decrypting of PKCS #8 (Encrypted) Private key", e); } }
public override string ProcessMessage() { LMKPairs.LMKPair LMKKeyPair; string var = ""; KeySchemeTable.KeyScheme ks; string clearComponent = m_inStack.PopFromStack().ConsoleMessageProperty; string keyScheme = m_inStack.PopFromStack().ConsoleMessageProperty; string keyType = m_inStack.PopFromStack().ConsoleMessageProperty; string keyLen; switch (clearComponent.Length) { case 16: keyLen = "1"; break; case 32: keyLen = "2"; break; default: keyLen = "3"; break; } ValidateKeySchemeAndLength(keyLen, keyScheme, out ks); ValidateKeyTypeCode(keyType, out LMKKeyPair, out var); clearComponent = Utility.MakeParity(clearComponent, Utility.ParityCheck.OddParity); string cryptKey = Utility.EncryptUnderLMK(clearComponent, ks, LMKKeyPair, var); string chkVal = TripleDES.TripleDESEncrypt(new HexKey(clearComponent), ZEROES); return("Encrypted Component: " + MakeKeyPresentable(cryptKey) + System.Environment.NewLine + "Key check value: " + MakeCheckValuePresentable(chkVal)); }
protected string GeneratePVV(string AccountNumber, string PVKI, string PIN, string PVKPair) { string stage1 = AccountNumber.Substring(1, 11) + PVKI + PIN.Substring(0, 4); string stage2 = TripleDES.TripleDESEncrypt(new ThalesCore.Cryptography.HexKey(PVKPair), stage1); string PVV = ""; int i; while (PVV.Length < 4) { i = 0; while ((PVV.Length < 4) && (i < stage2.Length)) { if (Char.IsDigit(stage2[i])) { PVV += stage2.Substring(i, 1); i += 1; } } if (PVV.Length < 4) { for (int j = 0; j < stage2.Length; j++) { string newChar = " "; if (Char.IsDigit(stage2[j]) == false) { newChar = (Convert.ToInt32(stage2.Substring(j, 1), 16) - 10).ToString("X"); } stage2 = stage2.Remove(j, 1); stage2 = stage2.Insert(j, newChar); } stage2 = stage2.Replace(" ", ""); } } return(PVV); }
private static void DecryptDocx(String cipherText, String recoveredText) { SymmetricAlgorithm tdes = TripleDES.Create(); FileStream fin = new FileStream(cipherText, FileMode.Open, FileAccess.Read); FileStream fout = new FileStream(recoveredText, FileMode.OpenOrCreate, FileAccess.Write); FileStream fsKeyInfo = new FileStream(@"..\..\..\..\keyInfo2.txt", FileMode.Open, FileAccess.Read); FileStream fsIVInfo = new FileStream(@"..\..\..\..\ivInfo2.txt", FileMode.Open, FileAccess.Read); //set key (key must by byte[]) byte[] bytes64 = new byte[tdes.Key.Length]; fsKeyInfo.Read(bytes64, 0, tdes.Key.Length); tdes.Key = bytes64; //set iv (key must by byte[]) bytes64 = new byte[tdes.IV.Length]; fsIVInfo.Read(bytes64, 0, tdes.IV.Length); tdes.IV = bytes64; byte[] bin = new byte[100]; long rdlen = 0; long totlen = fin.Length; int len; CryptoStream decStream = new CryptoStream( fout, tdes.CreateDecryptor(tdes.Key, tdes.IV), CryptoStreamMode.Write); Console.WriteLine("Decrypting..."); while (rdlen < totlen) { len = fin.Read(bin, 0, 100); decStream.Write(bin, 0, len); rdlen = rdlen + len; } decStream.Clear(); decStream.Close(); fin.Close(); fout.Close(); }
public string TripleDESCripto(string value, string salt) { if (salt.IsNullOrEmpaty()) { throw new InvalidOperationException("Salt not found"); } if (string.IsNullOrEmpty(value)) { return(string.Empty); } using (var tripleDES = TripleDES.Create()) { byte[] Results; byte[] TDESKey = this.MD5Hash(salt); if (TDESKey.Length == 16) { byte[] keyTemp = new byte[24]; Buffer.BlockCopy(TDESKey, 0, keyTemp, 0, TDESKey.Length); Buffer.BlockCopy(TDESKey, 0, keyTemp, TDESKey.Length, 8); TDESKey = keyTemp; } tripleDES.Key = TDESKey; tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.PKCS7; byte[] DataToEncrypt = UTF8Encoding.UTF8.GetBytes(value); ICryptoTransform Encryptor = tripleDES.CreateEncryptor(); Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length); return(Convert.ToBase64String(Results)); } }
public static string EncryptUnderLMK(string clearKey, KeySchemeTable.KeyScheme Target_KeyScheme, LMKPairs.LMKPair LMKKeyPair, string variantNumber) { string result = ""; switch (Target_KeyScheme) { case KeySchemeTable.KeyScheme.SingleDESKey: case KeySchemeTable.KeyScheme.DoubleLengthKeyAnsi: case KeySchemeTable.KeyScheme.TripleLengthKeyAnsi: case KeySchemeTable.KeyScheme.Unspecified: result = TripleDES.TripleDESEncrypt(new HexKey(Cryptography.LMK.LMKStorage.LMKVariant(LMKKeyPair, Convert.ToInt32(variantNumber))), clearKey); break; case KeySchemeTable.KeyScheme.DoubleLengthKeyVariant: case KeySchemeTable.KeyScheme.TripleLengthKeyVariant: result = TripleDES.TripleDESEncryptVariant(new HexKey(Cryptography.LMK.LMKStorage.LMKVariant(LMKKeyPair, Convert.ToInt32(variantNumber))), clearKey); break; default: //throw new InvalidOperationException("Invalid key scheme [" + Target_KeyScheme.ToString() + "]"); break; } switch (Target_KeyScheme) { case KeySchemeTable.KeyScheme.DoubleLengthKeyAnsi: case KeySchemeTable.KeyScheme.DoubleLengthKeyVariant: case KeySchemeTable.KeyScheme.TripleLengthKeyAnsi: case KeySchemeTable.KeyScheme.TripleLengthKeyVariant: result = KeySchemeTable.GetKeySchemeValue(Target_KeyScheme) + result; break; default: break; } return(result); }
private void CodeButton_Click(object sender, EventArgs e) { // cipher SymmetricAlgorithm sa = TripleDES.Create(); sa.GenerateKey(); key = sa.Key; sa.Mode = CipherMode.ECB; sa.Padding = PaddingMode.PKCS7; MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sa.CreateEncryptor(), CryptoStreamMode.Write); byte[] plainbytes = Encoding.Default.GetBytes(plainTextBox.Text); cs.Write(plainbytes, 0, plainbytes.Length); cs.Close(); cipherbytes = ms.ToArray(); ms.Close(); // show ciphered text str = Encoding.Default.GetString(cipherbytes); cipherTextBox.Text = str; // decipher te = new byte[str.Length]; te = Encoding.Default.GetBytes(str); SymmetricAlgorithm sa2 = TripleDES.Create(); sa2.Key = key; sa2.Mode = CipherMode.ECB; sa2.Padding = PaddingMode.PKCS7; MemoryStream ms2 = new MemoryStream(te); CryptoStream cs2 = new CryptoStream(ms2, sa2.CreateDecryptor(), CryptoStreamMode.Read); byte[] plainbytes2 = new byte[te.Length]; cs2.Read(plainbytes2, 0, te.Length); cs2.Close(); ms2.Close(); textBox.Text = Encoding.Default.GetString(plainbytes2); }
// Check a TripleDES instance against a particular key and plaintext. // We do this by comparing against what DES would do, if applied manually. // This assumes that DES has already been tested and found to be OK. private static void CheckTripleDES(TripleDES alg, byte[] key, byte[] plaintext) { // Set up the algorithm the way we want. alg.Mode = CipherMode.ECB; alg.Padding = PaddingMode.None; // Create an encryptor and determine the output ciphertext. ICryptoTransform encryptor = alg.CreateEncryptor(key, null); byte[] ciphertext = new byte [plaintext.Length * 2]; byte[] tail; int len = encryptor.TransformBlock (plaintext, 0, plaintext.Length, ciphertext, 0); AssertEquals("ECB encrypt length mismatch", len, plaintext.Length); tail = encryptor.TransformFinalBlock (plaintext, 0, 0); AssertNotNull("ECB encrypt tail should be non-null"); AssertEquals("ECB encrypt tail should be zero length", tail.Length, 0); // Create a decryptor and run the test backwards. ICryptoTransform decryptor = alg.CreateDecryptor(key, null); byte[] original = new byte [plaintext.Length * 2]; len = decryptor.TransformBlock (ciphertext, 0, plaintext.Length, original, 0); AssertEquals("ECB decrypt length mismatch", len, plaintext.Length); tail = decryptor.TransformFinalBlock (ciphertext, 0, 0); AssertNotNull("ECB decrypt tail should be non-null"); AssertEquals("ECB decrypt tail should be zero length", tail.Length, 0); if(!IdenticalBlock(plaintext, 0, original, 0, plaintext.Length)) { Fail("did not decrypt to the original plaintext"); } // Now see what DES would say on the same input to make // sure that TripleDES is giving the correct behaviour. DES des = DES.Create(); des.Mode = CipherMode.ECB; des.Padding = PaddingMode.None; ICryptoTransform encrypt1; ICryptoTransform decrypt2; ICryptoTransform encrypt3; if(key.Length == 16) { encrypt1 = des.CreateEncryptor(SubKey(key, 0, 8), null); decrypt2 = des.CreateDecryptor(SubKey(key, 8, 8), null); encrypt3 = des.CreateEncryptor(SubKey(key, 0, 8), null); } else { encrypt1 = des.CreateEncryptor(SubKey(key, 0, 8), null); decrypt2 = des.CreateDecryptor(SubKey(key, 8, 8), null); encrypt3 = des.CreateEncryptor(SubKey(key, 16, 8), null); } byte[] block = new byte [plaintext.Length]; encrypt1.TransformBlock (plaintext, 0, plaintext.Length, block, 0); tail = encrypt1.TransformFinalBlock (plaintext, 0, 0); decrypt2.TransformBlock (block, 0, plaintext.Length, block, 0); tail = decrypt2.TransformFinalBlock (block, 0, 0); encrypt3.TransformBlock (block, 0, plaintext.Length, block, 0); tail = encrypt3.TransformFinalBlock (block, 0, 0); if(!IdenticalBlock(ciphertext, 0, block, 0, plaintext.Length)) { Fail("TripleDES does not have the correct behaviour"); } }