public ITestResult Perform() { cipher.Init(true, param); byte[] outBytes = new byte[input.Length]; cipher.ProcessBytes(input, 0, input.Length, outBytes, 0); if (!Arrays.AreEqual(outBytes, output)) { return(new SimpleTestResult(false, Name + ": failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes))); } cipher.Init(false, param); cipher.ProcessBytes(output, 0, output.Length, outBytes, 0); if (!Arrays.AreEqual(input, outBytes)) { return(new SimpleTestResult(false, Name + ": failed reversal")); } return(new SimpleTestResult(true, Name + ": OKAY")); }
private void RunVector(IStreamCipher hc, string fileName, PeekableLineReader r, string vectorName) { // Console.WriteLine(fileName + " => " + vectorName); string hexKey = ReadBlock(r); string hexIV = ReadBlock(r); ICipherParameters cp = new KeyParameter(Hex.Decode(hexKey)); cp = new ParametersWithIV(cp, Hex.Decode(hexIV)); hc.Init(true, cp); byte[] input = new byte[64]; byte[] output = new byte[64]; byte[] digest = new byte[64]; int pos = 0; for (;;) { string line1 = r.PeekLine().Trim(); int equalsPos = line1.IndexOf('='); string lead = line1.Substring(0, equalsPos - 1); string hexData = ReadBlock(r); byte[] data = Hex.Decode(hexData); if (lead.Equals("xor-digest")) { if (!Arrays.AreEqual(data, digest)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } break; } int posA = lead.IndexOf('['); int posB = lead.IndexOf(".."); int posC = lead.IndexOf(']'); int start = Int32.Parse(lead.Substring(posA + 1, posB - (posA + 1))); int end = Int32.Parse(lead.Substring(posB + 2, posC - (posB + 2))); if (start % 64 != 0 || (end - start != 63)) { throw new InvalidOperationException(vectorName + ": " + lead + " not on 64 byte boundaries"); } while (pos < end) { hc.ProcessBytes(input, 0, input.Length, output, 0); xor(digest, output); pos += 64; } if (!Arrays.AreEqual(data, output)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } } }
public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher, IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); if (offset != prfSize) throw new TlsFatalAlert(AlertDescription.internal_error); // Init Ciphers encryptCipher.Init(true, encryptKey); decryptCipher.Init(false, decryptKey); }
public TlsStreamCipher(TlsClientContext context, IStreamCipher encryptCipher, IStreamCipher decryptCipher, IDigest writeDigest, IDigest readDigest, int cipherKeySize) { this.context = context; this.encryptCipher = encryptCipher; this.decryptCipher = decryptCipher; int prfSize = (2 * cipherKeySize) + writeDigest.GetDigestSize() + readDigest.GetDigestSize(); SecurityParameters securityParameters = context.SecurityParameters; byte[] keyBlock = TlsUtilities.PRF(securityParameters.masterSecret, "key expansion", TlsUtilities.Concat(securityParameters.serverRandom, securityParameters.clientRandom), prfSize); int offset = 0; // Init MACs writeMac = CreateTlsMac(writeDigest, keyBlock, ref offset); readMac = CreateTlsMac(readDigest, keyBlock, ref offset); // Build keys KeyParameter encryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); KeyParameter decryptKey = CreateKeyParameter(keyBlock, ref offset, cipherKeySize); if (offset != prfSize) { throw new TlsFatalAlert(AlertDescription.internal_error); } // Init Ciphers encryptCipher.Init(true, encryptKey); decryptCipher.Init(false, decryptKey); }
/// <summary> /// Creates a new instance of the <see cref="Secio1Stream"/> class. /// </summary> /// <param name="stream"> /// The source/destination of SECIO packets. /// </param> /// <param name="cipherName"> /// The cipher for the <paramref name="stream"/>, such as AES-256 or AES-128. /// </param> /// <param name="hashName"> /// The hash for the <paramref name="stream"/>, such as SHA256. /// </param> /// <param name="localKey"> /// The keys used by the local endpoint. /// </param> /// <param name="remoteKey"> /// The keys used by the remote endpoint. /// </param> public Secio1Stream( Stream stream, string cipherName, string hashName, StretchedKey localKey, StretchedKey remoteKey) { this.stream = stream; inHmac = new HMac(DigestUtilities.GetDigest(hashName)); inHmac.Init(new KeyParameter(localKey.MacKey)); outHmac = new HMac(DigestUtilities.GetDigest(hashName)); outHmac.Init(new KeyParameter(remoteKey.MacKey)); if (cipherName == "AES-256" || cipherName == "AES-512") { decrypt = new CtrStreamCipher(new AesEngine()); var p = new ParametersWithIV(new KeyParameter(remoteKey.CipherKey), remoteKey.IV); decrypt.Init(false, p); encrypt = new CtrStreamCipher(new AesEngine()); p = new ParametersWithIV(new KeyParameter(localKey.CipherKey), localKey.IV); encrypt.Init(true, p); } else { throw new NotSupportedException($"Cipher '{cipherName}' is not supported."); } }
public override void Init(bool forEncryption, ICipherParameters parameters) { if (parameters is ParametersWithRandom) { parameters = ((ParametersWithRandom)parameters).Parameters; } cipher.Init(forEncryption, parameters); }
public TlsStreamCipher(TlsContext context, IStreamCipher clientWriteCipher, IStreamCipher serverWriteCipher, IDigest clientWriteDigest, IDigest serverWriteDigest, int cipherKeySize, bool usesNonce) { bool isServer = context.IsServer; this.context = context; this.usesNonce = usesNonce; encryptCipher = clientWriteCipher; decryptCipher = serverWriteCipher; int num = 2 * cipherKeySize + clientWriteDigest.GetDigestSize() + serverWriteDigest.GetDigestSize(); byte[] key = TlsUtilities.CalculateKeyBlock(context, num); int num2 = 0; TlsMac tlsMac = new TlsMac(context, clientWriteDigest, key, num2, clientWriteDigest.GetDigestSize()); num2 += clientWriteDigest.GetDigestSize(); TlsMac tlsMac2 = new TlsMac(context, serverWriteDigest, key, num2, serverWriteDigest.GetDigestSize()); num2 += serverWriteDigest.GetDigestSize(); KeyParameter keyParameter = new KeyParameter(key, num2, cipherKeySize); num2 += cipherKeySize; KeyParameter keyParameter2 = new KeyParameter(key, num2, cipherKeySize); num2 += cipherKeySize; if (num2 != num) { throw new TlsFatalAlert(80); } ICipherParameters parameters; ICipherParameters parameters2; if (isServer) { writeMac = tlsMac2; readMac = tlsMac; encryptCipher = serverWriteCipher; decryptCipher = clientWriteCipher; parameters = keyParameter2; parameters2 = keyParameter; } else { writeMac = tlsMac; readMac = tlsMac2; encryptCipher = clientWriteCipher; decryptCipher = serverWriteCipher; parameters = keyParameter; parameters2 = keyParameter2; } if (usesNonce) { byte[] iv = new byte[8]; parameters = new ParametersWithIV(parameters, iv); parameters2 = new ParametersWithIV(parameters2, iv); } encryptCipher.Init(forEncryption: true, parameters); decryptCipher.Init(forEncryption: false, parameters2); }
private void ProcessStream(string InputPath, string OutputPath, MemoryStream Header = null) { using (BinaryReader inputReader = new BinaryReader(new FileStream(InputPath, FileMode.Open, FileAccess.Read, FileShare.None))) { int blockSize = (DCS_BLOCK * 4); long bytesRead = 0; long bytesTotal = 0; if (inputReader.BaseStream.Length < blockSize) { blockSize = (int)inputReader.BaseStream.Length; } using (BinaryWriter outputWriter = new BinaryWriter(new FileStream(OutputPath, FileMode.Create, FileAccess.Write, FileShare.None))) { byte[] inputBuffer = new byte[blockSize]; byte[] outputBuffer = new byte[blockSize]; if (Header != null) { outputWriter.Write(Header.ToArray()); } else { inputReader.BaseStream.Position = MessageHeader.GetHeaderSize; } // initialize the cipher StreamCipher.Init(new KeyParams(this.Key, this.IV)); // loop through file while ((bytesRead = inputReader.Read(inputBuffer, 0, blockSize)) == blockSize) { StreamCipher.Transform(inputBuffer, outputBuffer); outputWriter.Write(outputBuffer); bytesTotal += bytesRead; if (bytesTotal % this.ProgressInterval == 0) { CalculateProgress(bytesTotal); } } // last block if (bytesRead > 0) { outputBuffer = new byte[bytesRead]; StreamCipher.Transform(inputBuffer, outputBuffer); outputWriter.Write(outputBuffer); CalculateProgress(bytesTotal + bytesRead); } } } }
public void InitCrypto() { _dec = new Salsa20Engine(); _dec.Init(false, new ParametersWithIV(new KeyParameter(_salsaKey02), _salsaIV02)); _enc = new Salsa20Engine(); _enc.Init(true, new ParametersWithIV(new KeyParameter(_salsaKey01), _salsaIV01)); _dStream = new ZStream(); _dStream.deflateInit(-1, -15); _iStream = new ZStream(); _iStream.inflateInit(-15); }
private void HCTest(IStreamCipher hc, string test, byte[] key, byte[] IV, byte[] expected) { KeyParameter kp = new KeyParameter(key); ParametersWithIV ivp = new ParametersWithIV(kp, IV); hc.Init(true, ivp); for (int i = 0; i < 64; i++) { if (hc.ReturnByte(MSG[i]) != expected[i]) { Fail(test + " failure at byte " + i); } } }
public override void PerformTest() { cipher.Init(true, param); byte[] outBytes = new byte[input.Length]; cipher.ProcessBytes(input, 0, input.Length, outBytes, 0); if (!Arrays.AreEqual(outBytes, output)) { Fail("failed - " + "expected " + Hex.ToHexString(output) + " got " + Hex.ToHexString(outBytes)); } cipher.Init(false, param); cipher.ProcessBytes(output, 0, output.Length, outBytes, 0); if (!Arrays.AreEqual(input, outBytes)) { Fail("failed reversal"); } }
private void TestReset(IStreamCipher cipher1, IStreamCipher cipher2, ICipherParameters cipherParams) { cipher1.Init(true, cipherParams); byte[] plaintext = new byte[1023]; byte[] ciphertext = new byte[plaintext.Length]; // Establish baseline answer cipher1.ProcessBytes(plaintext, 0, plaintext.Length, ciphertext, 0); // Test encryption resets CheckReset(cipher1, cipherParams, true, plaintext, ciphertext); // Test decryption resets with fresh instance cipher2.Init(false, cipherParams); CheckReset(cipher2, cipherParams, false, ciphertext, plaintext); }
public void InitCrypto() { Console.WriteLine("Initialized decrypters and inflaters!"); _dec01 = new Salsa20Engine(); _dec01.Init(false, new ParametersWithIV(new KeyParameter(Key02), IV02)); _dec02 = new Salsa20Engine(); _dec02.Init(false, new ParametersWithIV(new KeyParameter(Key01), IV01)); _iStream01 = new ZStream(); _iStream01.inflateInit(-15); _iStream02 = new ZStream(); _iStream02.inflateInit(-15); CryptoInit = true; }
private void CheckReset(IStreamCipher cipher, ICipherParameters cipherParams, bool encrypt, byte[] pretext, byte[] posttext) { // Do initial run byte[] output = new byte[posttext.Length]; cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); // Check encrypt resets cipher cipher.Init(encrypt, cipherParams); try { cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); } catch (Exception e) { Fail(cipher.AlgorithmName + " init did not reset: " + e.Message); } if (!Arrays.AreEqual(output, posttext)) { Fail(cipher.AlgorithmName + " init did not reset.", Hex.ToHexString(posttext), Hex.ToHexString(output)); } // Check reset resets data cipher.Reset(); try { cipher.ProcessBytes(pretext, 0, pretext.Length, output, 0); } catch (Exception e) { Fail(cipher.AlgorithmName + " reset did not reset: " + e.Message); } if (!Arrays.AreEqual(output, posttext)) { Fail(cipher.AlgorithmName + " reset did not reset."); } }
protected virtual void UpdateIV(IStreamCipher cipher, bool forEncryption, long seqNo) { byte[] nonce = new byte[8]; TlsUtilities.WriteUint64(seqNo, nonce, 0); cipher.Init(forEncryption, new ParametersWithIV(null, nonce)); }
public override void Init( bool forEncryption, ICipherParameters parameters) { cipher.Init(forEncryption, parameters); }
protected virtual KeyParameter InitRecord(IStreamCipher cipher, bool forEncryption, long seqNo, byte[] iv) { byte[] nonce = CalculateNonce(seqNo, iv); cipher.Init(forEncryption, new ParametersWithIV(null, nonce)); return GenerateRecordMacKey(cipher); }
protected virtual KeyParameter InitRecord(IStreamCipher cipher, bool forEncryption, long seqNo, byte[] iv) { byte[] nonce = CalculateNonce(seqNo, iv); cipher.Init(forEncryption, new ParametersWithIV(null, nonce)); return(GenerateRecordMacKey(cipher)); }
private void RunVector(IStreamCipher hc, string fileName, PeekableLineReader r, string vectorName) { // Console.WriteLine(fileName + " => " + vectorName); string hexKey = ReadBlock(r); string hexIV = ReadBlock(r); ICipherParameters cp = new KeyParameter(Hex.Decode(hexKey)); cp = new ParametersWithIV(cp, Hex.Decode(hexIV)); hc.Init(true, cp); byte[] input = new byte[64]; byte[] output = new byte[64]; byte[] digest = new byte[64]; int pos = 0; for (;;) { string line1 = r.PeekLine().Trim(); int equalsPos = line1.IndexOf('='); string lead = line1.Substring(0, equalsPos - 1); string hexData = ReadBlock(r); byte[] data = Hex.Decode(hexData); if (lead.Equals("xor-digest")) { if (!Arrays.AreEqual(data, digest)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } break; } int posA = lead.IndexOf('['); int posB = lead.IndexOf(".."); int posC = lead.IndexOf(']'); int start = Int32.Parse(lead.Substring(posA + 1, posB - (posA + 1))); int end = Int32.Parse(lead.Substring(posB + 2, posC - (posB + 2))); if (start % 64 != 0 || (end - start != 63)) throw new InvalidOperationException(vectorName + ": " + lead + " not on 64 byte boundaries"); while (pos < end) { hc.ProcessBytes(input, 0, input.Length, output, 0); xor(digest, output); pos += 64; } if (!Arrays.AreEqual(data, output)) { Fail("Failed in " + fileName + " for test vector: " + vectorName + " at " + lead); // Console.WriteLine(fileName + " => " + vectorName + " failed at " + lead); return; } } }
public string DoEncrypt(string symmetricStreamAlgorithm, string key, string IV, string plainText) { this.GetError().cleanError(); SymmetricStreamAlgorithm algorithm = SymmetricStreamAlgorithmUtils.getSymmetricStreamAlgorithm(symmetricStreamAlgorithm, this.GetError()); if (this.GetError().existsError()) { return(""); } IStreamCipher engine = getCipherEngine(algorithm); if (this.GetError().existsError()) { return(""); } /* KeyParameter keyParam = new KeyParameter(Hex.Decode(key)); * engine.Init(true, keyParam);*/ byte[] keyBytes = SecurityUtils.GetHexa(key, "SS007", this.error); byte[] ivBytes = SecurityUtils.GetHexa(IV, "SS007", this.error); if (this.HasError()) { return(""); } KeyParameter keyParam = new KeyParameter(keyBytes); if (SymmetricStreamAlgorithmUtils.usesIV(algorithm, this.GetError())) { if (!this.GetError().existsError()) { ParametersWithIV keyParamWithIV = new ParametersWithIV(keyParam, ivBytes); try { engine.Init(false, keyParamWithIV); }catch (Exception e) { this.error.setError("SS008", e.Message); return(""); } } } else { try { engine.Init(false, keyParam); }catch (Exception e) { this.error.setError("SS009", e.Message); return(""); } } EncodingUtil eu = new EncodingUtil(); byte[] input = eu.getBytes(plainText); if (eu.GetError().existsError()) { this.error = eu.GetError(); return(""); } byte[] output = new byte[input.Length]; engine.ProcessBytes(input, 0, input.Length, output, 0); if (output == null || output.Length == 0) { this.GetError().setError("SS004", "Stream encryption exception"); return(""); } this.GetError().cleanError(); return(Base64.ToBase64String(output)); }