Ejemplo n.º 1
0
        public static byte[] EncryptData(Pkcs1Encoding engine, byte[] data)
        {
            // Calculate number of blocks we need to encrypt
            int inputBlockSize = engine.GetInputBlockSize();
            int totalBlocks    = (data.Length + inputBlockSize - 1) / inputBlockSize; // Integer division, round up

            // Allocate array for the correct amount of data
            byte[] result = new byte[totalBlocks * engine.GetOutputBlockSize()];

            // So long as there is data left to encrypt, encrypt another block
            int inputOffset  = 0;
            int outputOffset = 0;

            while (inputOffset < data.Length)
            {
                int dataToConsume = Math.Min(inputBlockSize, data.Length - inputOffset);

                byte[] encryptedBlock = engine.ProcessBlock(data, inputOffset, dataToConsume);
                Array.Reverse(encryptedBlock);
                Buffer.BlockCopy(encryptedBlock, 0, result, outputOffset, encryptedBlock.Length);

                inputOffset  += dataToConsume;
                outputOffset += encryptedBlock.Length;
            }

            return(result);
        }
Ejemplo n.º 2
0
        private static byte[] DecryptCore(byte[] payload, AsymmetricKeyParameter key)
        {
            var engine = new Pkcs1Encoding(new RsaEngine());

            engine.Init(false, key);

            int inBlockSize  = engine.GetInputBlockSize();
            int outBlockSize = engine.GetOutputBlockSize();
            int blocks       = (int)Math.Ceiling(payload.Length / (double)inBlockSize);
            int outputLength = 0;

            byte[] output = new byte[blocks * outBlockSize];
            for (int i = 0; i < blocks; ++i)
            {
                int offset      = i * inBlockSize;
                int blockLength = Math.Min(inBlockSize, payload.Length - offset);
                var cryptoBlock = engine.ProcessBlock(payload, offset, blockLength);
                cryptoBlock.CopyTo(output, i * outBlockSize);
                outputLength += cryptoBlock.Length;
            }

            if (outputLength != output.Length)
            {
                // Rescale output array
                byte[] tmp = new byte[outputLength];
                Array.Copy(output, tmp, outputLength);
                output = tmp;
            }

            return(output);
        }
Ejemplo n.º 3
0
        private byte[] encryptString(String source)
        {
            if (encryptEngine == null)
            {
                cryptInit();
            }

            byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(source);
            int    inLength       = encryptEngine.GetInputBlockSize();


            int resultLength = bytesToEncrypt.Length / inLength + (bytesToEncrypt.Length % inLength > 0 ? 1 : 0);

            byte[] cipherbytes = new byte[resultLength * encryptEngine.GetOutputBlockSize()];
            int    start       = 0;
            int    copyIdx     = 0;
            //logger.log("Bytes length: " + bytesToEncrypt.Length);
            int length = (bytesToEncrypt.Length - start) > inLength ? inLength : bytesToEncrypt.Length - start;

            while (start < bytesToEncrypt.Length)
            {
                byte[] encBuffer = new byte[length];
                byte[] buffer    = encryptEngine.ProcessBlock(bytesToEncrypt, start, length);
                //logger.log("Bytes ctypted: " + buffer.Length);
                //Console.WriteLine("Start: " + start + "\t Length: " + buffer.Length);
                Array.Copy(buffer, 0, cipherbytes, copyIdx, buffer.Length);
                start   += inLength;
                copyIdx += buffer.Length;
                length   = (bytesToEncrypt.Length - start) > inLength ? inLength : bytesToEncrypt.Length - start;
            }
            return(cipherbytes);
        }
Ejemplo n.º 4
0
        public static byte[] EncryptData(Pkcs1Encoding engine, byte[] data)
        {
            int inputBlockSize = engine.GetInputBlockSize(), totalBlocks = (data.Length + inputBlockSize - 1) / inputBlockSize;

            byte[] result = new byte[totalBlocks * engine.GetOutputBlockSize()];
            int    inputOffset = 0, outputOffset = 0;

            while (inputOffset < data.Length)
            {
                int dataToConsume = Math.Min(inputBlockSize, data.Length - inputOffset);

                byte[] encryptedBlock = engine.ProcessBlock(data, inputOffset, dataToConsume);
                Array.Reverse(encryptedBlock);
                Buffer.BlockCopy(encryptedBlock, 0, result, outputOffset, encryptedBlock.Length);

                inputOffset  += dataToConsume;
                outputOffset += encryptedBlock.Length;
            }
            return(result);
        }
Ejemplo n.º 5
0
        private void testZeroBlock(ICipherParameters encParameters, ICipherParameters decParameters)
        {
            IAsymmetricBlockCipher eng = new Pkcs1Encoding(new RsaEngine());

            eng.Init(true, encParameters);

            if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
            {
                Fail("PKCS1 output block size incorrect");
            }

            byte[] zero = new byte[0];
            byte[] data = null;

            try
            {
                data = eng.ProcessBlock(zero, 0, zero.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, decParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!Arrays.AreEqual(zero, data))
            {
                Fail("failed PKCS1 zero Test");
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Encrypts a byte payload using a given key.
        /// </summary>
        public byte[] Encrypt(byte[] payload, AsymmetricKeyParameter key)
        {
            var engine = new Pkcs1Encoding(new RsaEngine());

            engine.Init(true, key);

            int inBlockSize  = engine.GetInputBlockSize();
            int outBlockSize = engine.GetOutputBlockSize();
            int blocks       = (int)Math.Ceiling(payload.Length / (double)inBlockSize);
            int outputLength = 0;

            byte[] output = new byte[blocks * outBlockSize];
            for (int i = 0; i < blocks; ++i)
            {
                int offset      = i * inBlockSize;
                int blockLength = Math.Min(inBlockSize, payload.Length - offset);
                var cryptoBlock = engine.ProcessBlock(payload, offset, blockLength);
                cryptoBlock.CopyTo(output, i * outBlockSize);
                outputLength += cryptoBlock.Length;

                Logger.LogTrace(LoggingEvents.Cryptography,
                                "Encrypt {0}th block (offset {1} length {2}) to {3} bytes (offset {4})",
                                i + 1, offset, blockLength, cryptoBlock.Length, i * outBlockSize);
            }

            if (outputLength != output.Length)
            {
                // Rescale output array
                byte[] tmp = new byte[outputLength];
                Array.Copy(output, tmp, outputLength);
                output = tmp;
            }

            Logger.LogTrace(LoggingEvents.Cryptography,
                            "Encrypted {0} bytes into {1} blocks of {2} bytes, output {3} bytes",
                            payload.Length, blocks, outBlockSize, output.Length);

            return(output);
        }
Ejemplo n.º 7
0
        public override void PerformTest()
        {
            RsaKeyParameters pubParameters  = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);

            byte[] data = Hex.Decode(edgeInput);

            //
            // RAW
            //
            IAsymmetricBlockCipher eng = new RsaBlindedEngine();

            eng.Init(true, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("RSA: failed - exception " + e.ToString(), e);
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!edgeInput.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW edge Test");
            }

            data = Hex.Decode(input);

            eng.Init(true, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW Test");
            }

            //
            // PKCS1 - public encrypt, private decrypt
            //
            eng = new Pkcs1Encoding(eng);

            eng.Init(true, pubParameters);

            if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
            {
                Fail("PKCS1 output block size incorrect");
            }

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed PKCS1 public/private Test");
            }

            //
            // PKCS1 - private encrypt, public decrypt
            //
            eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());

            eng.Init(true, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed PKCS1 private/public Test");
            }

            //
            // key generation test
            //
            RsaKeyPairGenerator        pGen     = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            eng = new RsaBlindedEngine();

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
            {
                Fail("failed key generation (768) length test");
            }

            eng.Init(true, pair.Public);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, pair.Private);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (768) Test");
            }

            genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

            pGen.Init(genParam);
            pair = pGen.GenerateKeyPair();

            eng.Init(true, pair.Public);

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
            {
                Fail("failed key generation (1024) length test");
            }

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            eng.Init(false, pair.Private);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (1024) test");
            }

            doTestOaep(pubParameters, privParameters);
            doTestStrictPkcs1Length(pubParameters, privParameters);
            doTestDudPkcs1Block(pubParameters, privParameters);
            doTestMissingDataPkcs1Block(pubParameters, privParameters);
            doTestTruncatedPkcs1Block(pubParameters, privParameters);
            doTestWrongPaddingPkcs1Block(pubParameters, privParameters);

            try
            {
                new RsaBlindedEngine().ProcessBlock(new byte[] { 1 }, 0, 1);
                Fail("failed initialisation check");
            }
            catch (InvalidOperationException)
            {
                // expected
            }
        }
Ejemplo n.º 8
0
        public override void PerformTest()
        {
            RsaKeyParameters pubParameters  = new RsaKeyParameters(false, mod, pubExp);
            RsaKeyParameters privParameters = new RsaPrivateCrtKeyParameters(mod, pubExp, privExp, p, q, pExp, qExp, crtCoef);

            byte[] data = Hex.Decode(edgeInput);

            //
            // RAW
            //
            IAsymmetricBlockCipher eng = new RsaEngine();

            eng.Init(true, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("RSA: failed - exception " + e.ToString());
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!edgeInput.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW edge Test");
            }

            data = Hex.Decode(input);

            eng.Init(true, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            eng.Init(false, privParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed RAW Test");
            }

            //
            // PKCS1 - public encrypt, private decrypt
            //
            eng = new Pkcs1Encoding(eng);

            eng.Init(true, pubParameters);

            if (eng.GetOutputBlockSize() != ((Pkcs1Encoding)eng).GetUnderlyingCipher().GetOutputBlockSize())
            {
                Fail("PKCS1 output block size incorrect");
            }

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            eng.Init(false, privParameters);

            byte[] plainData = null;
            try
            {
                plainData = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!input.Equals(Hex.ToHexString(plainData)))
            {
                Fail("failed PKCS1 public/private Test");
            }

            Pkcs1Encoding fEng = new Pkcs1Encoding(new RsaEngine(), input.Length / 2);

            fEng.Init(false, new ParametersWithRandom(privParameters, new SecureRandom()));
            try
            {
                plainData = fEng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (!input.Equals(Hex.ToHexString(plainData)))
            {
                Fail("failed PKCS1 public/private fixed Test");
            }

            fEng = new Pkcs1Encoding(new RsaEngine(), input.Length);
            fEng.Init(false, new ParametersWithRandom(privParameters, new SecureRandom()));
            try
            {
                data = fEng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString(), e);
            }

            if (input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed to recognise incorrect plaint text length");
            }

            data = plainData;

            //
            // PKCS1 - private encrypt, public decrypt
            //
            eng = new Pkcs1Encoding(((Pkcs1Encoding)eng).GetUnderlyingCipher());

            eng.Init(true, privParameters);

            try
            {
                data = eng.ProcessBlock(plainData, 0, plainData.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            eng.Init(false, pubParameters);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed PKCS1 private/public Test");
            }

            testZeroBlock(pubParameters, privParameters);
            testZeroBlock(privParameters, pubParameters);

            //
            // key generation test
            //
            RsaKeyPairGenerator        pGen     = new RsaKeyPairGenerator();
            RsaKeyGenerationParameters genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 768, 25);

            pGen.Init(genParam);

            AsymmetricCipherKeyPair pair = pGen.GenerateKeyPair();

            eng = new RsaEngine();

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 768)
            {
                Fail("failed key generation (768) length test");
            }

            eng.Init(true, pair.Public);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            eng.Init(false, pair.Private);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (768) Test");
            }

            genParam = new RsaKeyGenerationParameters(BigInteger.ValueOf(0x11), new SecureRandom(), 1024, 25);

            pGen.Init(genParam);
            pair = pGen.GenerateKeyPair();

            eng.Init(true, pair.Public);

            if (((RsaKeyParameters)pair.Public).Modulus.BitLength < 1024)
            {
                Fail("failed key generation (1024) length test");
            }

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            eng.Init(false, pair.Private);

            try
            {
                data = eng.ProcessBlock(data, 0, data.Length);
            }
            catch (Exception e)
            {
                Fail("failed - exception " + e.ToString());
            }

            if (!input.Equals(Hex.ToHexString(data)))
            {
                Fail("failed key generation (1024) test");
            }

            genParam = new RsaKeyGenerationParameters(
                BigInteger.ValueOf(0x11), new SecureRandom(), 128, 25);
            pGen.Init(genParam);

            for (int i = 0; i < 100; ++i)
            {
                pair = pGen.GenerateKeyPair();
                RsaPrivateCrtKeyParameters privKey = (RsaPrivateCrtKeyParameters)pair.Private;
                BigInteger pqDiff = privKey.P.Subtract(privKey.Q).Abs();

                if (pqDiff.BitLength < 42)
                {
                    Fail("P and Q too close in RSA key pair");
                }
            }

            doTestBadSig();
            doTestOaep(pubParameters, privParameters);
            doTestStrictPkcs1Length(pubParameters, privParameters);
            doTestDudPkcs1Block(pubParameters, privParameters);
            doTestMissingDataPkcs1Block(pubParameters, privParameters);
            doTestTruncatedPkcs1Block(pubParameters, privParameters);
            doTestWrongPaddingPkcs1Block(pubParameters, privParameters);
            doTest_CVE_2017_15361();

            try
            {
                new RsaEngine().ProcessBlock(new byte[] { 1 }, 0, 1);
                Fail("failed initialisation check");
            }
            catch (InvalidOperationException)
            {
                // expected
            }
        }