Exemplo n.º 1
0
        /// <summary>
        ///     Low level RSA Process function for use with private key.
        ///     Should never be used; Because without padding RSA is vulnerable to attacks.  Use with caution.
        /// </summary>
        /// <param name="PlainText">Data to encrypt. Length must be less than Modulus size in octets.</param>
        /// <param name="usePrivate">True to use Private key, else Public.</param>
        /// <returns>Encrypted Data</returns>
        public byte[] RSAProcess(byte[] PlainText, bool usePrivate)
        {
            if (usePrivate && !rsaParams.Has_PRIVATE_Info)
            {
                throw new CryptographicException("RSA Process: Incomplete Private Key Info");
            }

            if ((usePrivate == false) && !rsaParams.Has_PUBLIC_Info)
            {
                throw new CryptographicException("RSA Process: Incomplete Public Key Info");
            }

            BigInteger _E;

            if (usePrivate)
            {
                _E = rsaParams.D;
            }
            else
            {
                _E = rsaParams.E;
            }

            var PT = RSAProviderUtils.OS2IP(PlainText, false);
            var M  = BigInteger.ModPow(PT, _E, rsaParams.N);

            if (M.Sign == -1)
            {
                return(RSAProviderUtils.I2OSP(M + rsaParams.N, rsaParams.OctetsInModulus, false));
            }
            return(RSAProviderUtils.I2OSP(M, rsaParams.OctetsInModulus, false));
        }
Exemplo n.º 2
0
        /// <summary>
        /// Mask Generation Function
        /// </summary>
        /// <param name="Z">Initial pseudorandom Seed.</param>
        /// <param name="l">Length of output required.</param>
        /// <returns></returns>
        private byte[] MGF(byte[] Z, int l)
        {
            if (l > (Math.Pow(2, 32)))
            {
                throw new ArgumentException("Mask too long.");
            }
            else
            {
                List <byte> result = new List <byte>();
                for (int i = 0; i <= l / rsaParams.hLen; i++)
                {
                    List <byte> data = new List <byte>();
                    data.AddRange(Z);
                    data.AddRange(RSAProviderUtils.I2OSP(i, 4, false));
                    result.AddRange(rsaParams.ComputeHash(data.ToArray()));
                }

                if (l <= result.Count)
                {
                    return(result.GetRange(0, l).ToArray());
                }
                else
                {
                    throw new ArgumentException("Invalid Mask Length.");
                }
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Low level RSA Decryption function for use with private key. Uses CRT and is Much faster.
        /// Should never be used; Because without padding RSA is vulnerable to attacks. Use with caution.
        /// </summary>
        /// <param name="Data">Data to encrypt. Length must be less than Modulus size in octets.</param>
        /// <returns>Encrypted Data</returns>
        public byte[] RSADecryptPrivateCRT(byte[] Data)
        {
            if (rsaParams.Has_PRIVATE_Info && rsaParams.HasCRTInfo)
            {
                BigInteger C = RSAProviderUtils.OS2IP(Data, false);

                BigInteger M1 = BigInteger.ModPow(C, rsaParams.DP, rsaParams.P);
                BigInteger M2 = BigInteger.ModPow(C, rsaParams.DQ, rsaParams.Q);
                BigInteger H  = ((M1 - M2) * rsaParams.InverseQ) % rsaParams.P;
                BigInteger M  = (M2 + (rsaParams.Q * H));

                if (M.Sign == -1)
                {
                    return(RSAProviderUtils.I2OSP(M + rsaParams.N, rsaParams.OctetsInModulus, false));
                }
                else
                {
                    return(RSAProviderUtils.I2OSP(M, rsaParams.OctetsInModulus, false));
                }
            }
            else
            {
                throw new CryptographicException("RSA Decrypt CRT: Incomplete Key Info");
            }
        }
 /// <summary>
 ///     Initialize the RSA class. Only the public parameters.
 /// </summary>
 /// <param name="Modulus">Modulus of the RSA key.</param>
 /// <param name="Exponent">Exponent of the RSA key</param>
 /// <param name="ModulusSize">Modulus size in number of bits. Ex: 512, 1024, 2048, 4096 etc.</param>
 public RSAProviderParameters(byte[] Modulus, byte[] Exponent, int ModulusSize)
 {
     // rsaParams;
     OctetsInModulus = ModulusSize / 8;
     E = RSAProviderUtils.OS2IP(Exponent, false);
     N = RSAProviderUtils.OS2IP(Modulus, false);
     Has_PUBLIC_Info = true;
 }
Exemplo n.º 5
0
 /// <summary>
 /// Initialize the RSA class.
 /// </summary>
 /// <param name="Modulus">Modulus of the RSA key.</param>
 /// <param name="Exponent">Exponent of the RSA key</param>
 /// /// <param name="D">Exponent of the RSA key</param>
 /// <param name="ModulusSize">Modulus size in number of bits. Ex: 512, 1024, 2048, 4096 etc.</param>
 public RSAProviderParameters(byte[] Modulus, byte[] Exponent, byte [] D, int ModulusSize)
 {
     // rsaParams;
     _ModulusOctets    = ModulusSize / 8;
     _E                = RSAProviderUtils.OS2IP(Exponent, false);
     _N                = RSAProviderUtils.OS2IP(Modulus, false);
     _D                = RSAProviderUtils.OS2IP(D, false);
     _Has_PUBLIC_Info  = true;
     _Has_PRIVATE_Info = true;
 }
 /// <summary>
 ///     Initialize the RSA class. It's assumed that both the Public and Extended Private info are there.
 /// </summary>
 /// <param name="rsaParams">Preallocated RSAParameters containing the required keys.</param>
 /// <param name="ModulusSize">Modulus size in bits</param>
 public RSAProviderParameters(RSAParameters rsaParams, int ModulusSize)
 {
     // rsaParams;
     OctetsInModulus = ModulusSize / 8;
     E                = RSAProviderUtils.OS2IP(rsaParams.Exponent, false);
     D                = RSAProviderUtils.OS2IP(rsaParams.D, false);
     N                = RSAProviderUtils.OS2IP(rsaParams.Modulus, false);
     P                = RSAProviderUtils.OS2IP(rsaParams.P, false);
     Q                = RSAProviderUtils.OS2IP(rsaParams.Q, false);
     DP               = RSAProviderUtils.OS2IP(rsaParams.DP, false);
     DQ               = RSAProviderUtils.OS2IP(rsaParams.DQ, false);
     InverseQ         = RSAProviderUtils.OS2IP(rsaParams.InverseQ, false);
     HasCRTInfo       = true;
     Has_PUBLIC_Info  = true;
     Has_PRIVATE_Info = true;
 }
Exemplo n.º 7
0
 /// <summary>
 /// Initialize the RSA class. For CRT.
 /// </summary>
 /// <param name="Modulus">Modulus of the RSA key.</param>
 /// <param name="Exponent">Exponent of the RSA key</param>
 /// /// <param name="D">Exponent of the RSA key</param>
 /// <param name="P">P paramater of RSA Algorithm.</param>
 /// <param name="Q">Q paramater of RSA Algorithm.</param>
 /// <param name="DP">DP paramater of RSA Algorithm.</param>
 /// <param name="DQ">DQ paramater of RSA Algorithm.</param>
 /// <param name="InverseQ">InverseQ paramater of RSA Algorithm.</param>
 /// <param name="ModulusSize">Modulus size in number of bits. Ex: 512, 1024, 2048, 4096 etc.</param>
 public RSAProviderParameters(byte[] Modulus, byte[] Exponent, byte[] D, byte[] P, byte [] Q, byte [] DP, byte [] DQ, byte [] InverseQ, int ModulusSize)
 {
     // rsaParams;
     _ModulusOctets    = ModulusSize / 8;
     _E                = RSAProviderUtils.OS2IP(Exponent, false);
     _N                = RSAProviderUtils.OS2IP(Modulus, false);
     _D                = RSAProviderUtils.OS2IP(D, false);
     _P                = RSAProviderUtils.OS2IP(P, false);
     _Q                = RSAProviderUtils.OS2IP(Q, false);
     _DP               = RSAProviderUtils.OS2IP(DP, false);
     _DQ               = RSAProviderUtils.OS2IP(DQ, false);
     _InverseQ         = RSAProviderUtils.OS2IP(InverseQ, false);
     _Has_CRT_Info     = true;
     _Has_PUBLIC_Info  = true;
     _Has_PRIVATE_Info = true;
 }
Exemplo n.º 8
0
 /// <summary>
 /// Initialize the RSA class. It's assumed that both the Public and Extended Private info are there.
 /// </summary>
 /// <param name="rsaParams">Preallocated RSAParameters containing the required keys.</param>
 /// <param name="ModulusSize">Modulus size in bits</param>
 public RSAProviderParameters(RSAParameters rsaParams, int ModulusSize)
 {
     // rsaParams;
     _ModulusOctets    = ModulusSize / 8;
     _E                = RSAProviderUtils.OS2IP(rsaParams.Exponent, false);
     _D                = RSAProviderUtils.OS2IP(rsaParams.D, false);
     _N                = RSAProviderUtils.OS2IP(rsaParams.Modulus, false);
     _P                = RSAProviderUtils.OS2IP(rsaParams.P, false);
     _Q                = RSAProviderUtils.OS2IP(rsaParams.Q, false);
     _DP               = RSAProviderUtils.OS2IP(rsaParams.DP, false);
     _DQ               = RSAProviderUtils.OS2IP(rsaParams.DQ, false);
     _InverseQ         = RSAProviderUtils.OS2IP(rsaParams.InverseQ, false);
     _Has_CRT_Info     = true;
     _Has_PUBLIC_Info  = true;
     _Has_PRIVATE_Info = true;
 }
 /// <summary>
 ///     Initialize the RSA class. For CRT.
 /// </summary>
 /// <param name="Modulus">Modulus of the RSA key.</param>
 /// <param name="Exponent">Exponent of the RSA key</param>
 /// ///
 /// <param name="D">Exponent of the RSA key</param>
 /// <param name="P">P paramater of RSA Algorithm.</param>
 /// <param name="Q">Q paramater of RSA Algorithm.</param>
 /// <param name="DP">DP paramater of RSA Algorithm.</param>
 /// <param name="DQ">DQ paramater of RSA Algorithm.</param>
 /// <param name="InverseQ">InverseQ paramater of RSA Algorithm.</param>
 /// <param name="ModulusSize">Modulus size in number of bits. Ex: 512, 1024, 2048, 4096 etc.</param>
 public RSAProviderParameters(byte[] Modulus, byte[] Exponent, byte[] D, byte[] P, byte[] Q, byte[] DP, byte[] DQ,
                              byte[] InverseQ, int ModulusSize)
 {
     // rsaParams;
     OctetsInModulus = ModulusSize / 8;
     E                = RSAProviderUtils.OS2IP(Exponent, false);
     N                = RSAProviderUtils.OS2IP(Modulus, false);
     this.D           = RSAProviderUtils.OS2IP(D, false);
     this.P           = RSAProviderUtils.OS2IP(P, false);
     this.Q           = RSAProviderUtils.OS2IP(Q, false);
     this.DP          = RSAProviderUtils.OS2IP(DP, false);
     this.DQ          = RSAProviderUtils.OS2IP(DQ, false);
     this.InverseQ    = RSAProviderUtils.OS2IP(InverseQ, false);
     HasCRTInfo       = true;
     Has_PUBLIC_Info  = true;
     Has_PRIVATE_Info = true;
 }
Exemplo n.º 10
0
 /// <summary>
 ///     Initialize the RSA class from a XML KeyInfo string.
 /// </summary>
 /// <param name="keyInfo">XML Containing Key Information</param>
 /// <param name="ModulusSize">Length of RSA Modulus in bits.</param>
 public RSAProvider(string keyInfo, int ModulusSize)
 {
     rsaParams = RSAProviderUtils.GetRSAProviderParameters(keyInfo, ModulusSize);
     UseCRTForPublicDecryption = true;
 }
Exemplo n.º 11
0
        private byte[] Decrypt(byte[] Message, byte[] Parameters, bool usePrivate, bool fOAEP)
        {
            var EM = new byte[0];

            try
            {
                if (usePrivate && UseCRTForPublicDecryption && rsaParams.HasCRTInfo)
                {
                    EM = RSADecryptPrivateCRT(Message);
                }
                else
                {
                    EM = RSAProcess(Message, usePrivate);
                }
            }
            catch (CryptographicException ex)
            {
                throw new CryptographicException("Exception while Decryption: " + ex.Message);
            }
            catch
            {
                throw new Exception("Exception while Decryption: ");
            }

            try
            {
                if (fOAEP) //DECODE OAEP
                {
                    if ((EM.Length == rsaParams.OctetsInModulus) && (EM.Length > 2 * rsaParams.hLen + 1))
                    {
                        byte[] maskedSeed;
                        byte[] maskedDB;
                        var    pHash = rsaParams.ComputeHash(Parameters);
                        if (EM[0] == 0) // RFC3447 Format : http://tools.ietf.org/html/rfc3447
                        {
                            maskedSeed = EM.ToList().GetRange(1, rsaParams.hLen).ToArray();
                            maskedDB   =
                                EM.ToList().GetRange(1 + rsaParams.hLen, EM.Length - rsaParams.hLen - 1).ToArray();
                            var seedMask = MGF(maskedDB, rsaParams.hLen);
                            var seed     = RSAProviderUtils.XOR(maskedSeed, seedMask);
                            var dbMask   = MGF(seed, rsaParams.OctetsInModulus - rsaParams.hLen - 1);
                            var DB       = RSAProviderUtils.XOR(maskedDB, dbMask);

                            if (DB.Length >= rsaParams.hLen + 1)
                            {
                                var _pHash = DB.ToList().GetRange(0, rsaParams.hLen).ToArray();
                                var PS_M   = DB.ToList().GetRange(rsaParams.hLen, DB.Length - rsaParams.hLen);
                                var pos    = PS_M.IndexOf(0x01);
                                if (pos >= 0 && (pos < PS_M.Count))
                                {
                                    var    _01_M = PS_M.GetRange(pos, PS_M.Count - pos);
                                    byte[] M;
                                    if (_01_M.Count > 1)
                                    {
                                        M = _01_M.GetRange(1, _01_M.Count - 1).ToArray();
                                    }
                                    else
                                    {
                                        M = new byte[0];
                                    }
                                    var success = true;
                                    for (var i = 0; i < rsaParams.hLen; i++)
                                    {
                                        if (_pHash[i] != pHash[i])
                                        {
                                            success = false;
                                            break;
                                        }
                                    }

                                    if (success)
                                    {
                                        return(M);
                                    }
                                    M = new byte[rsaParams.OctetsInModulus]; //Hash Match Failure.
                                    throw new CryptographicException("OAEP Decode Error");
                                }
                                // #3: Invalid Encoded Message Length.
                                throw new CryptographicException("OAEP Decode Error");
                            }
                            // #2: Invalid Encoded Message Length.
                            throw new CryptographicException("OAEP Decode Error");
                        }
                        //OAEP : THIS STADNARD IS NOT IMPLEMENTED
                        throw new CryptographicException("OAEP Decode Error");
                    }
                    // #1: Invalid Encoded Message Length.
                    throw new CryptographicException("OAEP Decode Error");
                }
                if (EM.Length >= 11)
                {
                    if ((EM[0] == 0x00) && (EM[1] == 0x02))
                    {
                        var startIndex = 2;
                        var PS         = new List <byte>();
                        for (var i = startIndex; i < EM.Length; i++)
                        {
                            if (EM[i] != 0)
                            {
                                PS.Add(EM[i]);
                            }
                            else
                            {
                                break;
                            }
                        }

                        if (PS.Count >= 8)
                        {
                            var DecodedDataIndex = startIndex + PS.Count + 1;
                            if (DecodedDataIndex < EM.Length - 1)
                            {
                                var DATA = new List <byte>();
                                for (var i = DecodedDataIndex; i < EM.Length; i++)
                                {
                                    DATA.Add(EM[i]);
                                }
                                return(DATA.ToArray());
                            }
                            return(new byte[0]);
                            //throw new CryptographicException("PKCS v1.5 Decode Error #4: No Data");
                        }
                        // #3: Invalid Key / Invalid Random Data Length
                        throw new CryptographicException("PKCS v1.5 Decode Error");
                    }
                    // #2: Invalid Key / Invalid Identifiers
                    throw new CryptographicException("PKCS v1.5 Decode Error");
                }
                // #1: Invalid Key / PKCS Encoding
                throw new CryptographicException("PKCS v1.5 Decode Error");
            }
            catch (CryptographicException ex)
            {
                throw new CryptographicException("Exception while decoding: " + ex.Message);
            }
            catch
            {
                throw new CryptographicException("Exception while decoding");
            }
        }
Exemplo n.º 12
0
        private byte[] RSAProcessEncodeOAEP(byte[] M, byte[] P, bool usePrivate)
        {
            //                           +----------+---------+-------+
            //                      DB = |  lHash   |    PS   |   M   |
            //                           +----------+---------+-------+
            //                                          |
            //                +----------+              V
            //                |   seed   |--> MGF ---> XOR
            //                +----------+              |
            //                      |                   |
            //             +--+     V                   |
            //             |00|    XOR <----- MGF <-----|
            //             +--+     |                   |
            //               |      |                   |
            //               V      V                   V
            //             +--+----------+----------------------------+
            //       EM =  |00|maskedSeed|          maskedDB          |
            //             +--+----------+----------------------------+

            var mLen = M.Length;

            if (mLen > rsaParams.OctetsInModulus - 2 * rsaParams.hLen - 2)
            {
                throw new ArgumentException("Message too long.");
            }
            var PS = new byte[rsaParams.OctetsInModulus - mLen - 2 * rsaParams.hLen - 2];
            //4. pHash = Hash(P),
            var pHash = rsaParams.ComputeHash(P);

            //5. DB = pHash||PS||01||M.
            var _DB = new List <byte>();

            _DB.AddRange(pHash);
            _DB.AddRange(PS);
            _DB.Add(0x01);
            _DB.AddRange(M);
            var DB = _DB.ToArray();

            //6. Generate a random octet string seed of length hLen.
            var seed = new byte[rsaParams.hLen];

            rng.GetBytes(seed);

            //7. dbMask = MGF(seed, k - hLen -1).
            var dbMask = MGF(seed, rsaParams.OctetsInModulus - rsaParams.hLen - 1);

            //8. maskedDB = DB XOR dbMask
            var maskedDB = RSAProviderUtils.XOR(DB, dbMask);

            //9. seedMask = MGF(maskedDB, hLen)
            var seedMask = MGF(maskedDB, rsaParams.hLen);

            //10. maskedSeed = seed XOR seedMask.
            var maskedSeed = RSAProviderUtils.XOR(seed, seedMask);

            //11. EM = 0x00 || maskedSeed || maskedDB.
            var result = new List <byte>();

            result.Add(0x00);
            result.AddRange(maskedSeed);
            result.AddRange(maskedDB);

            return(RSAProcess(result.ToArray(), usePrivate));
        }