Пример #1
0
        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"));
        }
Пример #2
0
 public override byte[] ProcessBytes(byte[] input, int inOff, int length)
 {
     if (length < 1)
     {
         return(null);
     }
     byte[] array = new byte[length];
     cipher.ProcessBytes(input, inOff, length, array, 0);
     return(array);
 }
Пример #3
0
        public byte[] EncodePlaintext(byte type, byte[] plaintext, int offset, int len)
        {
            byte[] mac  = writeMac.CalculateMac(type, plaintext, offset, len);
            int    size = len + mac.Length;

            byte[] outbuf = new byte[size];

            encryptCipher.ProcessBytes(plaintext, offset, len, outbuf, 0);
            encryptCipher.ProcessBytes(mac, 0, mac.Length, outbuf, len);

            return(outbuf);
        }
 public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
 {
     if (usesNonce)
     {
         UpdateIV(encryptCipher, forEncryption: true, seqNo);
     }
     byte[] array = new byte[len + writeMac.Size];
     encryptCipher.ProcessBytes(plaintext, offset, len, array, 0);
     byte[] array2 = writeMac.CalculateMac(seqNo, type, plaintext, offset, len);
     encryptCipher.ProcessBytes(array2, 0, array2.Length, array, len);
     return(array);
 }
Пример #5
0
		public override byte[] ProcessBytes(
			byte[]	input,
			int		inOff,
			int		length)
		{
			if (length < 1)
				return null;

			byte[] output = new byte[length];
			cipher.ProcessBytes(input, inOff, length, output, 0);
			return output;
		}
Пример #6
0
 public byte[] Finalize(IStreamCipher pEncryptor)
 {
     //Log.Write(LogLevel.Warning, "\n{0}", this.Data.ToHEX(this.Data.Length));
     byte[] oData = new byte[Data.Length];
     pEncryptor.ProcessBytes(Data, 0, Data.Length, oData, 0);
     return(oData);
 }
        public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
        {
            if (usesNonce)
            {
                UpdateIV(encryptCipher, true, seqNo);
            }

            byte[] outBuf = new byte[len + writeMac.Size];

            encryptCipher.ProcessBytes(plaintext, offset, len, outBuf, 0);

            byte[] mac = writeMac.CalculateMac(seqNo, type, plaintext, offset, len);
            encryptCipher.ProcessBytes(mac, 0, mac.Length, outBuf, len);

            return(outBuf);
        }
Пример #8
0
        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;
                }
            }
        }
Пример #9
0
        /// <exception cref="IOException"></exception>
        public virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
        {
            /*
             * draft-josefsson-salsa20-tls-04 2.1 Note that Salsa20 requires a 64-bit nonce. That
             * nonce is updated on the encryption of every TLS record, and is set to be the 64-bit TLS
             * record sequence number. In case of DTLS the 64-bit nonce is formed as the concatenation
             * of the 16-bit epoch with the 48-bit sequence number.
             */
            if (usesNonce)
            {
                UpdateIV(decryptCipher, false, seqNo);
            }

            int macSize = readMac.Size;

            if (len < macSize)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            int plaintextLength = len - macSize;

            byte[] deciphered = new byte[len];
            decryptCipher.ProcessBytes(ciphertext, offset, len, deciphered, 0);
            CheckMac(seqNo, type, deciphered, plaintextLength, len, deciphered, 0, plaintextLength);
            return(Arrays.CopyOfRange(deciphered, 0, plaintextLength));
        }
Пример #10
0
        protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
        {
            byte[] input = new byte[0x40];
            cipher.ProcessBytes(input, 0, input.Length, input, 0);
            KeyParameter parameter = new KeyParameter(input, 0, 0x20);

            Arrays.Fill(input, 0);
            return(parameter);
        }
        protected static KeyParameter GenerateRecordMacKey(IStreamCipher cipher, byte[] firstBlock)
        {
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            KeyParameter macKey = new KeyParameter(firstBlock, 0, 32);

            Arrays.Fill(firstBlock, (byte)0);
            return(macKey);
        }
Пример #12
0
        protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
        {
            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            KeyParameter macKey = new KeyParameter(firstBlock, 0, 32);

            Arrays.Fill(firstBlock, (byte)0);
            return(macKey);
        }
Пример #13
0
        public virtual BufferSegment EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
        {
            if (usesNonce)
            {
                UpdateIV(encryptCipher, true, seqNo);
            }

            int outBufLength = len + writeMac.Size;

            byte[] outBuf = BufferPool.Get(outBufLength, true);

            encryptCipher.ProcessBytes(plaintext, offset, len, outBuf, 0);

            BufferSegment mac = writeMac.CalculateMac(seqNo, type, plaintext, offset, len);

            encryptCipher.ProcessBytes(mac.Data, mac.Offset, mac.Count, outBuf, len);

            BufferPool.Release(mac);

            return(new BufferSegment(outBuf, 0, outBufLength));
        }
Пример #14
0
        protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
        {
            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            // NOTE: The BC implementation puts 'r' after 'k'
            Array.Copy(firstBlock, 0, firstBlock, 32, 16);
            Poly1305KeyGenerator.Clamp(firstBlock, 16);
            KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);

            Arrays.Fill(firstBlock, (byte)0);
            return(macKey);
        }
Пример #15
0
        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.");
            }
        }
Пример #16
0
        public virtual byte[] EncodePlaintext(long seqNo, byte type, byte[] plaintext, int offset, int len)
        {
            /*
             * draft-josefsson-salsa20-tls-04 2.1 Note that Salsa20 requires a 64-bit nonce. That
             * nonce is updated on the encryption of every TLS record, and is set to be the 64-bit TLS
             * record sequence number. In case of DTLS the 64-bit nonce is formed as the concatenation
             * of the 16-bit epoch with the 48-bit sequence number.
             */
            if (usesNonce)
            {
                UpdateIV(encryptCipher, true, seqNo);
            }

            byte[] outBuf = new byte[len + writeMac.Size];

            encryptCipher.ProcessBytes(plaintext, offset, len, outBuf, 0);

            byte[] mac = writeMac.CalculateMac(seqNo, type, plaintext, offset, len);
            encryptCipher.ProcessBytes(mac, 0, mac.Length, outBuf, len);

            return(outBuf);
        }
        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");
            }
        }
Пример #18
0
        public byte[] Construct(IStreamCipher encryptor, ZStream dStream)
        {
            Log.Write(LogLevel.Client, "Constructing Packet [{0}]", GetType().ToString());

            byte[] cData = _stream.ToArray();

            //Log.Write(LogLevel.Error, "{0}", cData.ToHEX());

            if (_def)
            {
                MemoryStream lStream = new MemoryStream();

                dStream.avail_in      = cData.Length;
                dStream.next_in       = cData;
                dStream.next_in_index = 0;

                byte[] dData = new byte[cData.Length * 2];

                dStream.avail_out      = cData.Length * 2;
                dStream.next_out       = dData;
                dStream.next_out_index = 0;

                dStream.deflate(2);

                lStream.Write(dData, 0, (cData.Length * 2) - dStream.avail_out);
                cData = lStream.ToArray();
                lStream.Dispose();
            }

            MemoryStream       oStream = new MemoryStream();
            EndianBinaryWriter oWriter = new EndianBinaryWriter(MiscUtil.Conversion.EndianBitConverter.Little, oStream);

            oWriter.Write((byte)GetModule());
            oWriter.Write((UInt32)cData.Length + 2);
            oWriter.Write((byte)GenerateChecksum(oStream.ToArray()));
            oWriter.Write(cData, 0, cData.Length - 4);

            byte[] fData = oStream.ToArray();

            if (_enc)
            {
                byte[] eData = new byte[fData.Length];
                encryptor.ProcessBytes(fData, 0, fData.Length, eData, 0);
                fData = eData;
            }

            return(fData);
        }
Пример #19
0
        protected static KeyParameter GenerateRecordMacKey(IStreamCipher cipher, byte[] firstBlock)
        {
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            if (_macKey == null)
            {
                _macKey = new KeyParameter(firstBlock, 0, 32);
            }
            else
            {
                _macKey.Reset();
                _macKey.SetKey(firstBlock, 0, 32);
            }

            Arrays.Fill(firstBlock, (byte)0);
            return(_macKey);
        }
Пример #20
0
        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);
        }
Пример #21
0
        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 virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
    {
        if (usesNonce)
        {
            UpdateIV(decryptCipher, forEncryption: false, seqNo);
        }
        int size = readMac.Size;

        if (len < size)
        {
            throw new TlsFatalAlert(50);
        }
        int num = len - size;

        byte[] array = new byte[len];
        decryptCipher.ProcessBytes(ciphertext, offset, len, array, 0);
        CheckMac(seqNo, type, array, num, len, array, 0, num);
        return(Arrays.CopyOfRange(array, 0, num));
    }
Пример #23
0
        public byte[] DecodeCiphertext(byte type, byte[] ciphertext, int offset, int len)
        {
            byte[] deciphered = new byte[len];
            decryptCipher.ProcessBytes(ciphertext, offset, len, deciphered, 0);

            int plaintextSize = deciphered.Length - readMac.Size;

            byte[] plainText = CopyData(deciphered, 0, plaintextSize);

            byte[] receivedMac = CopyData(deciphered, plaintextSize, readMac.Size);
            byte[] computedMac = readMac.CalculateMac(type, plainText, 0, plainText.Length);

            if (!Arrays.ConstantTimeAreEqual(receivedMac, computedMac))
            {
                throw new TlsFatalAlert(AlertDescription.bad_record_mac);
            }

            return(plainText);
        }
        /// <exception cref="IOException"></exception>
        public virtual byte[] DecodeCiphertext(long seqNo, byte type, byte[] ciphertext, int offset, int len)
        {
            if (usesNonce)
            {
                UpdateIV(decryptCipher, false, seqNo);
            }

            int macSize = readMac.Size;

            if (len < macSize)
            {
                throw new TlsFatalAlert(AlertDescription.decode_error);
            }

            int plaintextLength = len - macSize;

            byte[] deciphered = new byte[len];
            decryptCipher.ProcessBytes(ciphertext, offset, len, deciphered, 0);
            CheckMac(seqNo, type, deciphered, plaintextLength, len, deciphered, 0, plaintextLength);
            return(Arrays.CopyOfRange(deciphered, 0, plaintextLength));
        }
Пример #25
0
        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.");
            }
        }
Пример #26
0
        public PacketStream(List <byte[]> inPack, IStreamCipher Decryptor, ZStream Inflater)
        {
            Packets = new List <Packet>();

            byte[] inBuff = inPack[0];

            byte[] decData = new byte[inBuff.Length];

            Decryptor.ProcessBytes(inBuff, 0, inBuff.Length, decData, 0);

            MemoryStream       IStream = new MemoryStream(decData);
            EndianBinaryReader IReader = new EndianBinaryReader(MiscUtil.Conversion.BigEndianBitConverter.Little, IStream);

            int remLength = decData.Length;

            do
            {
                byte Module    = IReader.ReadByte();
                int  pLength   = IReader.ReadInt32();
                int  pChecksum = IReader.ReadByte();

                if (VerifyChecksum(decData, pChecksum, (int)IReader.BaseStream.Position - 6))
                {
                    byte[] Data;

                    if (inPack.Count > 1)
                    {
                        // Multipart packet
                        byte[] NewBuff  = new byte[pLength - 6];
                        int    curIndex = remLength - 6;
                        Array.Copy(IReader.ReadBytes(remLength - 6), 0, NewBuff, 0, remLength - 6);
                        for (int i = 1; i < inPack.Count; i++)
                        {
                            byte[] packDec = new byte[inPack[i].Length];
                            Decryptor.ProcessBytes(inPack[i], 0, inPack[i].Length, packDec, 0);
                            Array.Copy(packDec, 0, NewBuff, curIndex, packDec.Length);
                            curIndex += packDec.Length;
                        }
                        Data = NewBuff;
                    }
                    else
                    {
                        Data = IReader.ReadBytes(pLength - 6);
                    }

                    Packet iPacket = new Packet();
                    iPacket.Module = Module;
                    iPacket.Data   = Decompress(Data, Inflater);

                    iPacket.Stream = new MemoryStream(iPacket.Data);
                    iPacket.Reader = new EndianBinaryReader(MiscUtil.Conversion.EndianBitConverter.Little, iPacket.Stream);

                    iPacket.PacketID = iPacket.Reader.ReadUInt32();

                    //if (iPacket.PacketID == 0x34287945)
                    // Console.WriteLine(decData.ToHEX());

                    iPacket.Reader.ReadUInt32();

                    //iPacket.IsValid = true;

                    Packets.Add(iPacket);
                }
                else
                {
                    Console.WriteLine("Failure!!!!", inBuff.ToHEX(), decData.ToHEX());
                    break;
                }

                remLength -= pLength;
            }while (remLength > 0);

            IReader.Close();
            IStream.Close();
        }
Пример #27
0
        public PacketStream(byte[] mpBuffer, int mpLength, IStreamCipher mpDecryptor, ZStream iStream, bool IsHandshake = false)
        {
            Packets = new List <Packet>();
            if (IsHandshake)
            {
                MemoryStream       Stream = new MemoryStream(mpBuffer);
                EndianBinaryReader Reader = new EndianBinaryReader(MiscUtil.Conversion.BigEndianBitConverter.Little, Stream);

                Reader.ReadByte();
                int Length = Reader.ReadInt32();
                Reader.ReadBytes(5);

                byte[] Data   = Reader.ReadBytes(Length - 10);
                string RSAStr = Encoding.ASCII.GetString(Data);

                Packet iPacket = new Packet();

                iPacket.RSAData = new byte[RSAStr.Length / 2];
                for (int i = 0; i < RSAStr.Length; i += 2)
                {
                    iPacket.RSAData[i / 2] = byte.Parse(RSAStr.Substring(i, 2), NumberStyles.HexNumber);
                }

                Reader.Close();
                Stream.Close();

                Packets.Add(iPacket);
            }
            else
            {
                Packets = new List <Packet>();

                byte[] dBuffer = new byte[mpLength];
                mpDecryptor.ProcessBytes(mpBuffer, 0, mpLength, dBuffer, 0);

                MemoryStream       Stream = new MemoryStream(dBuffer);
                EndianBinaryReader Reader = new EndianBinaryReader(MiscUtil.Conversion.BigEndianBitConverter.Little, Stream);

                int remLength = mpLength;

                do
                {
                    Packet iPacket = new Packet();

                    iPacket.Module = Reader.ReadByte();
                    int pLength   = Reader.ReadInt32();
                    int pChecksum = Reader.ReadByte();

                    try
                    {
                        if (iPacket.VerifyChecksum(dBuffer, pChecksum, (int)Reader.BaseStream.Position - 6))
                        {
                            byte[] iData = Reader.ReadBytes(pLength - 6);
                            //Console.WriteLine("#########################################\n{0}", iData.ToHEX());
                            byte[] Data = Decompress(iData, iStream);

                            if (Data.Length >= 4)
                            {
                                iPacket.Stream = new MemoryStream(Data);
                                iPacket.Reader = new EndianBinaryReader(MiscUtil.Conversion.EndianBitConverter.Little, iPacket.Stream);

                                iPacket.PacketID = (CPacketType)iPacket.Reader.ReadUInt32();

                                iPacket.Reader.ReadUInt32();

                                iPacket.IsValid = true;

                                byte[] cData = new byte[pLength];
                                Array.Copy(dBuffer, 0, cData, 0, pLength);

                                iPacket.Data = Data;

                                Packets.Add(iPacket);
                            }
                        }
                    }
                    catch { }

                    remLength -= pLength;
                }while (remLength > 0);

                Reader.Close();
                Stream.Close();
            }
        }
Пример #28
0
        protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
        {
            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            KeyParameter macKey = new KeyParameter(firstBlock, 0, 32);
            Arrays.Fill(firstBlock, (byte)0);
            return macKey;
        }
Пример #29
0
        protected virtual KeyParameter GenerateRecordMacKey(IStreamCipher cipher)
        {
            byte[] firstBlock = new byte[64];
            cipher.ProcessBytes(firstBlock, 0, firstBlock.Length, firstBlock, 0);

            // NOTE: The BC implementation puts 'r' after 'k'
            Array.Copy(firstBlock, 0, firstBlock, 32, 16);
            Poly1305KeyGenerator.Clamp(firstBlock, 16);
            KeyParameter macKey = new KeyParameter(firstBlock, 16, 32);
            Arrays.Fill(firstBlock, (byte)0);
            return macKey;
        }
Пример #30
0
		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;
				}
			}
		}
Пример #31
0
        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));
        }