/// <summary> /// Function for Text String Encryption /// <param name="text">Text to encrypt</param> /// <param name="secretKey">Text to encrypt</param> /// <returns>Encrypted string</returns> /// </summary> public string Encrypt(string text, string secretKey) { string functionReturnValue = null; if (string.IsNullOrEmpty(text.Trim())) { functionReturnValue = ""; } else { Des.Key = HashMd5.ComputeHash(new UnicodeEncoding().GetBytes(secretKey)); Des.Mode = CipherMode.ECB; var encrypt = Des.CreateEncryptor(); var buff = Encoding.UTF8.GetBytes(text); buff = encrypt.TransformFinalBlock(buff, 0, buff.Length); // Convert bytes to string from hex for (var i = 0; i < buff.Length; i++) { functionReturnValue += buff[i].ToString("X2"); } } return(functionReturnValue); }
public static void EncryptorReuse_LeadsToSameResults(CipherMode cipherMode, int feedbackSize) { // AppleCCCryptor does not allow calling Reset on CFB cipher. // this test validates that the behavior is taken into consideration. var input = "b72606c98d8e4fabf08839abf7a0ac61".HexToByteArray(); using (TripleDES tdes = TripleDESFactory.Create()) { tdes.Mode = cipherMode; if (feedbackSize > 0) { tdes.FeedbackSize = feedbackSize; } using (ICryptoTransform transform = tdes.CreateEncryptor()) { byte[] output1 = transform.TransformFinalBlock(input, 0, input.Length); byte[] output2 = transform.TransformFinalBlock(input, 0, input.Length); Assert.Equal(output1, output2); } } }
/// <summary> /// Encrypts a string /// </summary> public string Encrypt(string originalString) { string returnValue; try { var saltedString = originalString + this.Salt; TripleDES des = CreateDes(); ICryptoTransform encryptor = des.CreateEncryptor(); var encryptedByte = Encoding.Unicode.GetBytes(saltedString); // Final encryption and return returnValue = Convert.ToBase64String(encryptor.TransformFinalBlock(encryptedByte, 0, encryptedByte.Length)); if (this.EncodeForURL) { returnValue = Uri.EscapeDataString(returnValue).Replace("+", "%20"); } } catch { returnValue = string.Empty; } return(returnValue); }
static void Main(string[] args) { byte[] key = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF".HexToByteArray(); byte[] data = "1122334455667788".HexToByteArray(); byte[] iv = "0000000000000000".HexToByteArray(); TripleDES tripleDES = TripleDES.Create(); tripleDES.Mode = CipherMode.ECB; tripleDES.Padding = PaddingMode.Zeros; byte[] allKey = new byte[24]; Buffer.BlockCopy(key, 0, allKey, 0, 16); Buffer.BlockCopy(key, 0, allKey, 16, 8); ICryptoTransform trans = tripleDES.CreateEncryptor(allKey, iv); byte[] res = trans.TransformFinalBlock(data, 0, data.Length); Console.WriteLine(res.ByteArrayToHex()); Console.ReadKey(true); }
/// <summary> /// Encrypts a string /// </summary> public string Encrypt(string originalString) { var returnValue = TypeExtension.DefaultString; try { var saltedString = originalString + this.Salt; TripleDES des = CreateDes(); ICryptoTransform encryptor = des.CreateEncryptor(); var encryptedByte = Encoding.Unicode.GetBytes(saltedString); // Final encryption and return returnValue = Convert.ToBase64String(encryptor.TransformFinalBlock(encryptedByte, 0, encryptedByte.Length)); if (this.EncodeForURL) { returnValue = UrlEncoder.Encode(returnValue); } } catch { returnValue = TypeExtension.DefaultString; } return(returnValue); }
internal static string Encrypt(string str) { if (str.NullEmpty()) { return(string.Empty); } byte[] bytes = Encoding.UTF8.GetBytes(str); str = string.Empty; try { using (TripleDES TDES = TripleDES.Create()) { TDES.Key = keyBytes; byte[] MSArray = null; using (MemoryStream MS = new MemoryStream()) { using (CryptoStream CS = new CryptoStream(MS, TDES.CreateEncryptor(), CryptoStreamMode.Write)) CS.Write(bytes, 0, bytes.Length); bytes = new byte[] { }; MSArray = MS.ToArray(); } string encrypted1 = Convert.ToBase64String(TDES.IV); string encrypted2 = Convert.ToBase64String(MSArray); return(encrypted1.Remove(0, 1).Insert(0, encrypted2[0].ToString()) + '(' + encrypted2.Remove(0, 1).Insert(0, encrypted1[0].ToString())); } } catch (Exception exp) { ExceptionHelper.Log(exp); } return(string.Empty); }
public static string EncryptTripleDES(string key, string data) { 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()); }
/// <summary> /// Criptografar uma string /// </summary> /// <param name="decryptedMessage">String a ser criptografar</param> /// <param name="key">Chave usada para criptografar </param> /// <returns>String Criptografar</returns> public static string Encryptor(string decryptedMessage, string key) { if (decryptedMessage == null) { throw new ArgumentNullException("decryptedMessage"); } if (key == null) { throw new ArgumentNullException("key"); } TripleDES tripleDes = TripleDES.Create(); tripleDes.IV = Encoding.ASCII.GetBytes(key); tripleDes.Key = Encoding.ASCII.GetBytes("passwordDR0wSS@P6660juht"); byte[] data = Encoding.ASCII.GetBytes(decryptedMessage); byte[] enc = new byte[0]; tripleDes.Mode = CipherMode.CBC; tripleDes.Padding = PaddingMode.Zeros; ICryptoTransform ict = tripleDes.CreateEncryptor(); enc = ict.TransformFinalBlock(data, 0, data.Length); return(ByteArrayToString(enc)); }
public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV) { try { // Create or open the specified file. using (FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate)) { // Create a new TripleDES object. using (TripleDES tripleDESalg = TripleDES.Create()) { // Create a CryptoStream using the FileStream // and the passed key and initialization vector (IV). using (CryptoStream cStream = new CryptoStream(fStream, tripleDESalg.CreateEncryptor(Key, IV), CryptoStreamMode.Write)) { // Create a StreamWriter using the CryptoStream. using (StreamWriter sWriter = new StreamWriter(cStream)) { // Write the data to the stream // to encrypt it. sWriter.WriteLine(Data); } } } } } catch (CryptographicException e) { Console.WriteLine("A Cryptographic error occurred: {0}", e.Message); } catch (UnauthorizedAccessException e) { Console.WriteLine("A file access error occurred: {0}", e.Message); } }
public static void Main(string[] passwordargs) { //If no file name is specified, write usage text. if (passwordargs.Length == 0) { Console.WriteLine(usageText); } else { //<SNIPPET6> string pwd1 = passwordargs[0]; // Create a byte array to hold the random value. byte[] salt1 = new byte[8]; using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider()) { // Fill the array with a random value. rngCsp.GetBytes(salt1); } //data1 can be a string or contents of a file. string data1 = "Some test data"; //<SNIPPET3> //The default iteration count is 1000 so the two methods use the same iteration count. int myIterations = 1000; //</SNIPPET6> //<SNIPPET2> try { //<SNIPPET4> Rfc2898DeriveBytes k1 = new Rfc2898DeriveBytes(pwd1, salt1, myIterations); Rfc2898DeriveBytes k2 = new Rfc2898DeriveBytes(pwd1, salt1); //</SNIPPET4> // Encrypt the data. TripleDES encAlg = TripleDES.Create(); encAlg.Key = k1.GetBytes(16); MemoryStream encryptionStream = new MemoryStream(); CryptoStream encrypt = new CryptoStream(encryptionStream, encAlg.CreateEncryptor(), CryptoStreamMode.Write); byte[] utfD1 = new System.Text.UTF8Encoding(false).GetBytes( data1); //</SNIPPET2> encrypt.Write(utfD1, 0, utfD1.Length); encrypt.FlushFinalBlock(); encrypt.Close(); byte[] edata1 = encryptionStream.ToArray(); k1.Reset(); // Try to decrypt, thus showing it can be round-tripped. TripleDES decAlg = TripleDES.Create(); decAlg.Key = k2.GetBytes(16); decAlg.IV = encAlg.IV; MemoryStream decryptionStreamBacking = new MemoryStream(); CryptoStream decrypt = new CryptoStream( decryptionStreamBacking, decAlg.CreateDecryptor(), CryptoStreamMode.Write); //<SNIPPET5> decrypt.Write(edata1, 0, edata1.Length); decrypt.Flush(); decrypt.Close(); k2.Reset(); //</SNIPPET5> string data2 = new UTF8Encoding(false).GetString( decryptionStreamBacking.ToArray()); if (!data1.Equals(data2)) { Console.WriteLine("Error: The two values are not equal."); } else { Console.WriteLine("The two values are equal."); Console.WriteLine("k1 iterations: {0}", k1.IterationCount); Console.WriteLine("k2 iterations: {0}", k2.IterationCount); } //</SNIPPET3> } catch (Exception e) { Console.WriteLine("Error: ", e); } } }
// 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"); } }
public static string ThreeDesEncryptHEX(string input) { string result; if (string.IsNullOrEmpty(input)) { result = string.Empty; } else { string text = ""; TripleDES tripleDES = TripleDES.Create(); tripleDES.Mode = CipherMode.CBC; tripleDES.Padding = PaddingMode.PKCS7; byte[] rgbKey = new byte[] { 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6 }; byte[] rgbIV = new byte[] { 1, 2, 3, 4, 5, 6, 1, 2 }; ICryptoTransform transform = tripleDES.CreateEncryptor(rgbKey, rgbIV); byte[] bytes = Encoding.GetEncoding("GB2312").GetBytes(input); MemoryStream memoryStream = new MemoryStream(); CryptoStream cryptoStream = new CryptoStream(memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(bytes, 0, bytes.Length); cryptoStream.FlushFinalBlock(); cryptoStream.Close(); byte[] array = memoryStream.ToArray(); for (int i = 0; i < array.Length; i++) { text += array[i].ToString("x").PadLeft(2, '0'); } result = text; } return(result); }
internal ICryptoTransform GetCryptoServiceProvider(byte[] bytesKey) { switch (this.algorithmID) { case EncryptionAlgorithm.Des: DES des = (DES) new DESCryptoServiceProvider(); des.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = des.Key; } else { des.Key = bytesKey; this.encKey = des.Key; } if (this.initVec == null) { this.initVec = des.IV; } else { des.IV = this.initVec; } return(des.CreateEncryptor()); case EncryptionAlgorithm.Rc2: RC2 rc2 = (RC2) new RC2CryptoServiceProvider(); rc2.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rc2.Key; } else { rc2.Key = bytesKey; this.encKey = rc2.Key; } if (this.initVec == null) { this.initVec = rc2.IV; } else { rc2.IV = this.initVec; } return(rc2.CreateEncryptor()); case EncryptionAlgorithm.Rijndael: Rijndael rijndael = (Rijndael) new RijndaelManaged(); rijndael.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = rijndael.Key; } else { rijndael.Key = bytesKey; this.encKey = rijndael.Key; } if (this.initVec == null) { this.initVec = rijndael.IV; } else { rijndael.IV = this.initVec; } return(rijndael.CreateEncryptor()); case EncryptionAlgorithm.TripleDes: TripleDES tripleDes = (TripleDES) new TripleDESCryptoServiceProvider(); tripleDes.Mode = CipherMode.CBC; if (bytesKey == null) { this.encKey = tripleDes.Key; } else { tripleDes.Key = bytesKey; this.encKey = tripleDes.Key; } if (this.initVec == null) { this.initVec = tripleDes.IV; } else { tripleDes.IV = this.initVec; } return(tripleDes.CreateEncryptor()); default: throw new CryptographicException("Algorithm ID '" + (object)this.algorithmID + "' not supported."); } }
public byte[] Encrypt(byte[] p_aucInput) { // byte[] input = HexToByte(text.ToCharArray()); byte[] aucOutput = Transform(p_aucInput, m_des.CreateEncryptor()); return(aucOutput); }
public override byte[] Transform(byte[] data, TransformType type) { MemoryStream memoryStream = (MemoryStream)null; ICryptoTransform transform = (ICryptoTransform)null; TripleDES tripleDes = TripleDES.Create(); try { memoryStream = new MemoryStream(); tripleDes.Key = this.Key; tripleDes.IV = this.IV; transform = type != TransformType.ENCRYPT ? tripleDes.CreateDecryptor() : tripleDes.CreateEncryptor(); if (data == null || data.Length == 0) { return((byte[])null); } CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, transform, CryptoStreamMode.Write); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); return(memoryStream.ToArray()); } catch (CryptographicException ex) { throw new CryptographicException(ex.Message); } finally { tripleDes?.Clear(); transform?.Dispose(); memoryStream.Close(); } }
public static ICryptoTransform CreateEncryptor(TripleDES provider, string key, int keySize) { var kv = CreateKeyVector(key, keySize); return(provider.CreateEncryptor(kv.First, kv.Second)); }
private static ICryptoTransform __createEncryptor(Rfc2898DeriveBytes KeyGen) { TripleDES provider = TripleDES.Create(); return(provider.CreateEncryptor(KeyGen.GetBytes(16), KeyGen.GetBytes(16))); }
// 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"); } }
public static byte[] OWHF2_8_2(KernelDatabaseBase database, byte[] pd) { int pl = database.Get(EMVTagsEnum.DS_ID_9F5E_KRN2).Value.Length; byte[] dsid = database.Get(EMVTagsEnum.DS_ID_9F5E_KRN2).Value; byte[] dspkl = new byte[6]; byte[] dspkr = new byte[6]; for (int i = 0; i < 6; i++) { dspkl[i] = (byte)(((dsid[i] / 16) * 10 + (dsid[i] % 16)) * 2); dspkr[i] = (byte)(((dsid[pl - 6 + i] / 16) * 10 + (dsid[pl - 6 + i] % 16)) * 2); } byte[] oid = new byte[8]; if (database.IsNotEmpty(EMVTagsEnum.DS_SLOT_MANAGEMENT_CONTROL_9F6F_KRN2.Tag) && (database.Get(EMVTagsEnum.DS_SLOT_MANAGEMENT_CONTROL_9F6F_KRN2).Value[0] & 0x80) == 0x80 && // Permanent slot type (database.Get(EMVTagsEnum.DS_ODS_INFO_DF62_KRN2).Value[0] & 0x40) == 0x40 //Volatile slot type ) { oid = new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; } else { oid = database.Get(EMVTagsEnum.DS_REQUESTED_OPERATOR_ID_9F5C_KRN2).Value; } byte[] kl = new byte[8]; byte[] kr = new byte[8]; for (int i = 0; i < 6; i++) { kl[i] = dspkl[i]; kr[i] = dspkr[i]; } for (int i = 6; i < 8; i++) { kl[i] = oid[i - 2]; kr[i] = oid[i]; } TripleDES des = TripleDES.Create(); List <byte[]> keyComps = new List <byte[]>(); keyComps.Add(kl); keyComps.Add(kr); keyComps.Add(kl); byte[] key = keyComps.SelectMany(x => x).ToArray(); des.Key = key; des.Mode = CipherMode.CBC; des.Padding = PaddingMode.None; byte[] exOrData = XOR(oid, pd); MemoryStream ms = new MemoryStream(); using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(exOrData, 0, exOrData.Length); } byte[] r = ms.ToArray(); ms.Dispose(); return(XOR(r, pd)); }