Example #1
0
 public virtual byte[] GenerateSignature()
 {
     contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
     if (sLen != 0)
     {
         random.NextBytes(salt);
         salt.CopyTo(mDash, mDash.Length - sLen);
     }
     byte[] array = new byte[hLen];
     contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
     contentDigest2.DoFinal(array, 0);
     block[block.Length - sLen - 1 - hLen - 1] = 1;
     salt.CopyTo(block, block.Length - sLen - hLen - 1);
     byte[] array2 = MaskGeneratorFunction1(array, 0, array.Length, block.Length - hLen - 1);
     for (int i = 0; i != array2.Length; i++)
     {
         block[i] ^= array2[i];
     }
     block[0] &= (byte)(255 >> block.Length * 8 - emBits);
     array.CopyTo(block, block.Length - hLen - 1);
     block[block.Length - 1] = trailer;
     byte[] result = cipher.ProcessBlock(block, 0, block.Length);
     ClearBlock(block);
     return(result);
 }
 public virtual byte[] GenerateSignature()
 {
     contentDigest1.DoFinal(mDash, mDash.Length - hLen - sLen);
     if (sLen != 0)
     {
         if (!sSet)
         {
             random.NextBytes(salt);
         }
         salt.CopyTo(mDash, mDash.Length - sLen);
     }
     byte[] array = new byte[hLen];
     contentDigest2.BlockUpdate(mDash, 0, mDash.Length);
     contentDigest2.DoFinal(array, 0);
     block[block.Length - sLen - 1 - hLen - 1] = 1;
     salt.CopyTo(block, block.Length - sLen - hLen - 1);
     byte[] array2 = MaskGeneratorFunction1(array, 0, array.Length, block.Length - hLen - 1);
     byte[] array3;
     for (int i = 0; i != array2.Length; i++)
     {
         byte[] array4 = array3 = block;
         int    num    = i;
         IntPtr intPtr = (IntPtr)num;
         array4[num] = (byte)(array3[(long)intPtr] ^ array2[i]);
     }
     (array3 = block)[0] = (byte)(array3[0] & (byte)(255 >> block.Length * 8 - emBits));
     array.CopyTo(block, block.Length - hLen - 1);
     block[block.Length - 1] = trailer;
     byte[] result = cipher.ProcessBlock(block, 0, block.Length);
     ClearBlock(block);
     return(result);
 }
Example #3
0
 private byte[] EncodeBlock(byte[] input, int inOff, int inLen)
 {
     //IL_0013: Unknown result type (might be due to invalid IL or missing references)
     if (inLen > GetInputBlockSize())
     {
         throw new ArgumentException("input data too large", "inLen");
     }
     byte[] array = new byte[engine.GetInputBlockSize()];
     if (forPrivateKey)
     {
         array[0] = 1;
         for (int i = 1; i != array.Length - inLen - 1; i++)
         {
             array[i] = 255;
         }
     }
     else
     {
         ((Random)random).NextBytes(array);
         array[0] = 2;
         for (int j = 1; j != array.Length - inLen - 1; j++)
         {
             while (array[j] == 0)
             {
                 array[j] = (byte)random.NextInt();
             }
         }
     }
     array[array.Length - inLen - 1] = 0;
     global::System.Array.Copy((global::System.Array)input, inOff, (global::System.Array)array, array.Length - inLen, inLen);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Example #4
0
 private byte[] EncodeBlock(byte[] input, int inOff, int inLen)
 {
     if (inLen > GetInputBlockSize())
     {
         throw new ArgumentException("input data too large", "inLen");
     }
     byte[] array = new byte[engine.GetInputBlockSize()];
     if (forPrivateKey)
     {
         array[0] = 1;
         for (int i = 1; i != array.Length - inLen - 1; i++)
         {
             array[i] = byte.MaxValue;
         }
     }
     else
     {
         random.NextBytes(array);
         array[0] = 2;
         for (int j = 1; j != array.Length - inLen - 1; j++)
         {
             while (array[j] == 0)
             {
                 array[j] = (byte)random.NextInt();
             }
         }
     }
     array[array.Length - inLen - 1] = 0;
     Array.Copy(input, inOff, array, array.Length - inLen, inLen);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Example #5
0
 private byte[] EncodeBlock(byte[] inBytes, int inOff, int inLen)
 {
     byte[] array = new byte[GetInputBlockSize() + 1 + 2 * defHash.Length];
     Array.Copy(inBytes, inOff, array, array.Length - inLen, inLen);
     array[array.Length - inLen - 1] = 1;
     Array.Copy(defHash, 0, array, defHash.Length, defHash.Length);
     byte[] nextBytes = SecureRandom.GetNextBytes(random, defHash.Length);
     byte[] array2    = maskGeneratorFunction1(nextBytes, 0, nextBytes.Length, array.Length - defHash.Length);
     for (int i = defHash.Length; i != array.Length; i++)
     {
         byte[] array3;
         byte[] array4 = array3 = array;
         int    num    = i;
         IntPtr intPtr = (IntPtr)num;
         array4[num] = (byte)(array3[(long)intPtr] ^ array2[i - defHash.Length]);
     }
     Array.Copy(nextBytes, 0, array, 0, defHash.Length);
     array2 = maskGeneratorFunction1(array, defHash.Length, array.Length - defHash.Length, defHash.Length);
     for (int j = 0; j != defHash.Length; j++)
     {
         byte[] array3;
         byte[] array5 = array3 = array;
         int    num2   = j;
         IntPtr intPtr = (IntPtr)num2;
         array5[num2] = (byte)(array3[(long)intPtr] ^ array2[j]);
     }
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Example #6
0
        private static byte[] SegmentDecrypt(IAsymmetricBlockCipher cipher, byte[] data)
        {
            int          len    = data.Length;
            MemoryStream ms     = new MemoryStream();
            int          offset = 0;

            byte[] buf;
            int    i = 0;

            while (len - offset > 0)
            {
                if (len - offset > MAX_DECRYPT_BLOCK)
                {
                    buf = cipher.ProcessBlock(data, offset, MAX_DECRYPT_BLOCK);
                }
                else
                {
                    buf = cipher.ProcessBlock(data, offset, len - offset);
                }
                ms.Write(buf, 0, buf.Length);
                i++;
                offset = i * MAX_DECRYPT_BLOCK;
            }
            byte[] res = ms.ToArray();
            ms.Close();
            return(res);
        }
Example #7
0
        /**
         * Generate a signature for the message we've been loaded with using the key
         * we were initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
            }

            byte[] hash = new byte[digest.GetDigestSize()];
            byte[] a, b = new byte[engine.GetInputBlockSize()];
            int    n;

            digest.DoFinal(hash, 0);
            using (MemoryStream dat = new MemoryStream(hash))
            {
                using (MemoryStream bf = new MemoryStream())
                {
                    while ((n = dat.Read(b, 0, b.Length)) > 0)
                    {
                        a = engine.ProcessBlock(b, 0, n);

                        bf.Write(a, 0, a.Length);
                        Array.Clear(a, 0, a.Length);
                    }

                    Array.Clear(b, 0, b.Length);
                    b = bf.ToArray();
                }
            }

            return(b);
        }
Example #8
0
        /// <summary>
        /// Encrypts a plain array of bytes using a public key
        /// </summary>
        /// <param name="publicKey">the public key used for encryption</param>
        /// <param name="plainBytes">the plain bytes to encrypt</param>
        /// <returns></returns>
        public byte[] EncryptBytes(byte[] publicKey, byte[] plainBytes)
        {
            //CreateKeyPair public key
            var pubKey = (RsaKeyParameters)CreateAsymmetricKeyParameterFromPublicKeyInfo(publicKey);

            cipher.Init(true, pubKey);

            byte[] encrypted;
            try
            {
                //encrypt plain bytes
                encrypted = cipher.ProcessBlock(plainBytes, 0, plainBytes.Length);
            }
            catch (CryptoException exception)
            {
                if (exception.Message == "input too large for RSA cipher.")
                {
                    string message = "Encryption Failure!\n" +
                                     $"{exception.Message}\n" +
                                     "The plain data bit size cannot be greater than the selected key size.\n" +
                                     $"Key bit size: {cipher.GetInputBlockSize() * 8}\n" +
                                     $"Plain data bit size: {plainBytes.Length * 8}";
                    throw new CryptoException(message, exception);
                }
                else
                {
                    string message = "Encryption Failure!\n" +
                                     $"{exception.Message}\n" +
                                     "Contact developer.";
                    throw new CryptoException(message, exception);
                }
            }
            return(encrypted);
        }
Example #9
0
        private byte[] EncodeBlock(
            byte[]      inBytes,
            int inOff,
            int inLen)
        {
            byte[] block = new byte[GetInputBlockSize() + 1 + 2 * defHash.Length];

            //
            // copy in the message
            //
            Array.Copy(inBytes, inOff, block, block.Length - inLen, inLen);

            //
            // add sentinel
            //
            block[block.Length - inLen - 1] = 0x01;

            //
            // as the block is already zeroed - there's no need to add PS (the >= 0 pad of 0)
            //

            //
            // add the hash of the encoding params.
            //
            Array.Copy(defHash, 0, block, defHash.Length, defHash.Length);

            //
            // generate the seed.
            //
            byte[] seed = random.GenerateSeed(defHash.Length);

            //
            // mask the message block.
            //
            byte[] mask = maskGeneratorFunction1(seed, 0, seed.Length, block.Length - defHash.Length);

            for (int i = defHash.Length; i != block.Length; i++)
            {
                block[i] ^= mask[i - defHash.Length];
            }

            //
            // add in the seed
            //
            Array.Copy(seed, 0, block, 0, defHash.Length);

            //
            // mask the seed.
            //
            mask = maskGeneratorFunction1(
                block, defHash.Length, block.Length - defHash.Length, defHash.Length);

            for (int i = 0; i != defHash.Length; i++)
            {
                block[i] ^= mask[i];
            }

            return(engine.ProcessBlock(block, 0, block.Length));
        }
    public virtual byte[] GenerateSignature()
    {
        CreateSignatureBlock();
        BigInteger bigInteger = new BigInteger(1, cipher.ProcessBlock(block, 0, block.Length));

        ClearBlock(block);
        bigInteger = bigInteger.Min(kParam.Modulus.Subtract(bigInteger));
        return(BigIntegers.AsUnsignedByteArray((kParam.Modulus.BitLength + 7) / 8, bigInteger));
    }
 public virtual byte[] GenerateSignature()
 {
     if (!forSigning)
     {
         throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
     }
     byte[] array = new byte[digest.GetDigestSize()];
     digest.DoFinal(array, 0);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Example #12
0
        public byte[] Encrypt(byte[] message)
        {
            cipher.Init(true, publicKey);

            //byte[] message = utf8enc.GetBytes(messages);
            byte[] ciphered     = cipher.ProcessBlock(message, 0, message.Length);
            string cipheredText = utf8enc.GetString(ciphered);

            return(ciphered);
        }
Example #13
0
        /**
         * Generate a signature for the message we've been loaded with using the key
         * we were initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
            }

            byte[] hash = BouncyCastle.Utilities.Digests.DoFinal(digest);

            return(engine.ProcessBlock(hash, 0, hash.Length));
        }
Example #14
0
 public virtual byte[] GenerateSignature()
 {
     //IL_000d: Unknown result type (might be due to invalid IL or missing references)
     if (!forSigning)
     {
         throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
     }
     byte[] array = new byte[digest.GetDigestSize()];
     digest.DoFinal(array, 0);
     return(engine.ProcessBlock(array, 0, array.Length));
 }
Example #15
0
        /**
         * Generate a signature for the message we've been loaded with using
         * the key we were initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");
            }

            byte[] hash = BouncyCastle.Utilities.Digests.DoFinal(digest);
            byte[] data = DerEncode(hash);
            return(rsaEngine.ProcessBlock(data, 0, data.Length));
        }
Example #16
0
        private byte[] EncodeBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            byte[] block = new byte[(bitSize + 7) / 8];
            int    r     = padBits + 1;
            int    z     = inLen;
            int    t     = (bitSize + 13) / 16;

            for (int i = 0; i < t; i += z)
            {
                if (i > t - z)
                {
                    Array.Copy(input, inOff + inLen - (t - i),
                               block, block.Length - t, t - i);
                }
                else
                {
                    Array.Copy(input, inOff, block, block.Length - (i + z), z);
                }
            }

            for (int i = block.Length - 2 * t; i != block.Length; i += 2)
            {
                byte val = block[block.Length - t + i / 2];

                block[i] = (byte)((shadows[(uint)(val & 0xff) >> 4] << 4)
                                  | shadows[val & 0x0f]);
                block[i + 1] = val;
            }

            block[block.Length - 2 * z] ^= (byte)r;
            block[block.Length - 1]      = (byte)((block[block.Length - 1] << 4) | 0x06);

            int maxBit = (8 - (bitSize - 1) % 8);
            int offSet = 0;

            if (maxBit != 8)
            {
                block[0] &= (byte)((ushort)0xff >> maxBit);
                block[0] |= (byte)((ushort)0x80 >> maxBit);
            }
            else
            {
                block[0]  = 0x00;
                block[1] |= 0x80;
                offSet    = 1;
            }

            return(engine.ProcessBlock(block, offSet, block.Length - offSet));
        }
Example #17
0
        /**
         * Generate a signature for the message we've been loaded with using
         * the key we were initialised with.
         */
        public byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("RsaDigestSigner not initialised for signature generation.");
            }

            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

            byte[] data = DerEncode(hash);
            return(rsaEngine.ProcessBlock(data, 0, data.Length));
        }
Example #18
0
        /**
         * generate a signature for the loaded message using the key we were
         * initialised with.
         */
        public virtual byte[] GenerateSignature()
        {
            CreateSignatureBlock();

            BigInteger t = new BigInteger(1, cipher.ProcessBlock(block, 0, block.Length));

            ClearBlock(block);

            t = t.Min(kParam.Modulus.Subtract(t));

            int size = BigIntegers.GetUnsignedByteLength(kParam.Modulus);

            return(BigIntegers.AsUnsignedByteArray(size, t));
        }
Example #19
0
        /**
         * Generate a signature for the message we've been loaded with using the key
         * we were initialised with.
         */
        public byte[] GenerateSignature()
        {
            if (!forSigning)
            {
                throw new InvalidOperationException("GenericSigner not initialised for signature generation.");
            }

            byte[] hash = new byte[digest.GetDigestSize()];
            digest.DoFinal(hash, 0);

            //jbonilla
            currentSignature = engine.ProcessBlock(hash, 0, hash.Length);

            return(currentSignature);
        }
Example #20
0
        private static void XTest(string mechanism, IAsymmetricBlockCipher encryptor, IAsymmetricBlockCipher decryptor, byte[] test)
        {
            byte[] enc  = encryptor.ProcessBlock(test, 0, test.Length);
            byte[] dec  = decryptor.ProcessBlock(enc, 0, enc.Length);
            bool   diff = !StructuralComparisons.StructuralEqualityComparer.Equals(dec, test);

            //
            Console.Write("{0}{1} max {2} bytes - src {3} bytes, enc {4} bytes - ",
                          mechanism.PadRight(32),
                          encryptor.AlgorithmName.PadRight(32),
                          encryptor.GetInputBlockSize(),
                          test.Length,
                          enc.Length);
            if (diff)
            {
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("diff");
                _diff++;
                Console.ResetColor();
            }
            else
            {
                Console.WriteLine("same");
            }
        }
Example #21
0
        public byte[] ProcessBlock(byte[] inBuf, int inOff, int inLen)
        {
            if (_forEncryption)
            {
                byte[] realBlock = new byte[_prefix.Length + inLen];
                Array.Copy(_prefix, 0, realBlock, 0, _prefix.Length);
                Array.Copy(inBuf, inOff, realBlock, _prefix.Length, inLen);

                return(_encryptor.ProcessBlock(realBlock, 0, realBlock.Length));
            }
            else
            {
                byte[] myBuf;

                if (inOff != 0 || inLen != inBuf.Length)
                {
                    myBuf = new byte[inLen];
                    Array.Copy(inBuf, inOff, myBuf, 0, inLen);
                }
                else
                {
                    myBuf = inBuf;
                }

                return(_keyHandle.Unbind(myBuf));
            }
        }
Example #22
0
        public virtual byte[] GenerateRawSignature(SecureRandom random,
                                                   AsymmetricKeyParameter privateKey, byte[] md5AndSha1)
        {
            IAsymmetricBlockCipher engine = CreateRsaImpl();

            engine.Init(true, new ParametersWithRandom(privateKey, random));
            return(engine.ProcessBlock(md5AndSha1, 0, md5AndSha1.Length));
        }
        private byte[] EncodeBlock(byte[] input, int inOff, int inLen)
        {
            byte[] array = new byte[(bitSize + 7) / 8];
            int    num   = padBits + 1;
            int    num2  = (bitSize + 13) / 16;

            for (int i = 0; i < num2; i += inLen)
            {
                if (i > num2 - inLen)
                {
                    global::System.Array.Copy((global::System.Array)input, inOff + inLen - (num2 - i), (global::System.Array)array, array.Length - num2, num2 - i);
                }
                else
                {
                    global::System.Array.Copy((global::System.Array)input, inOff, (global::System.Array)array, array.Length - (i + inLen), inLen);
                }
            }
            for (int j = array.Length - 2 * num2; j != array.Length; j += 2)
            {
                byte b = array[array.Length - num2 + j / 2];
                array[j]     = (byte)((shadows[(uint)(b & 0xFF) >> 4] << 4) | shadows[b & 0xF]);
                array[j + 1] = b;
            }
            byte[] array2;
            byte[] array3 = (array2 = array);
            int    num3   = array.Length - 2 * inLen;

            global::System.IntPtr intPtr = (global::System.IntPtr)num3;
            array3[num3]            = (byte)(array2[(long)intPtr] ^ (byte)num);
            array[array.Length - 1] = (byte)((uint)(array[array.Length - 1] << 4) | 6u);
            int num4 = 8 - (bitSize - 1) % 8;
            int num5 = 0;

            if (num4 != 8)
            {
                (array2 = array)[0] = (byte)(array2[0] & (byte)(255 >> num4));
                (array2 = array)[0] = (byte)(array2[0] | (byte)(128 >> num4));
            }
            else
            {
                array[0]            = 0;
                (array2 = array)[1] = (byte)(array2[1] | 0x80u);
                num5 = 1;
            }
            return(engine.ProcessBlock(array, num5, array.Length - num5));
        }
Example #24
0
        private byte[] EncodeBlock(
            byte[]  input,
            int inOff,
            int inLen)
        {
            if (inLen > GetInputBlockSize())
            {
                throw new ArgumentException("input data too large", "inLen");
            }

            byte[] block = new byte[engine.GetInputBlockSize()];

            if (forPrivateKey)
            {
                block[0] = 0x01;                                        // type code 1

                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    block[i] = (byte)0xFF;
                }
            }
            else
            {
                random.NextBytes(block);                                // random fill

                block[0] = 0x02;                                        // type code 2

                //
                // a zero byte marks the end of the padding, so all
                // the pad bytes must be non-zero.
                //
                for (int i = 1; i != block.Length - inLen - 1; i++)
                {
                    while (block[i] == 0)
                    {
                        block[i] = (byte)random.NextInt();
                    }
                }
            }

            block[block.Length - inLen - 1] = 0x00;                   // mark the end of the padding
            Array.Copy(input, inOff, block, block.Length - inLen, inLen);

            return(engine.ProcessBlock(block, 0, block.Length));
        }
Example #25
0
        public virtual bool VerifyRawSignature(byte[] sigBytes, AsymmetricKeyParameter publicKey,
                                               byte[] md5AndSha1)
        {
            IAsymmetricBlockCipher engine = CreateRsaImpl();

            engine.Init(false, publicKey);
            byte[] signed = engine.ProcessBlock(sigBytes, 0, sigBytes.Length);
            return(Arrays.ConstantTimeAreEqual(signed, md5AndSha1));
        }
Example #26
0
            public IBlockResult Wrap(byte[] keyData)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    throw new CryptoUnapprovedOperationError("attempt to create unapproved unwrapper in approved only mode");
                }

                return new SimpleBlockResult(wrapper.ProcessBlock(keyData, 0, keyData.Length));
            }
Example #27
0
            public IBlockResult Unwrap(byte[] cipherText, int offset, int length)
            {
                if (CryptoServicesRegistrar.IsInApprovedOnlyMode())
                {
                    throw new CryptoUnapprovedOperationError("attempt to create unapproved unwrapper in approved only mode");
                }

                return new SimpleBlockResult(unwrapper.ProcessBlock(cipherText, offset, length));
            }
Example #28
0
        private static void Demo1()
        {
            byte[] test = Utilities.ScoopBytes(4);
            AsymmetricCipherKeyPair keyPair   = AsymmetricAlgorithmHelper.RSA.GenerateKeyPair();
            IAsymmetricBlockCipher  encryptor = AsymmetricAlgorithmHelper.RSA.GenerateCipher(AsymmetricPaddingMode.PKCS1, keyPair.Public);
            IAsymmetricBlockCipher  decryptor = AsymmetricAlgorithmHelper.RSA.GenerateCipher(AsymmetricPaddingMode.PKCS1, keyPair.Private);

            byte[] enc = encryptor.ProcessBlock(test, 0, test.Length);
            _ = decryptor.ProcessBlock(enc, 0, enc.Length);
        }
Example #29
0
        /**
         * process the contents of the buffer using the underlying
         * cipher.
         *
         * @return the result of the encryption/decryption process on the
         * buffer.
         * @exception InvalidCipherTextException if we are given a garbage block.
         */
        public override byte[] DoFinal()
        {
            var outBytes = _bufOff > 0
                ? _cipher.ProcessBlock(_buffer, 0, _bufOff)
                : EmptyBuffer;

            this.Reset();

            return(outBytes);
        }
        /**
         * process the contents of the buffer using the underlying
         * cipher.
         *
         * @return the result of the encryption/decryption process on the
         * buffer.
         * @exception InvalidCipherTextException if we are given a garbage block.
         */
        public override byte[] DoFinal()
        {
            byte[] outBytes = bufOff > 0
                                ?       cipher.ProcessBlock(buffer, 0, bufOff)
                                :       EmptyBuffer;

            Reset();

            return(outBytes);
        }