public void process() { /* * Setup the DESede cipher engine, create a PaddedBufferedBlockCipher * in CBC mode. */ cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher(new DesEdeEngine())); /* * The input and output streams are currently set up * appropriately, and the key bytes are ready to be * used. * */ if (encrypt) { performEncrypt(key); } else { performDecrypt(key); } // after processing clean up the files try { inStr.Close(); outStr.Flush(); outStr.Close(); } catch (IOException) { } }
public static byte[] Encrypt256(byte[] dataToEncrypt, byte[] IV, String password, int algorithm) { //Set up CbcBlockCipher engine = GetCryptoEngine(algorithm); if (algorithm != 1) { Array.Resize(ref IV, 16); //only Rijndael uses 32 byte IV, the other use 16 } CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); //Default scheme is PKCS5/PKCS7 var expandedKey = GetExpandedKey(password); KeyParameter keyParam = new KeyParameter(expandedKey); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, IV); // Encrypt cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(dataToEncrypt.Length)]; int length = cipher.ProcessBytes(dataToEncrypt, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block return(outputBytes); }
public AesResult Encrypt(string input, string keyString) { var inputBytes = Encoding.UTF8.GetBytes(input); var iv = new byte[16]; new SecureRandom().NextBytes(iv); //Set up var engine = new AesEngine(); var blockCipher = new CbcBlockCipher(engine); //CBC var cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 var keyParam = new KeyParameter(Convert.FromBase64String(keyString)); var keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); var outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; var length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block var encryptedInput = Convert.ToBase64String(outputBytes); return(new AesResult { EncryptedText = encryptedInput, Iv = iv }); }
/// <summary> /// Borrowed from https://github.com/vadimkantorov/wemosetup/blob/master/wemosetup.py /// </summary> /// <param name="password"></param> /// <param name="metainfo"></param> /// <returns></returns> private string EncryptPassword(string password, string metainfo) { string[] metaInfoParts = metainfo.Split('|'); string keydata = metaInfoParts[0].Substring(0, 6) + metaInfoParts[1] + metaInfoParts[0].Substring(6, 6); string salt = keydata.Substring(0, 8); string iv = keydata.Substring(0, 16); byte[] passwordAsBytes = Encoding.ASCII.GetBytes(Password); OpenSslPbeParametersGenerator keyGen = new OpenSslPbeParametersGenerator(); keyGen.Init(Encoding.ASCII.GetBytes(keydata), Encoding.ASCII.GetBytes(salt)); ICipherParameters cipherParams = keyGen.GenerateDerivedParameters("AES128", 128); AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); ParametersWithIV keyParamWithIv = new ParametersWithIV(cipherParams, Encoding.ASCII.GetBytes(iv), 0, 16); cipher.Init(true, keyParamWithIv); byte[] outputBytes = new byte[cipher.GetOutputSize(passwordAsBytes.Length)]; int length = cipher.ProcessBytes(passwordAsBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); return(Convert.ToBase64String(outputBytes)); }
public static BufferedBlockCipher GetTwofishCipher() { BufferedBlockCipher cipher = new PaddedBufferedBlockCipher( new CbcBlockCipher(new TwofishEngine())); return(cipher); }
public void OFBProcess(bool mode) { var cipher = new PaddedBufferedBlockCipher(new OfbBlockCipher(engine, subBlockLength * 8)); cipher.Init(mode, new KeyParameter(sessionKey)); Process(cipher, mode); }
public static byte[] EncryptKey(byte[] key, byte[] password) { //append a magic key to the key so we know if it was decrypted sucessfully byte[] concatenatedKey = (new byte[] { 39, 39, 39 }).Concat(key).ToArray(); //create the cipher and parameter for the generator PaddedBufferedBlockCipher pbbc = new PaddedBufferedBlockCipher(new AesEngine()); KeyParameter aesKey = new KeyParameter(password); pbbc.Init(true, aesKey); //create the output buffer byte[] encryptedKey = new byte[pbbc.GetOutputSize(concatenatedKey.Length)]; //do the encryption int bytesWritten = pbbc.ProcessBytes(concatenatedKey, 0, concatenatedKey.Length, encryptedKey, 0); pbbc.DoFinal(encryptedKey, bytesWritten); //erase the unencrypted data Eraser.SecureErase(key); Eraser.SecureErase(password); Eraser.SecureErase(concatenatedKey); return(encryptedKey); }
/// <summary> /// Encrypts the specified <paramref name="input"/> use DES. /// </summary> /// <param name="input">The input to encrypt.</param> /// <param name="key">The key.</param> /// <param name="iv">The IV.</param> /// <param name="mode">The cipher mode.</param> /// <param name="paddingMode">The padding mode.</param> /// <returns>The encrypted result.</returns> public static byte[] DesEncrypt(this byte[] input, byte[] key, byte[] iv, CipherMode mode = CipherMode.CBC, PaddingMode paddingMode = PaddingMode.Zeros) { #if NET461 var des = new DESCryptoServiceProvider() { Key = key, IV = iv, Mode = mode, Padding = paddingMode }; using (var ms = new MemoryStream()) { using (var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(input, 0, input.Length); cs.FlushFinalBlock(); return(ms.ToArray()); } } #else var engine = new DesEngine(); var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new ZeroBytePadding()); cipher.Init(true, new ParametersWithIV(new DesParameters(key), iv)); var rv = new byte[cipher.GetOutputSize(input.Length)]; var tam = cipher.ProcessBytes(input, 0, input.Length, rv, 0); cipher.DoFinal(rv, tam); return(rv); #endif }
/// <summary> /// Encapsulates the specified links into a CCF container. /// </summary> /// <param name="name">The name of the package.</param> /// <param name="links">The links.</param> /// <returns> /// CCF container. /// </returns> public static byte[] CreateCCF(string name, string[] links) { var sb = new StringBuilder(); sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sb.Append("<CryptLoad>"); sb.Append("<Package service=\"\" name=\"" + name + "\" url=\"Directlinks\">"); foreach (var link in links) { sb.Append("<Download Url=\"" + link + "\">"); sb.Append("<Url>" + link + "</Url>"); //sb.Append("<FileName></FileName>"); //sb.Append("<FileSize></FileSize>"); sb.Append("</Download>"); } sb.Append("</Package>"); sb.Append("</CryptLoad>"); var aes = new AesEngine(); var cbc = new CbcBlockCipher(aes); var pk7 = new Pkcs7Padding(); var pad = new PaddedBufferedBlockCipher(cbc, pk7); pad.Init(true, new ParametersWithIV(new KeyParameter(CCFKey), CCFIV)); return(pad.DoFinal(Encoding.UTF8.GetBytes(sb.ToString()))); }
private const int derivationIterations = 40000; //TODO change to 100000+ (not exactly 100000) /// <summary> /// Returns AES encrypted string /// </summary> /// <param name="text"></param> /// <param name="key"></param> /// <returns>Encrypted string</returns> public static string Encrypt(this string text, string key) { if (String.IsNullOrEmpty(text)) { throw new ArgumentException("string cannot be null or empty", nameof(text)); } if (String.IsNullOrEmpty(key)) { throw new ArgumentException("string cannot be null or empty", nameof(key)); } // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text // so that the same Salt and IV values can be used when decrypting. var saltStringBytes = Generate256BitsOfRandomEntropy(); var ivStringBytes = Generate256BitsOfRandomEntropy(); var plainTextBytes = Encoding.UTF8.GetBytes(text); using var password = new Rfc2898DeriveBytes(key, saltStringBytes, derivationIterations); var keyBytes = password.GetBytes(keySize / 8); var engine = new RijndaelEngine(256); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var keyParam = new KeyParameter(keyBytes); var keyParamWithIv = new ParametersWithIV(keyParam, ivStringBytes, 0, 32); cipher.Init(true, keyParamWithIv); var comparisonBytes = new byte[cipher.GetOutputSize(plainTextBytes.Length)]; var length = cipher.ProcessBytes(plainTextBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); return(Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray())); }
/// <summary> /// Encrypt a string with a byte array key /// </summary> /// <param name="plain">data to encrypt - hex representation of byte array</param> /// <param name="passwordBytes">key to use to encrypt</param> /// <returns>hex coded encrypted string</returns> public static string Encrypt(string plain, byte[] key) { var inBytes = StringToByteArray(plain); // get our cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(true, new KeyParameter(key)); // encrypt data var osize = cipher.GetOutputSize(inBytes.Length); var outBytes = new byte[osize]; var olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { var t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } // return encoded byte->hex string return(ByteArrayToString(outBytes)); }
public byte[] Encrypto(byte[] data, KeyParameter key) { PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), new Pkcs7Padding()); aes.Init(true, key); return(aes.DoFinal(data)); }
public Scp03CryptoSession() { ecb_cipher = new BufferedBlockCipher(new AesEngine()); cbc_cipher = new BufferedBlockCipher(new CbcBlockCipher(new AesEngine())); cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), new ISO7816d4Padding()); cmac = new CMac(new AesEngine()); }
public static byte[] HandleSessionKey(byte[] sessionKey, byte[] sharedSecret) { byte[] iv = new byte[16]; new SecureRandom().NextBytes(iv); TwofishEngine engine = new TwofishEngine(); CtrBlockCipher blockCipher = new CtrBlockCipher(engine); PaddedBufferedBlockCipher bufferedBlockCipher = new PaddedBufferedBlockCipher(blockCipher, new ZeroBytePadding()); KeyParameter secret = new KeyParameter(sharedSecret); ParametersWithIV key = new ParametersWithIV(secret, iv); bufferedBlockCipher.Init(true, key); byte[] result = new byte[iv.Length + sessionKey.Length]; bufferedBlockCipher.ProcessBytes(sessionKey, 0, sessionKey.Length, result, 16); Array.Copy(iv, result, iv.Length); int pos = 0; while (pos < sessionKey.Length) { int length = blockCipher.ProcessBlock(sessionKey, pos, result, pos + iv.Length); pos += length; } return(result); }
private static byte[] Crypto(bool encryption, byte[] dataForCrypt, byte[] key, IBlockCipher blockCipher) { PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); cipher.Init(encryption, new KeyParameter(key)); //does encryption or decryption based on value sent return(cipher.DoFinal(dataForCrypt)); }
/// <summary>Decrypt a hex-coded string using our MD5 or PBKDF2 generated key</summary> /// <param name="data">data string to be decrypted</param> /// <param name="key">decryption key</param> /// <param name="PBKDF2">flag to indicate we are using PBKDF2 to generate derived key</param> /// <returns>hex coded decrypted string</returns> public static string Decrypt(string data, string password, bool PBKDF2) { byte[] key; byte[] saltBytes = StringToByteArray(data.Substring(0, SALT_LENGTH * 2)); if (PBKDF2 == true) { // extract the salt from the data byte[] passwordBytes = Encoding.UTF8.GetBytes(password); // build our PBKDF2 key #if NETCF PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, 2000); #else Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltBytes, PBKDF2_ITERATIONS); #endif key = kg.GetBytes(PBKDF2_KEYSIZE); } else { // extract the salt from the data byte[] passwordBytes = Encoding.Default.GetBytes(password); key = new byte[saltBytes.Length + passwordBytes.Length]; Array.Copy(saltBytes, key, saltBytes.Length); Array.Copy(passwordBytes, 0, key, saltBytes.Length, passwordBytes.Length); // build out combined key MD5 md5 = MD5.Create(); key = md5.ComputeHash(key); } // extract the actual data to be decrypted byte[] inBytes = StringToByteArray(data.Substring(SALT_LENGTH * 2)); // get cipher BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new BlowfishEngine(), new ISO10126d2Padding()); cipher.Init(false, new KeyParameter(key)); // decrypt the data int osize = cipher.GetOutputSize(inBytes.Length); byte[] outBytes = new byte[osize]; try { int olen = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); olen += cipher.DoFinal(outBytes, olen); if (olen < osize) { byte[] t = new byte[olen]; Array.Copy(outBytes, 0, t, 0, olen); outBytes = t; } } catch (Exception) { // an exception is due to bad password throw new BadPasswordException(); } // return encoded string return(ByteArrayToString(outBytes)); }
string AESDecrypt(byte[] data, byte[] baseKey) { var cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new RijndaelEngine()), new ZeroBytePadding()); var iv = data.Take(16).ToArray(); var d = data.Skip(16).ToArray(); var s = new MemoryStream(); cipher.Init(false, new ParametersWithIV(new KeyParameter(baseKey), iv)); var outSize = cipher.GetOutputSize(d.Length); byte[] output = new byte[outSize]; var off = cipher.ProcessBytes(d, 0, d.Length, output, 0); s.Write(output, 0, off); off = cipher.DoFinal(output, 0); s.Write(output, 0, off); s.Seek(0, SeekOrigin.Begin); var o = s.ToArray(); s.Close(); return(Encoding.UTF8.GetString(o)); }
private void EncryptUsingBC(Stream istream, Stream ostream, byte[] iv, bool forEncryption) { var padding = ((TypeWrapper)BlockCipherModel.Padding).Instance <IBlockCipherPadding>(); var engine = BlockCipherModel.Engine.Instance <IBlockCipher>(); var mode = ((TypeWrapper)BlockCipherModel.Mode).Instance <IBlockCipher>(engine); var cipher = new PaddedBufferedBlockCipher(mode, padding); var buf = new byte[16]; //input buffer var obuf = new byte[512]; //output buffer int noBytesRead; //number of bytes read from input int noBytesProcessed; //number of bytes processed var p = new ParametersWithIV(new KeyParameter(PbkdfModel.Key), iv); cipher.Init(forEncryption, p); // Buffer used to transport the bytes from one stream to another while ((noBytesRead = istream.Read(buf, 0, Blocksize)) > 0) { //System.out.println(noBytesRead +" bytes read"); noBytesProcessed = cipher.ProcessBytes(buf, 0, noBytesRead, obuf, 0); //System.out.println(noBytesProcessed +" bytes processed"); ostream.Write(obuf, 0, noBytesProcessed); } //System.out.println(noBytesRead +" bytes read"); noBytesProcessed = cipher.DoFinal(obuf, 0); //System.out.println(noBytesProcessed +" bytes processed"); ostream.Write(obuf, 0, noBytesProcessed); ostream.Flush(); }
public void ECBProcess(bool mode) { var cipher = new PaddedBufferedBlockCipher(engine); cipher.Init(mode, new KeyParameter(sessionKey)); Process(cipher, mode); }
/// <summary> /// Symmetrical decryption of the bytes /// </summary> /// <param name="key">Password for the encryption</param> /// <param name="bytes">Bytes array which should be decrypted</param> /// <returns></returns> public static byte[] DecryptBytes(byte[] key, byte[] secret, byte[] iv = null) { var Keysize = 256 / 8; int iterationCount = 1; if (iv == null) { iv = new byte[16]; } AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding()); KeyParameter keyParam = new KeyParameter(key); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); byte[] outputBytes = secret; cipher.Init(false, keyParamWithIV); byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)]; int length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0); cipher.DoFinal(comparisonBytes, length); //Do the final block byte[] output = comparisonBytes.Take(comparisonBytes.Length).ToArray(); return(output); }
private void blockCheck( PaddedBufferedBlockCipher cipher, IBlockCipherPadding padding, KeyParameter key, byte[] data) { byte[] outBytes = new byte[data.Length + 8]; byte[] dec = new byte[data.Length]; try { cipher.Init(true, key); int len = cipher.ProcessBytes(data, 0, data.Length, outBytes, 0); len += cipher.DoFinal(outBytes, len); cipher.Init(false, key); int decLen = cipher.ProcessBytes(outBytes, 0, len, dec, 0); decLen += cipher.DoFinal(dec, decLen); if (!AreEqual(data, dec)) { Fail("failed to decrypt - i = " + data.Length + ", padding = " + padding.PaddingName); } } catch (Exception e) { Fail("Exception - " + e.ToString(), e); } }
/// <summary> /// Symmetrical encryption of the bytes /// </summary> /// <param name="key">Password for the encryption</param> /// <param name="bytes">Bytes array which should be encrypted</param> /// <returns></returns> public static byte[] EncryptBytes(byte[] key, byte[] secret, byte[] iv = null) { var iv_base64 = string.Empty; byte[] inputBytes = secret; //SecureRandom random = new SecureRandom(); if (iv == null) { iv = new byte[16]; } //random.NextBytes(iv); iv_base64 = Convert.ToBase64String(iv); string keyStringBase64 = Convert.ToBase64String(key); //Set up AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine), new Pkcs7Padding()); KeyParameter keyParam = new KeyParameter(Convert.FromBase64String(keyStringBase64)); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block return(outputBytes); }
void cbcStream(IBlockCipher blockCipher, bool encrypt, Stream inputStream, byte[] iv, Stream outputStream) { const int size = 4096; byte[] buffer = new byte[size]; var engine = blockCipher; var _cipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(_cipher, new Pkcs7Padding()); cipher.Init(encrypt, new ParametersWithIV( new KeyParameter(identifier.EncryptionKey), iv) ); var left = (int)(inputStream.Length - inputStream.Position); for (int i = 0; i < left / size - 1; i += 1) { inputStream.Read(buffer, 0, size); var bytes = cipher.ProcessBytes(buffer, 0, size); outputStream.Write(bytes, 0, bytes.Length); } left = (int)(inputStream.Length - inputStream.Position); buffer = new byte[left]; { inputStream.Read(buffer, 0, left); var bytes = cipher.DoFinal(buffer, 0, left); outputStream.Write(bytes, 0, bytes.Length); } }
protected virtual byte[] Crypt(bool encrypt, byte[] data, byte[] iv, byte[] keyE) { // Pad the input text to a multiple of 16 bytes, in accordance to PKCS7. BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new AesEngine()), new Pkcs7Padding()); ICipherParameters parms = new ParametersWithIV(new KeyParameter(keyE), iv); // Encrypt the data with AES - 256 - CBC, using IV as initialization vector, // key_e as encryption key and the padded input text as payload. Call the output cipher text. cipher.Init(encrypt, parms); byte[] buffer = new byte[cipher.GetOutputSize(data.Length)]; int length = cipher.ProcessBytes(data, 0, data.Length, buffer, 0); length += cipher.DoFinal(buffer, length); byte[] encrypted; if (length < buffer.Length) { encrypted = Arrays.CopyOfRange(buffer, 0, length); } else { encrypted = buffer; } return(encrypted); }
internal static AesWrapper Create() { CbcBlockCipher blockCipher = new CbcBlockCipher(new AesFastEngine()); //CBC var aes = new PaddedBufferedBlockCipher(blockCipher); return(new AesWrapper(aes)); }
private static string Decrypt(string cryptedMessage) { byte[] message = Convert.FromBase64String(cryptedMessage); // BouncyCastle version var Hmac = new Org.BouncyCastle.Crypto.Digests.Sha512Digest(); var keyToHash = Encoding.UTF8.GetBytes("Vg*b51^_! j4a\"I-d73j"); Hmac.BlockUpdate(keyToHash, 0, keyToHash.Length); byte[] result = new byte[Hmac.GetDigestSize()]; Hmac.DoFinal(result, 0); var array = new byte[24]; Array.Copy(result, array, array.Length); var DesEngine = new PaddedBufferedBlockCipher(new DesEdeEngine()); DesEngine.Init(false, new KeyParameter(array)); byte[] output = new byte[message.Length]; DesEngine.DoFinal(message, output, 0); return(Encoding.UTF8.GetString(output, 0, output.Length)); // PCLCrypto version //var hashEngine = WinRTCrypto.HashAlgorithmProvider.OpenAlgorithm(HashAlgorithm.Sha512); //var hash = hashEngine.HashData(Encoding.UTF8.GetBytes("Vg*b51^_! j4a\"I-d73j")); //var desEngine = WinRTCrypto.SymmetricKeyAlgorithmProvider.OpenAlgorithm(SymmetricAlgorithm.TripleDesEcb); //var key = new byte[24]; //Array.Copy(hash, key, key.Length); //var cryptoKey = desEngine.CreateSymmetricKey(key); //var bytes = WinRTCrypto.CryptographicEngine.Decrypt(cryptoKey, message); //return Encoding.UTF8.GetString(bytes, 0, bytes.Length); }
public static byte[] Decrypt256(byte[] encryptedBytes, byte[] IV, String password, int algorithm) { //Set up CbcBlockCipher engine = GetCryptoEngine(algorithm); if (algorithm != 1) { Array.Resize(ref IV, 16); //only Rijndael uses 32 byte IV, the other use 16 } CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); //Default scheme is PKCS5/PKCS7 var expandedKey = GetExpandedKey(password); KeyParameter keyParam = new KeyParameter(expandedKey); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, IV); //Decrypt cipher.Init(false, keyParamWithIV); byte[] decryptedBytes = new byte[cipher.GetOutputSize(encryptedBytes.Length)]; var length = cipher.ProcessBytes(encryptedBytes, decryptedBytes, 0); int finalBlockLengthWithoutPadding = cipher.DoFinal(decryptedBytes, length); //Do the final block int blockSize = 32; if (algorithm != 1) { blockSize = 16; } Array.Resize(ref decryptedBytes, decryptedBytes.Length - (blockSize - finalBlockLengthWithoutPadding)); //remove padding return(decryptedBytes); }
public static byte[] EncryptAES(byte[] inputBytes, byte[] key, byte[] iVector) { //Convert.FromBase64String(keyString); //Set up byte[] iv = iVector; //new byte[16]; AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(key); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, 16); // Encrypt cipher.Init(true, keyParamWithIV); byte[] outputBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int length = cipher.ProcessBytes(inputBytes, outputBytes, 0); cipher.DoFinal(outputBytes, length); //Do the final block //string encryptedInput = Convert.ToBase64String(outputBytes); //cipher.Init(false, keyParamWithIV); //byte[] comparisonBytes = new byte[cipher.GetOutputSize(outputBytes.Length)]; //length = cipher.ProcessBytes(outputBytes, comparisonBytes, 0); //cipher.DoFinal(comparisonBytes, length); //Do the final block return(outputBytes); }
/// <summary> /// 使用DES解密 /// </summary> /// <param name="data">待解密的字符串</param> /// <param name="key">解密密钥,要求8位</param> /// <param name="vi">偏移向量</param> /// <returns></returns> public static string DecryptDES(string data, string key, string vi) { StringBuilder ret = new StringBuilder(); foreach (byte b in Convert.FromBase64String(data)) { ret.AppendFormat("{0:X2}", b); } byte[] byData = new byte[ret.ToString().Length / 2]; for (int x = 0; x < ret.ToString().Length / 2; x++) { int i = (Convert.ToInt32(ret.ToString().Substring(x * 2, 2), 16)); byData[x] = (byte)i; } byte[] byKey = Encoding.ASCII.GetBytes(key); byte[] byVI = Encoding.ASCII.GetBytes(vi); BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(engine)); cipher.Init(false, new Org.BouncyCastle.Crypto.Parameters.ParametersWithIV(new DesParameters(byKey), byVI)); byte[] rv = new byte[cipher.GetOutputSize(byData.Length)]; int tam = cipher.ProcessBytes(byData, 0, byData.Length, rv, 0); cipher.DoFinal(rv, tam); var rvl = new List <byte>(); rvl.AddRange(rv); rvl.RemoveAll(b => b == 0); rv = rvl.ToArray(); return(Encoding.GetEncoding("gb2312").GetString(rv)); }
internal static RSA DecryptPrivateKey(EncryptedPrivateKeyInfo encryptedPrivateKeyInfo, string password) { var parameters = (DerSequence)encryptedPrivateKeyInfo.EncryptionAlgorithm.Parameters; var salt = ((DerOctetString)parameters[0]).GetOctets(); var iterations = ((DerInteger)parameters[1]).Value.IntValue; var pbkdf1 = new PasswordDeriveBytes(password, salt, "SHA1", iterations); var keyBytes = pbkdf1.GetBytes(16); var ivBytes = SHA1.Create().ComputeHash(pbkdf1.GetBytes(4)); var engine = new SeedEngine(); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher); var cipherParams = new ParametersWithIV(new KeyParameter(keyBytes), ivBytes, 0, 16); try { cipher.Init(false, cipherParams); var decoded = cipher.DoFinal(encryptedPrivateKeyInfo.GetEncryptedData()); var rsaParams = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(decoded); return(DotNetUtilities.ToRSA(rsaParams)); } catch (InvalidCipherTextException) { return(null); } }