public void Init(bool encrypting, ICipherParameters parameters) { if (!(parameters is KeyParameter)) { throw new ArgumentException("Invalid parameter passed to " + "DesSsh1Engine init - " + parameters.GetType()); } this.encrypting = encrypting; byte[] passphraseKey = (parameters as KeyParameter).GetKey(); if (passphraseKey.Length != 16) { throw new ArgumentException("key size different than 16 bytes"); } byte[] keyPart1 = new byte[8]; byte[] keyPart2 = new byte[8]; Array.Copy(passphraseKey, keyPart1, 8); Array.Copy(passphraseKey, 8, keyPart2, 0, 8); desEngine1 = new CbcBlockCipher(new DesEngine()); desEngine2 = new CbcBlockCipher(new DesEngine()); desEngine3 = new CbcBlockCipher(new DesEngine()); desEngine1.Init(encrypting, new KeyParameter(keyPart1)); desEngine2.Init(!encrypting, new KeyParameter(keyPart2)); desEngine3.Init(encrypting, new KeyParameter(keyPart1)); }
private static BufferedBlockCipher CreateCipher(DerObjectIdentifier algorithm) { IBlockCipher cipher; if (NistObjectIdentifiers.IdAes128Cbc.Equals(algorithm) || NistObjectIdentifiers.IdAes192Cbc.Equals(algorithm) || NistObjectIdentifiers.IdAes256Cbc.Equals(algorithm)) { cipher = new CbcBlockCipher(new AesEngine()); } else if (PkcsObjectIdentifiers.DesEde3Cbc.Equals(algorithm)) { cipher = new CbcBlockCipher(new DesEdeEngine()); } else if (OiwObjectIdentifiers.DesCbc.Equals(algorithm)) { cipher = new CbcBlockCipher(new DesEngine()); } else if (PkcsObjectIdentifiers.RC2Cbc.Equals(algorithm)) { cipher = new CbcBlockCipher(new RC2Engine()); } else if (MiscObjectIdentifiers.cast5CBC.Equals(algorithm)) { cipher = new CbcBlockCipher(new Cast5Engine()); } else { throw new InvalidOperationException("cannot recognise cipher: " + algorithm); } return(new PaddedBufferedBlockCipher(cipher, new Pkcs7Padding())); }
public static GarlicMessage AESEncryptGarlic( Garlic msg, I2PSessionKey sessionkey, I2PSessionTag tag, List <I2PSessionTag> newtags) { var cipher = new CbcBlockCipher(new AesEngine()); var payload = msg.ToByteArray(); var dest = new BufLen(new byte[65536]); // Reserve header + 4 bytes for GarlicMessageLength var writer = new BufRefLen(dest, I2NPMaxHeaderSize + 4); // Tag as header writer.Write(tag.Value); // AES block var aesstart = new BufLen(writer); var aesblock = new GarlicAESBlock(writer, newtags, null, new BufRefLen(payload)); var pivh = I2PHashSHA256.GetHash(tag.Value); cipher.Init(true, sessionkey.Key.ToParametersWithIV(new BufLen(pivh, 0, 16))); cipher.ProcessBytes(aesblock.DataBuf); var length = writer - dest; dest.PokeFlip32((uint)(length - 4), I2NPMaxHeaderSize); return(new GarlicMessage(new BufRefLen(dest, I2NPMaxHeaderSize, length))); }
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())); }
public static (GarlicAESBlock, I2PSessionKey) EGDecryptGarlic( GarlicMessage garlic, I2PPrivateKey privkey) { var cipher = new CbcBlockCipher(new AesEngine()); var egdata = garlic.EGData; var egbuf = new BufLen(egdata, 0, 514); var egheader = ElGamalCrypto.Decrypt(egbuf, privkey, true); var sessionkey = new I2PSessionKey(new BufLen(egheader, 0, 32)); var preiv = new BufLen(egheader, 32, 32); var egpadding = new BufLen(egheader, 64, 158); var aesbuf = new BufLen(egdata, 514); var pivh = I2PHashSHA256.GetHash(preiv); cipher.Init(false, sessionkey.Key.ToParametersWithIV(new BufLen(pivh, 0, 16))); cipher.ProcessBytes(aesbuf); GarlicAESBlock aesblock = new GarlicAESBlock(new BufRefLen(aesbuf)); if (!aesblock.VerifyPayloadHash()) { throw new ChecksumFailureException("AES block hash check failed!"); } return(aesblock, sessionkey); }
public void Init(string passkey) { //0-4 AssertNextBytesEqual(Safe.Tag); //5-36 var salt = ReadBytes(Safe.SaltLengthV3); //37-40 var iterations = ReadUInt32(); var keyCipher = new KeyCipher(_crypto, false, passkey, salt, iterations); //41-72 var expectedKeyHash = ReadBytes(Safe.StretchedPasskeyHashLength); if (!keyCipher.ValidateHashedKey(expectedKeyHash)) { throw new InvalidPasskeyException(); } //73-104 var dataKey = Decrypt(keyCipher, Safe.DataKeyLength); //105-136 var hmacKey = Decrypt(keyCipher, Safe.HmacKeyLength); //137-152 var dataInitializationVector = ReadBytes(Safe.DataInitializationVectorLength); _dataCipher = new DataCipher(false, dataKey, dataInitializationVector); _hmac = _crypto.HMACSHA256Factory.From(hmacKey); }
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); } }
/// <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()))); }
/** * create a standard MAC based on a block cipher with the size of the * MAC been given in bits. * <p/> * Note: the size of the MAC must be at least 24 bits (FIPS Publication 81), * or 16 bits if being used as a data authenticator (FIPS Publication 113), * and in general should be less than the size of the block cipher as it reduces * the chance of an exhaustive attack (see Handbook of Applied Cryptography). * * @param cipher the cipher to be used as the basis of the MAC generation. * @param macSizeInBits the size of the MAC in bits, must be a multiple of 8 and @lt;= 128. */ public CMac( BlockCipherBase cipher, int macSizeInBits) { if ((macSizeInBits % 8) != 0) { throw new ArgumentException("MAC size must be multiple of 8"); } if (macSizeInBits > (cipher.BlockSize * 8)) { throw new ArgumentException( "MAC size must be less or equal to " + (cipher.BlockSize * 8)); } if (cipher.BlockSize != 8 && cipher.BlockSize != 16) { throw new ArgumentException( "Block size must be either 64 or 128 bits"); } this._cipher = new CbcBlockCipher(cipher); this._outputSize = macSizeInBits / 8; _zeroes = new byte[cipher.BlockSize]; _nullCbcIv = new byte[cipher.BlockSize]; _buf = new byte[cipher.BlockSize]; _bufOff = 0; _mac = new byte[this._outputSize]; }
public string Encrypt(string plainText, string passPhrase) { // 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(plainText); using (var password = new Rfc2898DeriveBytes(passPhrase, 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(comparisonBytes); return(Convert.ToBase64String(saltStringBytes.Concat(ivStringBytes).Concat(comparisonBytes).ToArray())); } }
/// <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); }
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> /// 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 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 }); }
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 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); }
/// <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); }
internal static AesWrapper Create() { CbcBlockCipher blockCipher = new CbcBlockCipher(new AesFastEngine()); //CBC var aes = new PaddedBufferedBlockCipher(blockCipher); return(new AesWrapper(aes)); }
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); } }
/// <exclude /> public static byte[] CreateEncryptionParams(string password, byte[] salt, int iterations, byte[] dataKey) { var versionBytes = BitConverter.GetBytes(1); var iterationsBytes = BitConverter.GetBytes(iterations); if (BitConverter.IsLittleEndian) { Array.Reverse(iterationsBytes); } var key = DeriveKeyV1(password, salt, iterations); var iv = GetRandomBytes(16); var parameters = new ParametersWithIV(new KeyParameter(key), iv); var cipher = new CbcBlockCipher(new AesEngine()); cipher.Init(true, parameters); var outBuffer = new byte[dataKey.Length * 2]; var len = 0; while (len < outBuffer.Length) { var offset = len % dataKey.Length; len += cipher.ProcessBlock(dataKey, offset, outBuffer, len); } return(new[] { versionBytes.Take(1), iterationsBytes.Skip(1), salt, iv, outBuffer }.SelectMany(x => x) .ToArray()); }
public static string Cipher(this string data, CypherMode mode) { var kdf2BytesGenerator = new Kdf2BytesGenerator(new Sha1Digest()); var kdfParameters = new KdfParameters(Key, Iv); kdf2BytesGenerator.Init(kdfParameters); var key = new byte[16]; kdf2BytesGenerator.GenerateBytes(key, 0, key.Length); var engine = new AesLightEngine(); var blockCipher = new CbcBlockCipher(engine); var cipher = new PaddedBufferedBlockCipher(blockCipher, new Pkcs7Padding()); var parameter = new KeyParameter(key); var parameterWithIv = new ParametersWithIV(parameter, Iv, 0, 16); var targetBytes = mode == CypherMode.Decryption ? Convert.FromBase64String(data) : Encoding.UTF8.GetBytes(data); cipher.Init(mode == CypherMode.Encryption, parameterWithIv); var output = new byte[cipher.GetOutputSize(targetBytes.Length)]; var length = cipher.ProcessBytes(targetBytes, output, 0); cipher.DoFinal(output, length); return(mode == CypherMode.Encryption ? Convert.ToBase64String(output) : Encoding.UTF8.GetString(output.Where(@byte => @byte != 0).ToArray())); }
public IEnumerable <AesEGBuildRequestRecord> CreateTunnelBuildReplyRecords( BuildResponseRecord.RequestResponse response) { var newrecords = new List <AesEGBuildRequestRecord>( Records.Select(r => r.Clone()) ); var tmp = new TunnelBuildRequestDecrypt(newrecords, Me, Key); tmp.ToMeField.Data.Randomize(); var responserec = new BuildResponseRecord(tmp.ToMeField.Data) { Reply = response }; responserec.UpdateHash(); var cipher = new CbcBlockCipher(new AesEngine()); cipher.Init(true, Decrypted.ReplyKeyBuf.ToParametersWithIV(Decrypted.ReplyIV)); foreach (var one in newrecords) { cipher.Reset(); one.Process(cipher); } return(newrecords); }
public static string GenEncrypedPin(string pin, string pinToken, string sessionId, RsaPrivateCrtKeyParameters rsa, ulong it) { ulong time = (ulong)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds; var bPinToken = Convert.FromBase64String(pinToken); IAsymmetricBlockCipher cipherRsa = new RsaBlindedEngine(); cipherRsa = new OaepEncoding(cipherRsa, new Sha256Digest(), new Sha256Digest(), Encoding.ASCII.GetBytes(sessionId)); BufferedAsymmetricBlockCipher cipher = new BufferedAsymmetricBlockCipher(cipherRsa); cipher.Init(false, rsa); cipher.ProcessBytes(bPinToken, 0, bPinToken.Length); var key = cipher.DoFinal(); var bPin = Encoding.ASCII.GetBytes(pin); var btime = BitConverter.GetBytes(time); var biterator = BitConverter.GetBytes(it); int len = bPin.Length + btime.Length + biterator.Length; IBlockCipher cipherAes = new AesEngine(); int bsize = cipherAes.GetBlockSize(); KeyParameter keyParameter = new KeyParameter(key); int nPadding = bsize - len % bsize; var bPadding = new byte[nPadding]; len += (len % bsize == 0 ? 0 : nPadding); var blocks = new byte[len]; Array.Copy(bPin, blocks, bPin.Length); Array.Copy(btime, 0, blocks, bPin.Length, btime.Length); Array.Copy(biterator, 0, blocks, bPin.Length + btime.Length, biterator.Length); Array.Copy(bPadding, 0, blocks, bPin.Length + btime.Length + biterator.Length, nPadding); var iv = new byte[bsize]; random.NextBytes(iv); CbcBlockCipher cbcBc = new CbcBlockCipher(cipherAes); ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, iv); BufferedBlockCipher bc = new BufferedBlockCipher(cbcBc); bc.Init(true, parametersWithIV); var bOut = bc.ProcessBytes(blocks); var rz = new byte[bOut.Length + bsize]; Array.Copy(iv, rz, iv.Length); Array.Copy(bOut, 0, rz, iv.Length, bOut.Length); return(Convert.ToBase64String(rz)); }
protected override string EncryptOrDecrypt(bool type, string plainStr) { //Demo params string keyString = GetEncryptionKey(); string input = plainStr; byte[] inputBytes; byte[] iv = System.Text.Encoding.UTF8.GetBytes("0123456789012345"); byte[] keyBytes = System.Text.Encoding.UTF8.GetBytes(keyString); //Set up AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); //CBC PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(blockCipher); //Default scheme is PKCS5/PKCS7 KeyParameter keyParam = new KeyParameter(keyBytes); ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, iv, 0, iv.Length); if (type) { // Encrypt input = EncodeNonAsciiCharacters(input); inputBytes = Encoding.UTF8.GetBytes(input); 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); return(encryptedInput); } else { try { //Decrypt inputBytes = Convert.FromBase64CharArray(input.ToCharArray(), 0, input.Length); cipher.Init(false, keyParamWithIV); byte[] encryptedBytes = new byte[cipher.GetOutputSize(inputBytes.Length)]; int encryptLength = cipher.ProcessBytes(inputBytes, encryptedBytes, 0); int numOfOutputBytes = cipher.DoFinal(encryptedBytes, encryptLength); //Do the final block //string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, encryptedBytes.Length); int len = Array.IndexOf(encryptedBytes, (byte)0); len = (len == -1) ? encryptedBytes.Length : len; string actualInput = Encoding.UTF8.GetString(encryptedBytes, 0, len); return(actualInput); } catch (Exception ex) { #if (ENABLE_PUBNUB_LOGGING) pnLog.WriteToLog(string.Format("Decrypt Error. {0}", ex.ToString()), PNLoggingMethod.LevelVerbose); #endif throw ex; //LoggingMethod.WriteToLog(string.Format("DateTime {0} Decrypt Error. {1}", DateTime.Now.ToString(), ex.ToString()), LoggingMethod.LevelVerbose); //return "**DECRYPT ERROR**"; } } }
public static void EncryptFile(string inFile, string outFile, string in_key) { byte[] key = Encoding.ASCII.GetBytes(in_key); byte[] IV = Encoding.ASCII.GetBytes(iv); AesEngine aesEngine = new AesEngine(); CbcBlockCipher cbc = new CbcBlockCipher(aesEngine); PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(cbc); KeyParameter keySpec = new KeyParameter(key); ICipherParameters parameters = new ParametersWithIV(keySpec, IV); cipher.Init(true, parameters); using (FileStream fin = File.OpenRead(inFile), fout = File.Open(outFile, FileMode.Create)) { BinaryReader br = new BinaryReader(fin); BinaryWriter bw = new BinaryWriter(fout); int block = 0; //初始化缓冲区 byte[] decryptor_data = null; if (fin.Length > EnBufferLen) { decryptor_data = new byte[EnBufferLen]; } else { decryptor_data = new byte[fin.Length]; } while ((block = br.Read(decryptor_data, 0, decryptor_data.Length)) > 0) { if (decryptor_data.Length != block) { byte[] temp = new byte[block]; Buffer.BlockCopy(decryptor_data, 0, temp, 0, block); decryptor_data = temp; } // 开始处理编码 byte[] encrypted = new byte[cipher.GetOutputSize(decryptor_data.Length)]; int bytesProcessed1 = cipher.ProcessBytes(decryptor_data, 0, decryptor_data.Length, encrypted, 0); //保存进文件 int write_len = encrypted.Length; bw.Write(encrypted, 0, bytesProcessed1); } byte[] output = new byte[cipher.GetOutputSize(decryptor_data.Length)]; int bytesProcessed2 = cipher.DoFinal(output, 0); if (bytesProcessed2 > 0) { bw.Write(output, 0, bytesProcessed2); } br.Close(); bw.Close(); } }
/// <summary> /// Creates a new instance of AESCipher /// </summary> public AesCipher(bool forEncryption, byte[] key, byte[] iv) { IBlockCipher aes = new AesEngine(); IBlockCipher cbc = new CbcBlockCipher(aes); _bp = new PaddedBufferedBlockCipher(cbc); KeyParameter kp = new KeyParameter(key); ParametersWithIV piv = new ParametersWithIV(kp, iv); _bp.Init(forEncryption, piv); }
private void EncryptTunnelMessages(IEnumerable <TunnelDataMessage> msgs) { var cipher = new CbcBlockCipher(new AesEngine()); foreach (var msg in msgs) { msg.IV.AesEcbEncrypt(IVKey); cipher.Encrypt(LayerKey, msg.IV, msg.EncryptedWindow); msg.IV.AesEcbEncrypt(IVKey); } }
private static void InitializeEncryption() { if (cipher == null || keyParamWithIV == null) { DesEngine engine = new DesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); cipher = new PaddedBufferedBlockCipher(blockCipher); KeyParameter keyParam = new KeyParameter(GenerateArray(21)); keyParamWithIV = new ParametersWithIV(keyParam, GenerateArray(8), 0, 8); } }
internal static IBufferedCipher CreateBufferedCipher(string name, AlgorithmMode algorithmMode, IParametersWithIV <IParameters <Algorithm>, Algorithm> parameters, bool forEncryption, IEngineProvider <Internal.IBlockCipher> cipherProvider) { Internal.IBlockCipher baseCipher = cipherProvider.CreateEngine(GetUsage(forEncryption, algorithmMode)); Internal.IBlockCipher cipher; switch (algorithmMode) { case AlgorithmMode.CBC: cipher = new CbcBlockCipher(baseCipher); break; case AlgorithmMode.CS1: return(new NistCtsBlockCipher(NistCtsBlockCipher.CS1, baseCipher)); case AlgorithmMode.CS2: return(new NistCtsBlockCipher(NistCtsBlockCipher.CS2, baseCipher)); case AlgorithmMode.CS3: return(new NistCtsBlockCipher(NistCtsBlockCipher.CS3, baseCipher)); case AlgorithmMode.CFB8: cipher = new CfbBlockCipher(baseCipher, 8); break; case AlgorithmMode.CFB64: cipher = new CfbBlockCipher(baseCipher, 64); break; case AlgorithmMode.CFB128: cipher = new CfbBlockCipher(baseCipher, 128); break; case AlgorithmMode.OpenPGPCFB: cipher = new OpenPgpCfbBlockCipher(baseCipher); break; case AlgorithmMode.OFB64: cipher = new OfbBlockCipher(baseCipher, 64); break; case AlgorithmMode.OFB128: cipher = new OfbBlockCipher(baseCipher, 128); break; case AlgorithmMode.CTR: cipher = new SicBlockCipher(baseCipher); break; default: throw new ArgumentException("Unknown algorithm mode passed to " + name + ".Provider: " + algorithmMode); } return(new BufferedBlockCipher(cipher)); }
/// <summary> /// Encapsulates the specified links into a DLC container. /// </summary> /// <param name="name">The name of the package.</param> /// <param name="links">The links.</param> /// <returns> /// Base-64-encoded DLC container. /// </returns> public static string CreateDLC(string name, string[] links) { var sb = new StringBuilder(); sb.Append("<dlc>"); sb.Append("<header>"); sb.Append("<generator>"); sb.Append("<app>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("RS TV Show Tracker")) + "</app>"); sb.Append("<version>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("1.0")) + "</version>"); sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/")) + "</url>"); sb.Append("</generator>"); sb.Append("<dlcxmlversion>" + Convert.ToBase64String(Encoding.UTF8.GetBytes("20_02_2008")) + "</dlcxmlversion>"); sb.Append("</header>"); sb.Append("<content>"); sb.Append("<package name=\"" + Convert.ToBase64String(Encoding.UTF8.GetBytes(name)) + "\">"); foreach (var link in links) { sb.Append("<file>"); sb.Append("<url>" + Convert.ToBase64String(Encoding.UTF8.GetBytes(link)) + "</url>"); //sb.Append("<filename></filename>"); //sb.Append("<size></size>"); sb.Append("</file>"); } sb.Append("</package>"); sb.Append("</content>"); sb.Append("</dlc>"); var xml = Convert.ToBase64String(Encoding.UTF8.GetBytes(sb.ToString())); var key = BitConverter.ToString(new SHA256CryptoServiceProvider().ComputeHash(BitConverter.GetBytes(DateTime.Now.ToBinary()))).Replace("-", string.Empty).Substring(0, 16); var srv = Utils.GetURL(DLCCrypt, "&data=" + key + "&lid=" + Convert.ToBase64String(Encoding.UTF8.GetBytes("http://lab.rolisoft.net/_3600")) + "&version=1.0&client=rstvshowtracker"); var rcr = Regex.Match(srv, @"<rc>(.+)</rc>"); if (!rcr.Groups[1].Success) { throw new Exception("The jDownloader DLC encryption service did not return an encryption key."); } var enc = rcr.Groups[1].Value; var aes = new AesEngine(); var cbc = new CbcBlockCipher(aes); var zbp = new ZeroBytePadding(); var pad = new PaddedBufferedBlockCipher(cbc, zbp); pad.Init(true, new ParametersWithIV(new KeyParameter(Encoding.ASCII.GetBytes(key)), Encoding.ASCII.GetBytes(key))); var xm2 = Convert.ToBase64String(pad.DoFinal(Encoding.ASCII.GetBytes(xml))); return(xm2 + enc); }