/** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IesEngine(IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher) { _agree = agree; _kdf = kdf; _mac = mac; _macBuf = new byte[mac.GetMacSize()]; _cipher = cipher; }
public AesStream(byte[] data, byte[] key) : base(data) { EncryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8)); EncryptCipher.Init(true, new ParametersWithIV(new KeyParameter(key), key, 0, 16)); DecryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8)); DecryptCipher.Init(false, new ParametersWithIV(new KeyParameter(key), key, 0, 16)); var oldStream = this.BaseStream; this.BaseStream = new CipherStream(oldStream, DecryptCipher, EncryptCipher); }
/// <summary> /// Encrypt data with DES-CBC /// </summary> /// <param name="data">Data to encrypt</param> /// <param name="key">Key</param> /// <param name="iv">IV</param> /// <returns>Encrypted data</returns> public static byte[] EncryptCBC(byte[] data, byte[] key, byte[] iv) { byte[] enc = new byte[data.Length]; IBufferedCipher cipher = new BufferedBlockCipher(new CbcBlockCipher(new DesEngine())); ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length); cipher.Init(true, parameters); cipher.ProcessBytes(data, enc, 0); return(enc); }
public void InitEncryption(byte[] key, bool write) { EncryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8)); EncryptCipher.Init(true, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); DecryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesEngine(), 8)); DecryptCipher.Init(false, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); BaseStream = new CipherStream(BaseStream, DecryptCipher, EncryptCipher); }
/** * set up for use in conjunction with a block cipher to handle the * message. * * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param cipher the cipher to used for encrypting the message */ public IesEngine( IBasicAgreement agree, IDerivationFunction kdf, IMac mac, BufferedBlockCipher cipher) { this.agree = agree; this.kdf = kdf; this.mac = mac; this.macBuf = new byte[mac.GetMacSize()]; this.cipher = cipher; }
public AesCbcCryptor(byte[] key, byte[] iv) { KeyParameter keyParam = new KeyParameter(key); this._parametersWithIv = new ParametersWithIV(keyParam, iv, 0, iv.Length); AesEngine engine = new AesEngine(); CbcBlockCipher blockCipher = new CbcBlockCipher(engine); IBlockCipherPadding padding = new Pkcs7Padding(); this._cipher = new BufferedBlockCipher(blockCipher); this._cipher.Init(false, this._parametersWithIv); }
public byte[] DecryptDES3(byte[] message, byte[] key) { DesEdeEngine desedeEngine = new DesEdeEngine(); BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine); // Create the KeyParameter for the DES3 key generated. KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", key); byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)]; bufferedCipher.Init(false, keyparam); output = bufferedCipher.DoFinal(message); return(output); }
/// <summary> /// De/encrypt data via AES128-CBC without applying standarized /// padding (SmartGlass uses out-of-spec padding technique). /// </summary> /// <returns>The transformed data without padding.</returns> /// <param name="data">Data to transform.</param> /// <param name="initVector">Init vector.</param> /// <param name="encrypt">If set to <c>true</c> data is encrypted, <c>false</c> decrypts.</param> private byte[] UseAesCipherWithoutPadding(byte[] data, byte[] initVector, bool encrypt) { var aesCipher = new AesEngine(); var blockCipher = new CbcBlockCipher(aesCipher); var cipher = new BufferedBlockCipher(blockCipher); var keyParams = new KeyParameter(_cryptoKey); var paramsWithIv = new ParametersWithIV(keyParams, initVector); cipher.Init(encrypt, paramsWithIv); return(cipher.DoFinal(data)); }
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, byte[] key, byte[] iv) { try { this.mode.Init(forEncrypt, new ParametersWithIV(new KeyParameter(key), iv)); BufferedBlockCipher cipher = new BufferedBlockCipher(this.mode); return(cipher.DoFinal(input)); } catch (CryptoException) { throw; } }
private byte[] BouncyCastleCrypto(bool forEncrypt, byte[] input, byte[] key) { try { this.cipher = new BufferedBlockCipher(this.blockCipher); this.cipher.Init(forEncrypt, new KeyParameter(key)); return(this.cipher.DoFinal(input)); } catch (CryptoException) { throw; } }
/** * set up for use with stream mode, where the key derivation function * is used to provide a stream of bytes to xor with the message. * @param agree the key agreement used as the basis for the encryption * @param kdf the key derivation function used for byte generation * @param mac the message authentication code generator for the message * @param hash hash ing function * @param cipher the actual cipher */ public EthereumIesEngine( IBasicAgreement agreement, IDerivationFunction kdf, IMac mac, IDigest hash, BufferedBlockCipher cipher) { _agreement = agreement; _kdf = kdf; Mac = mac; _hash = hash; _macBuf = new byte[mac.GetMacSize()]; Cipher = cipher; }
//private private static byte[] encryptDecrypt(byte[] input, byte[] key, byte[] iv, BlockMode mode, BlockPadding padding, bool encrypt) { DesEdeEngine engine = new DesEdeEngine(); IBlockCipher cipherMode; BufferedBlockCipher cipher; KeyParameter keyP = new KeyParameter(key); ParametersWithIV keyParams = new ParametersWithIV(keyP, iv); if (mode == BlockMode.CBC) { cipherMode = new CbcBlockCipher(engine); } else if (mode == BlockMode.CFB) { cipherMode = new CfbBlockCipher(engine, iv.Length); } else if (mode == BlockMode.OFB) { cipherMode = new OfbBlockCipher(engine, iv.Length); } else { throw new Exception("mode must be a valid BlockMode."); } if (padding == BlockPadding.PKCS7Padding) { cipher = new PaddedBufferedBlockCipher(cipherMode, new Pkcs7Padding()); } else if (padding == BlockPadding.ZeroBytePadding) { cipher = new PaddedBufferedBlockCipher(cipherMode, new ZeroBytePadding()); } else if (padding == BlockPadding.NoPadding) { cipher = new BufferedBlockCipher(cipherMode); } else { throw new Exception("padding must be a valid BlockPadding."); } cipher.Init(encrypt, keyParams); byte[] output = new byte[cipher.GetOutputSize(input.Length)]; int length = cipher.ProcessBytes(input, output, 0); cipher.DoFinal(output, length); return(output); }
internal PbeTest( Pkcs5Test enclosingInstance, int id, BufferedBlockCipher cipher, byte[] sample, int keySize) { InitBlock(enclosingInstance); this.id = id; this.cipher = cipher; this.sample = sample; this.keySize = keySize; }
public byte[] Decrypt(byte[] key, byte[] iv, byte[] data) { //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding()); BufferedBlockCipher cipher = new BufferedBlockCipher(engine); //cipher.Init(false, new ParametersWithIV(new DesParameters(key), iv)); cipher.Init(false, new DesEdeParameters(key)); byte[] rv = new byte[cipher.GetOutputSize(data.Length)]; int tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0); cipher.DoFinal(rv, tam); return(rv); }
public static EncryptedPrivateKeyInfo createEncryptedPrivateKeyInfo( String algorithm, char[] passPhrase, byte[] salt, int iterationCount, PrivateKeyInfo keyInfo) { if (!PBEUtil.isPBEAlgorithm(algorithm)) { throw new Exception("attempt to use non-PBE algorithm with PBE EncryptedPrivateKeyInfo generation"); } ASN1Encodable parameters = PBEUtil.generateAlgorithmParameters(algorithm, salt, iterationCount); CipherParameters keyParameters = PBEUtil.generateCipherParameters(algorithm, passPhrase, parameters); byte[] encoding = null; Object engine = PBEUtil.createEngine(algorithm); if (engine is BufferedBlockCipher) { BufferedBlockCipher cipher = (BufferedBlockCipher)engine; cipher.init(true, keyParameters); byte[] keyBytes = keyInfo.getEncoded(); int encLen = cipher.getOutputSize(keyBytes.Length); encoding = new byte[encLen]; int off = cipher.processBytes(keyBytes, 0, keyBytes.Length, encoding, 0); cipher.doFinal(encoding, off); } else if (engine is StreamCipher) { StreamCipher cipher = (StreamCipher)engine; cipher.init(true, keyParameters); byte[] keyBytes = keyInfo.getEncoded(); encoding = new byte[keyBytes.Length]; cipher.processBytes(keyBytes, 0, keyBytes.Length, encoding, 0); } return(new EncryptedPrivateKeyInfo(new AlgorithmIdentifier(PBEUtil.getObjectIdentifier(algorithm), parameters), encoding)); }
public Packet ChannelEncrypt(ICipherSetRemoteInfo channelInfo, Packet inner) { var ci = (CS1ARemoteInfo)channelInfo; // TODO: Validate we don't care about endianess of IV here // Setup and encrypt the actual data byte[] aesIV = new byte[16]; Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, aesIV, 0, 4); Array.Clear(aesIV, 4, 12); var cipher = new SicBlockCipher(new AesFastEngine()); var parameters = new ParametersWithIV(new KeyParameter(ci.EncryptionKey), aesIV); cipher.Init(true, parameters); var encryptedInner = new byte[inner.FullPacket.Length]; BufferedBlockCipher bufferCipher = new BufferedBlockCipher(cipher); var offset = bufferCipher.ProcessBytes(inner.FullPacket, encryptedInner, 0); bufferCipher.DoFinal(encryptedInner, offset); // Hmac the output byte[] hmacKey = new byte[20]; Buffer.BlockCopy(ci.EncryptionKey, 0, hmacKey, 0, 16); Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, hmacKey, 16, 4); var hmac = new HMac(new Sha256Digest()); hmac.Init(new KeyParameter(hmacKey)); hmac.BlockUpdate(encryptedInner, 0, encryptedInner.Length); byte[] mac = new byte[hmac.GetMacSize()]; hmac.DoFinal(mac, 0); var foldedMac = Helpers.Fold(mac, 3); // Create the outgoing packet Packet outPacket = new Packet(); outPacket.Body = new byte[encryptedInner.Length + 24]; Buffer.BlockCopy(ci.Token, 0, outPacket.Body, 0, 16); Buffer.BlockCopy(BitConverter.GetBytes(ci.IV), 0, outPacket.Body, 16, 4); Buffer.BlockCopy(encryptedInner, 0, outPacket.Body, 20, encryptedInner.Length); Buffer.BlockCopy(foldedMac, 0, outPacket.Body, outPacket.Body.Length - 4, 4); // Next IV next packet ++ci.IV; return(outPacket); }
} //private byte[] encryptDesEde(byte[] plain) private byte[] encryptAES(byte[] plain, KeyChaining chaining = KeyChaining.CBC, bool doEncrypt = true, byte[] icv = null) { BufferedBlockCipher cipher = chaining == KeyChaining.CBC ? new BufferedBlockCipher(new CbcBlockCipher(new AesEngine())) //CBC chaining : new BufferedBlockCipher(new AesEngine()); //ECB chaining if (icv != null) { cipher.Init(doEncrypt, new ParametersWithIV(new KeyParameter(theKey), icv)); } else { cipher.Init(doEncrypt, new KeyParameter(theKey)); } MemoryStream dst = new MemoryStream(); byte[] bin = padded(plain, 24); byte[] result = new byte[bin.Length]; int outL = cipher.ProcessBytes(bin, result, 0); if (outL > 0) { dst.Write(result, 0, outL); } if (outL < plain.Length) { outL = cipher.DoFinal(result, 0); if (outL > 0) { dst.Write(result, 0, outL); } } //if (outL < plain.Length) dst.Position = 0; result = dst.ToArray(); dst.Close(); if (result.Length > plain.Length) { byte[] res = new byte[plain.Length]; System.Array.Copy(result, res, plain.Length); return(res); } //if (result.Length > plain.Length) return(result); } //private byte[] encryptAES(byte[] plain)
/// <summary> /// /// </summary> /// <param name="data"></param> /// <param name="key"></param> /// <returns></returns> public static byte[] ComputeCbc3Des(this byte[] data, KeyParameter key) { IBlockCipher engine = new DesEdeEngine(); var cipher = new BufferedBlockCipher(new CbcBlockCipher(engine)); cipher.Init(true, key); var cbc = new byte[cipher.GetOutputSize(data.Length)]; var length = cipher.ProcessBytes(data, 0, data.Length, cbc, 0); cipher.DoFinal(cbc, length); return(cbc); }
public KGcmBlockCipher(IBlockCipher cipher) { this.cipher = cipher; this.ctrCipher = new BufferedBlockCipher(new KCtrBlockCipher(this.cipher)); this.macSize = 0; this.IV = new byte[cipher.GetBlockSize()]; this.H = new byte[cipher.GetBlockSize()]; this.b = new byte[cipher.GetBlockSize()]; this.temp = new byte[cipher.GetBlockSize()]; this.lambda_c = 0; this.lambda_o = 0; }
/// <summary> /// Creates a symmetric encryptor/decryptor object using the specified key and initialization vector (IV). /// </summary> /// <param name="forEncryption">Flag used to determine what object, a symmetric encryptor or a symmetric decryptor method returns.</param> /// <returns>A symmetric encryptor/decryptor object.</returns> public IBufferedCipher CreateTwofishCipher(bool forEncryption) { IBufferedCipher cipher; var keyParameter = new KeyParameter(Key); ParametersWithIV keyWithIv = null; if (!ModeSignature.Equals("ECB")) { keyWithIv = new ParametersWithIV(keyParameter, IV); } switch (ModeSignature) { case "ECB": { cipher = new PaddedBufferedBlockCipher(new TwofishEngine()); cipher.Init(forEncryption, keyParameter); return(cipher); } case "CBC": { cipher = new PaddedBufferedBlockCipher(new CbcBlockCipher(new TwofishEngine())); cipher.Init(forEncryption, keyWithIv); return(cipher); } case "CFB": { cipher = new BufferedBlockCipher(new CfbBlockCipher(new TwofishEngine(), 16)); cipher.Init(forEncryption, keyWithIv); return(cipher); } case "OFB": { cipher = new BufferedBlockCipher(new OfbBlockCipher(new TwofishEngine(), 16)); cipher.Init(forEncryption, keyWithIv); return(cipher); } default: { throw new CryptographicException("Unknown block cipher mode '" + ModeSignature + "' used."); } } }
/// <summary> /// Encrypt stream with Blowfish-CBC /// </summary> /// <param name="input">Input stream to encrypt</param> /// <param name="output">Output stream</param> /// <param name="key">Key</param> /// <param name="iv">IV</param> /// <param name="paddingStyle">Padding</param> /// <param name="notifyProgression">Notify progression method</param> /// <param name="bufferSize">Buffer size</param> public static void EncryptCBC(Stream input, Stream output, byte[] key, byte[] iv, PaddingStyle paddingStyle = PaddingStyle.Pkcs7, Action <int> notifyProgression = null, int bufferSize = 4096) { IBufferedCipher cipher = new BufferedBlockCipher(new CbcBlockCipher(new BlowfishEngine())); ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(key, 0, key.Length), iv, 0, iv.Length); cipher.Init(true, parameters); bool padDone = false; int bytesRead; byte[] buffer = new byte[bufferSize]; byte[] enc = new byte[bufferSize]; do { bytesRead = input.Read(buffer, 0, bufferSize); if (bytesRead == bufferSize) { cipher.ProcessBytes(buffer, enc, 0); output.Write(enc, 0, bytesRead); } else if (bytesRead > 0) { byte[] smallBuffer = new byte[bytesRead]; Array.Copy(buffer, 0, smallBuffer, 0, bytesRead); byte[] padData = Padding.Pad(smallBuffer, BLOCK_SIZE, paddingStyle); cipher.ProcessBytes(padData, enc, 0); output.Write(enc, 0, padData.Length); padDone = true; } if (notifyProgression != null && bytesRead > 0) { notifyProgression(bytesRead); } } while (bytesRead == bufferSize); if (!padDone) { buffer = new byte[0]; byte[] padData = Padding.Pad(buffer, BLOCK_SIZE, paddingStyle); cipher.ProcessBytes(padData, enc, 0); output.Write(enc, 0, padData.Length); } }
private Byte[] Decrypt(BufferedBlockCipher cipher, Byte[] data) { var size = cipher.GetOutputSize(data.Length); var outBuffer = new Byte[size]; //int off1 = cipher.ProcessBytes(content, 0, content.Length, outBuffer, 0); cipher.DoFinal(data, 0, data.Length, outBuffer, 0); //int off2 = cipher.DoFinal(outBuffer, off1); //int resultSize = off1 + off2; var result = new Byte[outBuffer.Length /*resultSize*/]; Array.Copy(outBuffer, 0, result, 0, result.Length); //String asString = Encoding.ASCII.GetString(result); //Console.WriteLine(asString); return(result); }
public static byte[] Encrypt(string key, byte[] inBytes) { var cipher = new BufferedBlockCipher(new BlowfishEngine()); cipher.Init(true, new KeyParameter(Encoding.UTF8.GetBytes(key))); inBytes = BSwap(inBytes); var outBytes = new byte[cipher.GetOutputSize(inBytes.Length)]; var len2 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len2); outBytes = BSwap(outBytes); return(outBytes); }
public byte[] Decrypt(byte[] value) { BufferedBlockCipher aes = new BufferedBlockCipher(new OfbBlockCipher(new AesEngine(), AesBlockSizeInBytes * 8)); ArraySegment <byte> iv = new ArraySegment <byte>(value, 0, AesBlockSizeInBytes); ArraySegment <byte> secret = new ArraySegment <byte>(value, AesBlockSizeInBytes, value.Length - AesBlockSizeInBytes); ParametersWithIV ivAndKey = new ParametersWithIV(new KeyParameter(aesKey), iv.ToArray()); aes.Init(false, ivAndKey); int maximumSize = aes.GetOutputSize(secret.Count); byte[] outputBuffer = new byte[maximumSize]; int length1 = aes.ProcessBytes(secret.ToArray(), 0, secret.Count, outputBuffer, 0); int length2 = aes.DoFinal(outputBuffer, length1); return(new ArraySegment <byte>(outputBuffer, 0, length1 + length2).ToArray()); }
/* * No idea... doesnt work.. cant seem to fix it.. * * */ private static byte[] Transform(BufferedBlockCipher cipher, byte[] data) { var buf = new byte[cipher.GetOutputSize(data.Length)]; var length = cipher.ProcessBytes(data, 0, data.Length, buf, 0); try { length += cipher.DoFinal(buf, length); } catch (InvalidCipherTextException) { return(null); } var final = new byte[length]; Array.Copy(buf, final, length); return(final); }
public AesStream(Stream stream, byte[] key) { BaseStream = stream; Key = key; #if MONO encryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8)); encryptCipher.Init(true, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); decryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8)); decryptCipher.Init(false, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); #else var rijndael = GenerateAES(key); var encryptTransform = rijndael.CreateEncryptor(); var decryptTransform = rijndael.CreateDecryptor(); encryptStream = new CryptoStream(BaseStream, encryptTransform, CryptoStreamMode.Write); decryptStream = new CryptoStream(BaseStream, decryptTransform, CryptoStreamMode.Read); #endif }
public AESStream(Stream stream, byte[] key) { BaseStream = stream; Key = key; encryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8)); encryptCipher.Init(true, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); decryptCipher = new BufferedBlockCipher(new CfbBlockCipher(new AesFastEngine(), 8)); decryptCipher.Init(false, new ParametersWithIV( new KeyParameter(key), key, 0, 16)); }
public byte[] Encrypt(byte[] key, byte[] iv, byte[] data) { //BufferedBlockCipher cipher = new PaddedBufferedBlockCipher(engine, new ISO7816d4Padding()); //BufferedBlockCipher cipher = new BufferedGenericBlockCipher(cipher.getUnderlyingCipher(), new ISO7816d4Padding()); BufferedBlockCipher cipher = new BufferedBlockCipher(engine); //cipher.Init(true, new ParametersWithIV(new DesParameters(key), iv)); cipher.Init(true, new DesEdeParameters(key)); byte[] rv = new byte[cipher.GetOutputSize(data.Length)]; int tam = cipher.ProcessBytes(data, 0, data.Length, rv, 0); cipher.DoFinal(rv, tam); //BufferedBlockCipher bufferedCipher = new BufferedBlockCipher(desedeEngine); // Create the KeyParameter for the DES3 key generated. KeyParameter keyparam = ParameterUtilities.CreateKeyParameter("DESEDE", keyDES3); byte[] output = new byte[bufferedCipher.GetOutputSize(message.Length)]; bufferedCipher.Init(true, keyparam); output = bufferedCipher.DoFinal(message); return(rv); }
public static PrivateKeyInfo createPrivateKeyInfo( char[] passPhrase, EncryptedPrivateKeyInfo encInfo) { CipherParameters keyParameters = PBEUtil.generateCipherParameters(encInfo.getEncryptionAlgorithm().getObjectId(), passPhrase, encInfo.getEncryptionAlgorithm().getParameters()); Object engine = PBEUtil.createEngine(encInfo.getEncryptionAlgorithm().getObjectId()); byte[] encoding = null; if (engine is BufferedBlockCipher) { BufferedBlockCipher cipher = (BufferedBlockCipher)engine; cipher.init(false, keyParameters); byte[] keyBytes = encInfo.getEncryptedData(); int encLen = cipher.getOutputSize(keyBytes.Length); encoding = new byte[encLen]; int off = cipher.processBytes(keyBytes, 0, keyBytes.Length, encoding, 0); cipher.doFinal(encoding, off); } else if (engine is StreamCipher) { StreamCipher cipher = (StreamCipher)engine; cipher.init(false, keyParameters); byte[] keyBytes = encInfo.getEncryptedData(); encoding = new byte[keyBytes.Length]; cipher.processBytes(keyBytes, 0, keyBytes.Length, encoding, 0); } ASN1InputStream aIn = new ASN1InputStream(new MemoryStream(encoding)); return(PrivateKeyInfo.getInstance(aIn.readObject())); }
/// <summary> /// Creates a symmetric encryptor/decryptor object using the specified key and initialization vector (IV) for OFB block cipher mode of operation. /// </summary> /// <param name="forEncryption">Flag used to determine what object, a symmetric encryptor or a symmetric decryptor method returns.</param> /// <returns>A symmetric encryptor/decryptor object used for OFB block cipher mode of operation.</returns> public IBufferedCipher CreateTripleDesCipher(bool forEncryption) { IBufferedCipher cipher; var keyParameter = new KeyParameter(Key); var keyWithIv = new ParametersWithIV(keyParameter, IV); switch (ModeSignature) { case "OFB": { cipher = new BufferedBlockCipher(new OfbBlockCipher(new DesEdeEngine(), 8)); // DesEdeEngine or Triple DES engine cipher.Init(forEncryption, keyWithIv); return cipher; } default: { throw new CryptographicException("Unknown block cipher mode '" + ModeSignature + "' used."); } } }
private static byte[] DecryptAes(Stream inputStream, BufferedBlockCipher cipher, long length) { int blockSize = cipher.GetBlockSize(); int inputLength = (int)length; int paddedLength = inputLength; if (paddedLength % blockSize > 0) { paddedLength += blockSize - paddedLength % blockSize; } byte[] input = new byte[paddedLength]; byte[] output = new byte[cipher.GetOutputSize(paddedLength)]; inputStream.Read(input, 0, inputLength); int len = cipher.ProcessBytes(input, 0, input.Length, output, 0); cipher.DoFinal(output, len); return(output); }
public override void PerformTest() { base.PerformTest(); //advanced tests with Gost28147KeyGenerator: //encrypt on hesh message; ECB mode: byte[] inBytes = Hex.Decode("4e6f77206973207468652074696d6520666f7220616c6c20"); byte[] output = Hex.Decode("8ad3c8f56b27ff1fbd46409359bdc796bc350e71aac5f5c0"); byte[] outBytes = new byte[inBytes.Length]; byte[] key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! // System.out.println(new string(Hex.Encode(key))); ICipherParameters param = new ParametersWithSBox(new KeyParameter(key), Gost28147Engine.GetSBox("E-A")); //CipherParameters param = new Gost28147Parameters(key,"D-Test"); BufferedBlockCipher cipher = new BufferedBlockCipher(new Gost28147Engine()); cipher.Init(true, param); int len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); try { cipher.DoFinal(outBytes, len1); } catch (CryptoException e) { Fail("failed - exception " + e.ToString(), e); } if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; CFB mode: inBytes = Hex.Decode("bc350e71aac5f5c2"); output = Hex.Decode("0ebbbafcf38f14a5"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")); //IV cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64)); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); try { cipher.DoFinal(outBytes, len1); } catch (CryptoException e) { Fail("failed - exception " + e.ToString(), e); } if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; CFB mode: inBytes = Hex.Decode("000102030405060708090a0b0c0d0e0fff0102030405060708090a0b0c0d0e0f"); output = Hex.Decode("64988982819f0a1655e226e19ecad79d10cc73bac95c5d7da034786c12294225"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("aafd12f659cae63489b479e5076ddec2f06cb58faafd12f659cae63489b479e5")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("aafd12f659cae634")); //IV cipher = new BufferedBlockCipher(new CfbBlockCipher(new Gost28147Engine(), 64)); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len1); if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } //encrypt on hesh message; OFB mode: inBytes = Hex.Decode("bc350e71aa11345709acde"); output = Hex.Decode("1bcc2282707c676fb656dc"); outBytes = new byte[inBytes.Length]; key = generateKey(Hex.Decode("0123456789abcdef")); //!!! heshing start_key - get 256 bits !!! param = new ParametersWithIV( new ParametersWithSBox( new KeyParameter(key), //key Gost28147Engine.GetSBox("E-A")), //type S-box Hex.Decode("1234567890abcdef")); //IV cipher = new BufferedBlockCipher(new GOfbBlockCipher(new Gost28147Engine())); cipher.Init(true, param); len1 = cipher.ProcessBytes(inBytes, 0, inBytes.Length, outBytes, 0); cipher.DoFinal(outBytes, len1); if (outBytes.Length != output.Length) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } for (int i = 0; i != outBytes.Length; i++) { if (outBytes[i] != output[i]) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } } }
private IBufferedCipher createCipher(bool forEncryption) { // IBufferedCipher cipher = CipherUtilities.GetCipher("AES/CFB/NoPadding"); IBlockCipher blockCipher = new AesEngine(); int bits = 8 * blockCipher.GetBlockSize(); // TODO Is this right? blockCipher = new CfbBlockCipher(blockCipher, bits); IBufferedCipher cipher = new BufferedBlockCipher(blockCipher); // SecureRandom random = new SecureRandom(); byte[] keyBytes = new byte[32]; //random.NextBytes(keyBytes); KeyParameter key = new KeyParameter(keyBytes); byte[] iv = new byte[cipher.GetBlockSize()]; //random.NextBytes(iv); cipher.Init(forEncryption, new ParametersWithIV(key, iv)); return cipher; }