Exemple #1
0
        public static byte[] Encrypt(RSAPublicKey pk,
                                     byte[] buf, int off, int len)
        {
            byte[] n      = pk.Modulus;
            int    modLen = n.Length;

            byte[] x = DoPKCS1Padding(modLen, true, null, buf, off, len);
            return(BigInt.ModPow(x, pk.Exponent, n));
        }
Exemple #2
0
        public static bool Verify(RSAPublicKey pk,
                                  byte[] header, byte[] headerAlt,
                                  byte[] hash, int hashOff, int hashLen,
                                  byte[] sig, int sigOff, int sigLen)
        {
            /*
             * Signature must be an integer less than the modulus,
             * but encoded over exactly the same size as the modulus.
             */
            byte[] n      = pk.Modulus;
            int    modLen = n.Length;

            if (sigLen != modLen)
            {
                return(false);
            }
            byte[] x = new byte[modLen];
            Array.Copy(sig, sigOff, x, 0, modLen);
            if (BigInt.Compare(x, n) >= 0)
            {
                return(false);
            }

            /*
             * Do the RSA exponentation, then verify and remove the
             * "Type 1" padding (00 01 FF...FF 00 with at least
             * eight bytes of value FF).
             */
            x = BigInt.ModPow(x, pk.Exponent, n);
            if (x.Length < 11 || x[0] != 0x00 || x[1] != 0x01)
            {
                return(false);
            }
            int k = 2;

            while (k < x.Length && x[k] == 0xFF)
            {
                k++;
            }
            if (k < 10 || k == x.Length || x[k] != 0x00)
            {
                return(false);
            }
            k++;

            /*
             * Check that the remaining byte end with the provided
             * hash value.
             */
            int len = modLen - k;

            if (len < hashLen)
            {
                return(false);
            }
            for (int i = 0; i < hashLen; i++)
            {
                if (x[modLen - hashLen + i] != hash[hashOff + i])
                {
                    return(false);
                }
            }
            len -= hashLen;

            /*
             * Header is at offset 'k', and length 'len'. Compare
             * with the provided header(s).
             */
            if (Eq(header, 0, header.Length, x, k, len))
            {
                return(true);
            }
            if (headerAlt != null)
            {
                if (Eq(headerAlt, 0, headerAlt.Length, x, k, len))
                {
                    return(true);
                }
            }
            return(false);
        }