public void TestEncryptDecryptWithSalt(Cipher cipher) { if (cipher == Cipher.Null) { Assert.Ignore(); } var inputMsg = "This is a message"; var input = Encoding.ASCII.GetBytes(inputMsg); var salt = Encoding.ASCII.GetBytes("salt"); var secret = Encoding.ASCII.GetBytes("Password!"); Console.Write("Using cipher {0}: ", cipher.LongName); using (var cc = new CipherContext(cipher)) { Console.Write(" KeyLength: {0}, IVLength: {1}, BlockSize: {2}, Stream: {3} ", cipher.KeyLength, cipher.IVLength, cipher.BlockSize, cc.IsStream); byte[] iv; var key = cc.BytesToKey(MessageDigest.SHA1, salt, secret, 1, out iv); var pt = cc.Encrypt(input, key, iv); Assert.AreNotEqual(input, pt); var ct = cc.Decrypt(pt, key, iv); var msg = Encoding.ASCII.GetString(ct); Console.WriteLine("\"{0}\"", msg); Assert.AreEqual(inputMsg, msg); } }
public void TestEncryptDecrypt(Cipher cipher) { var inputMsg = "This is a message"; var input = Encoding.ASCII.GetBytes(inputMsg); var iv = Encoding.ASCII.GetBytes("12345678"); var key = Encoding.ASCII.GetBytes("This is the key"); Console.Write("Using cipher {0}: ", cipher.LongName); using (var cc = new CipherContext(cipher)) { Console.Write(" KeyLength: {0}, IVLength: {1}, BlockSize: {2}, Stream: {3} ", cipher.KeyLength, cipher.IVLength, cipher.BlockSize, cc.IsStream); var pt = cc.Encrypt(input, key, iv); if (cipher == Cipher.Null) { Assert.AreEqual(input, pt); } else { Assert.AreNotEqual(input, pt); } var ct = cc.Decrypt(pt, key, iv); var msg = Encoding.ASCII.GetString(ct); Console.WriteLine("\"{0}\"", msg); Assert.AreEqual(inputMsg, msg); } }
public static string EncryptNEW(string plainText, byte[] hashBytes, byte[] ivBytes, Encoding encoding) { byte[] encryptedBytes; string encrypted = null; using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = hashBytes; aesAlg.IV = ivBytes; // Create an encryptor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) { //Write all data to the stream. swEncrypt.Write(plainText); } encryptedBytes = msEncrypt.ToArray(); } } } CipherContext aes = new CipherContext(Cipher.AES_256_CBC); byte[] plainTextBytes = encoding.GetBytes(plainText); encrypted = encoding.GetString(encryptedBytes); return(encrypted); }
/// <summary> /// 构造函数,初始化加密解密算法,生成密钥和初始化向量 /// </summary> /// <param name="password"></param> /// <param name="encodingname"></param> public OpensslHelper(string password, string encodingname) { this.EncodingName = encodingname; this.Password = Encoding.GetEncoding(EncodingName).GetBytes(password); //加密,解密算法:3DES cipherContext = new CipherContext(Cipher.DES_EDE3_CBC); GenerateKeyIV(); }
/// <summary> /// Exception in encrypting less than 8 bytes with Blowfish_CBC /// </summary> public void Bug3066497() { CipherContext cc = new CipherContext(Cipher.Blowfish_CBC); byte[] inputData = Encoding.UTF8.GetBytes("1234567"); byte[] key = Encoding.UTF8.GetBytes("secret!!"); byte[] iv = Encoding.UTF8.GetBytes("secret!!"); byte[] outputData = cc.Encrypt(inputData, key, iv); }
//https://stackoverflow.com/questions/2201631/how-do-i-use-the-openssl-net-c-sharp-wrapper-to-encrypt-a-string-with-aes public static string EncryptWithOpenSSLCrypt(string plainText, byte[] hashBytes, byte[] ivBytes, Encoding encoding) { string encrypted = null; CipherContext aes = new CipherContext(Cipher.AES_256_CBC); byte[] plainTextBytes = encoding.GetBytes(plainText); byte[] encryptedBytes = aes.Encrypt(plainTextBytes, hashBytes, ivBytes); encrypted = encoding.GetString(encryptedBytes); return(encrypted); }
public void EnableEncryption(byte[] pSharedSecretKey) { mDecryptCipher = Cipher.AES_128_OFB; mDecryptCipherContext = new CipherContext(mDecryptCipher); mDecryptKey = new byte[16]; mDecryptIV = new byte[16]; Buffer.BlockCopy(pSharedSecretKey, 0, mDecryptKey, 0, 16); Buffer.BlockCopy(pSharedSecretKey, 16, mDecryptIV, 0, 16); mProtocolState = EProtocolState.EncryptedAndCompressed; AdvanceDecryptIV(); }
public static byte[] Hash(byte[] input, CipherContext context) { uint r0 = 0x00000000; uint r3 = 0x5B3AA654; uint r5 = 0x75970A4D; uint r6 = (uint)input.Length; int newLength = (input.Length % 4 != 0) ? (input.Length + (4 - (input.Length % 4))) : input.Length; byte[] buffer = new byte[newLength]; Array.Copy(input, 0, buffer, 0, input.Length); FlipWords(buffer); // IV // Here the IV is determined by performing an RC pass on an empty 16 byte buffer. byte[] empty = new byte[0x10]; uint[] iv = new uint[4]; RC_Pass(empty, ref iv); // B5A0559C 88AA4C20 013D2CC7 CB2DE2B6 uint r16 = iv[0]; uint r17 = iv[1]; uint r18 = iv[2]; uint r19 = iv[3]; for (int i = 0; i < input.Length; i += 4) { r19 ^= r3; r18 += r16; r18 += r19; r18 = (r18 << 7) | (r18 >> (32 - 7)); r17 += r19; r17 += r18; r18 ^= r5; r17 = (r17 << 11) | (r17 >> (32 - 11)); r16 += r18; r16 += r17; r16 = (r16 >> 15) | (r16 << (32 - 15)); r0 = r16 & r17; r17 = ~r17; r6 = r18 & r17; r0 |= r6; r19 += r0; r16 = ~r16; r0 = (uint)((buffer[i + 0] << 24) | (buffer[i + 1] << 16) | (buffer[i + 2] << 8) | (buffer[i + 3] << 0)); r19 ^= r0; } uint hash = (uint)(((ulong)((r16 + r17 + r18 + r19) & 0x1FFFFFFF) | (ulong)context << 29)); return(BitConverter.GetBytes(hash)); }
public static String ExtractPassword(String phoneNumber, String pwFile) { byte[] usernameKey = Encoding.UTF8.GetBytes(phoneNumber); byte[] key = Hex.Decode(Encoding.UTF8.GetBytes("c2991ec29b1d0cc2b8c3b7556458c298c29203c28b45c2973e78c386c395")); MemoryStream PbkdfFileData = new MemoryStream(); PbkdfFileData.Write(key, 0, key.Length); PbkdfFileData.Write(usernameKey, 0, usernameKey.Length); PbkdfFileData.Flush(); PbkdfFileData.Close(); try { byte[] pw = File.ReadAllBytes(pwFile); byte[] pw_key = new byte[20]; Buffer.BlockCopy(pw, 49, pw_key, 0, 20); //File.WriteAllBytes("pw_key", pw_key); byte[] pw_salt = new byte[4]; Buffer.BlockCopy(pw, 29, pw_salt, 0, 4); //File.WriteAllBytes("pw_salt", pw_salt); byte[] pw_iv = new byte[16]; Buffer.BlockCopy(pw, 33, pw_iv, 0, 16); //File.WriteAllBytes("pw_iv", pw_iv); byte[] pbkdf2_pass_bin = PbkdfFileData.ToArray(); Pkcs5S2ParametersGenerator bcKeyDer = new Pkcs5S2ParametersGenerator(); bcKeyDer.Init(pbkdf2_pass_bin, pw_salt, 16); KeyParameter keyParameter = (KeyParameter)bcKeyDer.GenerateDerivedParameters("AES128", 128); byte[] pbkdf2_key_bin = keyParameter.GetKey(); Cipher cipher = Cipher.AES_128_OFB; CipherContext cipherContext = new CipherContext(cipher); byte[] passwordData = cipherContext.Decrypt(pw_key, pbkdf2_key_bin, pw_iv); String password = Convert.ToBase64String(passwordData); return(password); } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } finally { } return(null); }
public static BaseScertMessage Instantiate(RT_MSG_TYPE id, byte[] hash, byte[] messageBuffer, Func <RT_MSG_TYPE, CipherContext, ICipher> getCipherCallback = null) { // Init first Initialize(); BaseScertMessage msg = null; // Get class if (!_messageClassById.TryGetValue(id, out var classType)) { classType = null; } // Decrypt if (hash != null) { CipherContext context = (CipherContext)(hash[3] >> 5); var cipher = getCipherCallback(id, context); if (cipher == null) { return(null); } if (cipher.Decrypt(messageBuffer, hash, out var plain)) { msg = Instantiate(classType, id, plain); } // This is a hack to make the dme server connect // We don't really care what their key is since we're not encrypting our response else if (id == RT_MSG_TYPE.RT_MSG_CLIENT_CRYPTKEY_PUBLIC) { msg = Instantiate(classType, id, plain); } else { Logger.Error($"Unable to decrypt {id}, HASH:{BitConverter.ToString(hash)} DATA:{BitConverter.ToString(messageBuffer)} CIPHER:{cipher}"); } } else { msg = Instantiate(classType, id, messageBuffer); } return(msg); }
public void TestCase() { string magic = "Salted__"; const int PKCS5_SALT_LEN = 8; string base64 = "U2FsdGVkX1/moDHvAjok9X4prr8TXQtv9LRAIHk1IE8="; byte[] input = Convert.FromBase64String(base64); byte[] salt = new byte[PKCS5_SALT_LEN]; byte[] msg = new byte[input.Length - magic.Length - PKCS5_SALT_LEN]; Buffer.BlockCopy(input, magic.Length, salt, 0, salt.Length); Buffer.BlockCopy(input, magic.Length + PKCS5_SALT_LEN, msg, 0, msg.Length); using (CipherContext cc = new CipherContext(Cipher.AES_256_CBC)) { byte[] iv; byte[] password = Encoding.ASCII.GetBytes("example"); byte[] key = cc.BytesToKey(MessageDigest.MD5, salt, password, 1, out iv); byte[] output = cc.Decrypt(msg, key, iv); string text = Encoding.ASCII.GetString(output); Console.WriteLine(text); } }
public void TestSealOpen(Cipher cipher) { if (cipher == Cipher.Null) { Assert.Ignore(); } var inputMsg = "This is a message"; var input = Encoding.ASCII.GetBytes(inputMsg); using (var cc = new CipherContext(cipher)) { var env = cc.Seal(Keys, input); Assert.AreNotEqual(input, env.Data); for (int i = 0; i < Keys.Length; i++) { var result = cc.Open(env.Data, env.Keys[i], env.IV, Keys[i]); Assert.AreEqual(input, result); } } }
public void TestSealOpen() { string inputMsg = "This is a message"; byte[] input = Encoding.ASCII.GetBytes(inputMsg); const int numKeys = 10; var rsas = new RSA[numKeys]; var pkeys = new CryptoKey[numKeys]; for (int i = 0; i < numKeys; i++) { rsas[i] = new RSA(); rsas[i].GenerateKeys(1024, BigNumber.One, null, null); pkeys[i] = new CryptoKey(rsas[i]); } try { foreach (var cipher in Ciphers(true)) { using (var cc = new CipherContext(cipher)) { var env = cc.Seal(pkeys, input); Assert.AreNotEqual(input, env.Data); for (int i = 0; i < numKeys; i++) { var result = cc.Open(env.Data, env.Keys[i], env.IV, pkeys[i]); Assert.AreEqual(input, result); } } } } finally { for (int i = 0; i < numKeys; i++) { pkeys[i].Dispose(); rsas[i].Dispose(); } } }
public static byte[] Hash(byte[] input, CipherContext context) { byte[] result = new byte[4]; Hash(input, 0, input.Length, result, 0, (byte)context); return(result); }
public void Execute(string[] args) { try { options.ParseArguments(args); } catch (Exception) { Usage(); return; } MessageDigest md = null; if (options.IsSet("md")) { md = MessageDigest.CreateByName(options.GetString("md")); if (md == null) { Console.Error.WriteLine("{0} is an unsupported message digest type", options.GetString("md")); return; } } if (md == null) { md = MessageDigest.MD5; } if (options.IsSet("bufsize")) { } BIO bin = Program.GetInFile(options.GetString("infile")); string password = null; if (options.IsSet("password")) { password = options.GetString("password"); } else if (options.IsSet("kfile")) { var filename = options.GetString("kfile"); var lines = File.ReadAllLines(filename); if (lines.Length < 1 || lines[0].Length < 1) { Console.Error.WriteLine("zero length password"); return; } password = lines[0]; } if (password == null) { password = Program.OnPassword(true, options["passarg"]); if (password == null) { Console.Error.WriteLine("error getting password"); return; } } if (options.IsSet("base64")) { } var cipherName = options["cipher"] as string; if (!string.IsNullOrEmpty(cipherName)) { var cipher = Cipher.CreateByName(cipherName); if (cipher == null) { Console.Error.WriteLine("{0} is an unknown cipher", cipherName); return; } byte[] salt = null; if (!options.IsSet("nosalt")) { if (options.IsSet("enc")) { } } byte[] iv; var cc = new CipherContext(cipher); if (password != null) { var bytes = Encoding.ASCII.GetBytes(password); var key = cc.BytesToKey(MessageDigest.MD5, salt, bytes, 1, out iv); } } //string outfile = this.options["outfile"] as string; //if (string.IsNullOrEmpty(outfile)) // Console.WriteLine(bio.ReadString()); //else // File.WriteAllText(outfile, bio.ReadString()); }
public static String ExtractPassword(String phoneNumber) { byte[] usernameKey = Encoding.UTF8.GetBytes(phoneNumber); byte[] key = Hex.Decode(Encoding.UTF8.GetBytes("c2991ec29b1d0cc2b8c3b7556458c298c29203c28b45c2973e78c386c395")); MemoryStream PbkdfFileData = new MemoryStream(); PbkdfFileData.Write(key, 0, key.Length); PbkdfFileData.Write(usernameKey, 0, usernameKey.Length); PbkdfFileData.Flush(); PbkdfFileData.Close(); AndroidDebugBridge _AndroidDebugDevice = null; try { _AndroidDebugDevice = AndroidDebugBridge.CreateBridge("Tools\\adb.exe", false); _AndroidDebugDevice.Start(); //Get First Device Device _Device = AdbHelper.Instance.GetDevices(AndroidDebugBridge.SocketAddress).First(); if (_Device != null) { //Is Root Device if (_Device.CanSU()) { Object[] args = new Object[2]; args[0] = "/data/data/com.whatsapp/files/pw"; args[1] = "/sdcard"; _Device.ExecuteRootShellCommand("cp /data/data/com.whatsapp/files/pw /sdcard", new ConsoleOutputReceiver(), args); using (SyncService service = new SyncService(_Device)) { SyncResult syncResult = service.PullFile("/sdcard/pw", PasswordFile, new NullSyncProgressMonitor()); if (syncResult.Code == 0) { byte[] pw = File.ReadAllBytes(PasswordFile); byte[] pw_key = new byte[20]; Buffer.BlockCopy(pw, 49, pw_key, 0, 20); //File.WriteAllBytes("pw_key", pw_key); byte[] pw_salt = new byte[4]; Buffer.BlockCopy(pw, 29, pw_salt, 0, 4); //File.WriteAllBytes("pw_salt", pw_salt); byte[] pw_iv = new byte[16]; Buffer.BlockCopy(pw, 33, pw_iv, 0, 16); //File.WriteAllBytes("pw_iv", pw_iv); byte[] pbkdf2_pass_bin = PbkdfFileData.ToArray(); Pkcs5S2ParametersGenerator bcKeyDer = new Pkcs5S2ParametersGenerator(); bcKeyDer.Init(pbkdf2_pass_bin, pw_salt, 16); KeyParameter keyParameter = (KeyParameter)bcKeyDer.GenerateDerivedParameters("AES128", 128); byte[] pbkdf2_key_bin = keyParameter.GetKey(); Cipher cipher = Cipher.AES_128_OFB; CipherContext cipherContext = new CipherContext(cipher); byte[] passwordData = cipherContext.Decrypt(pw_key, pbkdf2_key_bin, pw_iv); String password = Convert.ToBase64String(passwordData); return(password); } } } } } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } finally { if (_AndroidDebugDevice != null) { _AndroidDebugDevice.Stop(); } CleanUp(); } return(null); }
/// <summary> /// Initialize with key. /// UYA wants a 512 bit key. /// </summary> public PS2_RC4(byte[] key, CipherContext context) { Context = context; workingKey = key; }
public PS3_RC(byte[] key, CipherContext context) { Context = context; SetKey(key); }
public CipherController() { ctx = new CipherContext(); }
public static List <BaseMessage> Instantiate(byte[] messageBuffer, int index, int size, Func <RT_MSG_TYPE, CipherContext, ICipher> getCipherCallback = null) { // Init first Initialize(); List <BaseMessage> msgs = new List <BaseMessage>(); BaseMessage msg = null; // using (MemoryStream stream = new MemoryStream(messageBuffer, index, size)) { using (BinaryReader reader = new BinaryReader(stream)) { while (reader.BaseStream.CanRead && reader.BaseStream.Position < reader.BaseStream.Length) { // Reset msg = null; long start = reader.BaseStream.Position; // Parse header byte rawId = reader.ReadByte(); RT_MSG_TYPE id = (RT_MSG_TYPE)(rawId & 0x7F); bool encrypted = rawId >= 0x80; ushort len = reader.ReadUInt16(); // End if (len > (reader.BaseStream.Length - reader.BaseStream.Position)) { break; } // Get class if (!_messageClassById.TryGetValue(id, out var classType)) { classType = null; } // Decrypt if (encrypted && len > 0) { byte[] hash = reader.ReadBytes(4); byte[] cipherText = reader.ReadBytes(len); CipherContext context = (CipherContext)(hash[3] >> 5); var cipher = getCipherCallback(id, context); if (cipher.Decrypt(cipherText, hash, out var plain)) { msg = Instantiate(classType, id, plain); } // This is a hack to make the dme server connect // We don't really care what their key is since we're not encrypting our response else if (id == RT_MSG_TYPE.RT_MSG_CLIENT_CRYPTKEY_PUBLIC) { msg = new RT_MSG_CLIENT_CRYPTKEY_PUBLIC(); } else { Console.WriteLine($"Unable to decrypt {id} {len}, HASH:{BitConverter.ToString(hash)} DATA:{BitConverter.ToString(cipherText)}"); } } else { msg = Instantiate(classType, id, reader.ReadBytes(len)); } if (msg != null) { msgs.Add(msg); } } } } return(msgs); }