示例#1
0
        /// <summary>
        /// Writes the core.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="value">The value.</param>
        protected override void WriteCore(Stream stream, RSAParameters value)
        {
            Requires.NotNull(stream, "stream");

            var sequence = new MemoryStream();

            if (KeyFormatter.HasPrivateKey(value))
            {
                // Only include the version element if this is a private key.
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, new byte[1]));
            }

            sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, this.prependLeadingZeroOnCertainElements ? PrependLeadingZero(value.Modulus) : value.Modulus));
            sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, value.Exponent));
            if (KeyFormatter.HasPrivateKey(value))
            {
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, value.D));
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, this.prependLeadingZeroOnCertainElements ? PrependLeadingZero(value.P) : value.P));
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, this.prependLeadingZeroOnCertainElements ? PrependLeadingZero(value.Q) : value.Q));
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, this.prependLeadingZeroOnCertainElements ? PrependLeadingZero(value.DP) : value.DP));
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, value.DQ));
                sequence.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Primitive, Asn.BerTag.Integer, this.prependLeadingZeroOnCertainElements ? PrependLeadingZero(value.InverseQ) : value.InverseQ));
            }

            stream.WriteAsn1Element(new Asn.DataElement(Asn.BerClass.Universal, Asn.BerPC.Constructed, Asn.BerTag.Sequence, sequence.ToArray()));
        }
示例#2
0
        static TestData()
        {
            RSAParameters rp = new RSAParameters();
            rp.D = ("2806880f41dfba6ea9cb91f141c07e09cc0def786030162e1947c50d427d21dc5c0779ded52c50e570665884ba0ba32977c6"
                  + "3019da0d255de458c9f421f0a17cd70bc21ea1e97152d3ded5ef1f17927bf2c03f83a72534033baacc670443d4e9c80e2d87"
                  + "e206a3c3094ee5b20c3a1edf99c275f8f63cd4de7cdea326050cb151").HexToByteArray();

            rp.DP = ("0aa6fc0436a24aa03c7a4d0b4cb84b75b9475eb0410ffaaa2a2c6d4dd8d4c3a5ac815bdeb93245babef613f983e4770d63d0"
                   + "d931e33f0509019a1e431e6b5911").HexToByteArray();

            rp.DQ = ("b7944d4d4846708c33adb0ad964623ad0e55d7c5bbd6475d25b12fbb39ab8c75794fdc977d67f54833ba59acbec8f3d91ddb"
                   + "f29d0e780d52f8c656cad787fad5").HexToByteArray();

            rp.Exponent = ("010001").HexToByteArray();

            rp.InverseQ = ("8fdd8821b7fcc6e907436bc33d7311f9344ee18a3af36429c550f34f83c4c93fd0429f63bdc502db9cc03d3d857a6354e98b"
                         + "db7c76b3ab54c32cdae75c539f2c").HexToByteArray();

            rp.Modulus = ("c7b5012552672f812a015bf3356abdfe4964cfe2ae35b8aba819120c58ffa2f1fc0f512e76fd22e6d32646ceea78829a9cbb"
                        + "2dbe5c66d14390e1bcef05afbababfe1f5ca07983b1f688a01b2beef8886b05df9e9420e65a1c0dc605ccfa2e27d84b39433"
                        + "ffcd07441ef5be8ab80497bc553fce022c7620922d1d624b6e3babe1").HexToByteArray();

            rp.P = ("c7eb601fdd49b22eda5b9a5ccb2fcfc35a660bb3bd2872857c864432e32916c2231e3b3da8afddc3efa38d04f9b1a08a08ab"
                  + "08b4603ff28345ba32d24de3cfa5").HexToByteArray();

            rp.Q = ("ffba608710355472b48b41e57eadd19a3f1a5d2fc1baa3d6210520c95694f11a065a16354827abdb06a59c3616f5ff2c5ca3"
                  + "be835f1278e9a9e9f0373027b68d").HexToByteArray();

            TestRsaKeyPair = rp;
        }
        /// <summary>
        /// Writes a key to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="parameters">The RSA parameters of the key.</param>
        protected override void WriteCore(Stream stream, RSAParameters parameters)
        {
            Requires.NotNull(stream, "stream");

            var rootElement = new Asn.DataElement(
                Asn.BerClass.Universal,
                Asn.BerPC.Constructed,
                Asn.BerTag.Sequence,
                new Asn.DataElement(
                    Asn.BerClass.Universal,
                    Asn.BerPC.Constructed,
                    Asn.BerTag.Sequence,
                    new Asn.DataElement(
                        Asn.BerClass.Universal,
                        Asn.BerPC.Primitive,
                        Asn.BerTag.ObjectIdentifier,
                        Pkcs1KeyFormatter.RsaEncryptionObjectIdentifier),
                    new Asn.DataElement(
                        Asn.BerClass.Universal,
                        Asn.BerPC.Primitive,
                        Asn.BerTag.Null,
                        new byte[0])),
                new Asn.DataElement(
                        Asn.BerClass.Universal,
                        Asn.BerPC.Primitive,
                        Asn.BerTag.BitString,
                        PrependLeadingZero(KeyFormatter.Pkcs1PrependZeros.Write(parameters, includePrivateKey: false), alwaysPrependZero: true)));
            stream.WriteAsn1Element(rootElement);
        }
示例#4
0
        /// <summary>
        /// Writes a key to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="parameters">The RSA parameters of the key.</param>
        protected override void WriteCore(Stream stream, RSAParameters parameters)
        {
            var rootElement = new Asn.DataElement(
                Asn.BerClass.Universal,
                Asn.BerPC.Constructed,
                Asn.BerTag.Sequence,
                new Asn.DataElement( // Version 0
                    Asn.BerClass.Universal,
                    Asn.BerPC.Primitive,
                    Asn.BerTag.Integer,
                    new byte[] { 0x00 }),
                new Asn.DataElement(
                    Asn.BerClass.Universal,
                    Asn.BerPC.Constructed,
                    Asn.BerTag.Sequence,
                    new Asn.DataElement( // privateKeyAlgorithm
                        Asn.BerClass.Universal,
                        Asn.BerPC.Primitive,
                        Asn.BerTag.ObjectIdentifier,
                        Pkcs1KeyFormatter.RsaEncryptionObjectIdentifier),
                    new Asn.DataElement(
                        Asn.BerClass.Universal,
                        Asn.BerPC.Primitive,
                        Asn.BerTag.Null,
                        new byte[0])),
                new Asn.DataElement( // rsaPrivateKey
                    Asn.BerClass.Universal,
                    Asn.BerPC.Primitive,
                    Asn.BerTag.OctetString,
                    KeyFormatter.Pkcs1PrependZeros.Write(parameters, HasPrivateKey(parameters))),
                new Asn.DataElement(
                    Asn.BerClass.ContextSpecific,
                    Asn.BerPC.Constructed,
                    Asn.BerTag.EndOfContent,
                    new Asn.DataElement(
                        Asn.BerClass.Universal,
                        Asn.BerPC.Constructed,
                        Asn.BerTag.Sequence,
                        new Asn.DataElement(
                            Asn.BerClass.Universal,
                            Asn.BerPC.Primitive,
                            Asn.BerTag.ObjectIdentifier,
                            new byte[] { 0x55, 0x1d, 0x0f }),
                        new Asn.DataElement(
                            Asn.BerClass.Universal,
                            Asn.BerPC.Constructed,
                            Asn.BerTag.SetAndSetOf,
                            new Asn.DataElement(
                                Asn.BerClass.Universal,
                                Asn.BerPC.Primitive,
                                Asn.BerTag.BitString,
                                new byte[] { 0x00, 0x10 })))));

            Asn.WriteAsn1Element(stream, rootElement);
        }
示例#5
0
 /// <summary>
 /// Throws an exception if the specified RSAParameters cannot be
 /// serialized in the CAPI format.
 /// </summary>
 /// <param name="parameters">The RSA parameters.</param>
 internal static void VerifyCapiCompatibleParameters(RSAParameters parameters)
 {
     try
     {
         KeyFormatter.VerifyFormat(IsCapiCompatible(parameters), "Private key parameters have lengths that are not supported by CAPI.");
     }
     catch (FormatException ex)
     {
         throw new NotSupportedException(ex.Message, ex);
     }
 }
示例#6
0
        internal static unsafe RSAParameters ExportRsaParameters(SafeRsaHandle key, bool includePrivateParameters)
        {
            Debug.Assert(
                key != null && !key.IsInvalid,
                "Callers should check the key is invalid and throw an exception with a message");

            if (key == null || key.IsInvalid)
            {
                throw new CryptographicException();
            }

            RSAParameters rsaParameters;
            bool addedRef = false;

            try
            {
                key.DangerousAddRef(ref addedRef);
                RSA_ST* rsaStructure = (RSA_ST*)key.DangerousGetHandle();

                int modulusSize = RSA_size(key);

                // RSACryptoServiceProvider expects P, DP, Q, DQ, and InverseQ to all
                // be padded up to half the modulus size.
                int halfModulus = modulusSize / 2;

                rsaParameters = new RSAParameters
                {
                    Modulus = ExtractBignum(rsaStructure->n, modulusSize),
                    Exponent = ExtractBignum(rsaStructure->e, 0),
                };

                if (includePrivateParameters)
                {
                    rsaParameters.D = ExtractBignum(rsaStructure->d, modulusSize);
                    rsaParameters.P = ExtractBignum(rsaStructure->p, halfModulus);
                    rsaParameters.DP = ExtractBignum(rsaStructure->dmp1, halfModulus);
                    rsaParameters.Q = ExtractBignum(rsaStructure->q, halfModulus);
                    rsaParameters.DQ = ExtractBignum(rsaStructure->dmq1, halfModulus);
                    rsaParameters.InverseQ = ExtractBignum(rsaStructure->iqmp, halfModulus);
                }
            }
            finally
            {
                if (addedRef)
                {
                    key.DangerousRelease();
                }
            }

            return rsaParameters;
        }
示例#7
0
 public override bool FromSFSObject(Sfs2X.Entities.Data.ISFSObject data)
 {
     // We just pull the data straight out of the packet because we don't have a GetByteArray that works with encryption
     bool retVal = false;
     if (data.ContainsKey("key"))
     {
         ISFSObject publicKeyData = data.GetSFSObject("key");
         var tempParams = new RSAParameters();
         tempParams.Modulus = publicKeyData.GetByteArray("mod").Bytes;
         tempParams.Exponent = publicKeyData.GetByteArray("exp").Bytes;
         parameters = tempParams;
     }
     return retVal;
 }
        public static void PublicOnly_WithNoPrivate()
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                RSAParameters publicParams = new RSAParameters
                {
                    Modulus = TestData.RSA1024Params.Modulus,
                    Exponent = TestData.RSA1024Params.Exponent,
                };

                rsa.ImportParameters(publicParams);
                Assert.True(rsa.PublicOnly);
            }
        }
示例#9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        var code = Request.QueryString["code"];


        //send request to github server to get access token
        HttpWebRequest req = WebRequest.Create("https://github.com/login/oauth/access_token?client_id=TODO:<your own client id>&client_secret=TODO:<your own client secret>&code=" + code) as HttpWebRequest;
        req.Method = "POST";
        HttpWebResponse rsps = req.GetResponse() as HttpWebResponse;
        var str = new StreamReader(rsps.GetResponseStream()).ReadToEnd();
        Match m = Regex.Match(str, "access_token=([^&]+)&token_type=([^&]+)");


        //RSA encrypt access token with public key from browser side
        RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
        RSAParameters publicKey = new RSAParameters();
        publicKey.Modulus = literal2bytes(Request.Cookies["modulus"].Value);
        publicKey.Exponent = literal2bytes(Request.Cookies["exponent"].Value);
        rsa.ImportParameters(publicKey);
        byte[] result = rsa.Encrypt(Encoding.UTF8.GetBytes(m.Groups[1].ToString()), false);
        StringBuilder access_token = new StringBuilder();
        for (var i = 0; i < result.Length; i++)
        {
            access_token.Append(result[i].ToString("x2"));
        }

        //write encrypted access_token back into cookie
        HttpCookie cookie = new HttpCookie("access_token");
        DateTime dt = DateTime.Now;
        TimeSpan ts = new TimeSpan(0, 0, 0, 0);
        cookie.Expires = dt.Add(ts);
        cookie.Value = access_token.ToString();
        Response.AppendCookie(cookie);


        cookie = new HttpCookie("token_type");
        dt = DateTime.Now;
        ts = new TimeSpan(0, 0, 0, 0);
        cookie.Expires = dt.Add(ts);
        cookie.Value = m.Groups[2].ToString();
        Response.AppendCookie(cookie);

        //now jump back, only the browser side could decrypt the access_token from cookie
        Response.Redirect("TODO:<your own address>");
    }
示例#10
0
    public static byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo)
    {
        try
        {
            byte[] encryptedData;
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                RSA.ImportParameters(RSAKeyInfo);
                encryptedData = RSA.Encrypt(DataToEncrypt, false);
            }
            return encryptedData;
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }
示例#11
0
        internal static RSAParameters ExportRsaParameters(SafeRsaHandle key, bool includePrivateParameters)
        {
            Debug.Assert(
                key != null && !key.IsInvalid,
                "Callers should check the key is invalid and throw an exception with a message");

            if (key == null || key.IsInvalid)
            {
                throw new CryptographicException();
            }

            IntPtr n, e, d, p, dmp1, q, dmq1, iqmp;
            if (!GetRsaParameters(key, out n, out e, out d, out p, out dmp1, out q, out dmq1, out iqmp))
            {
                throw new CryptographicException();
            }

            int modulusSize = Crypto.RsaSize(key);

            // RSACryptoServiceProvider expects P, DP, Q, DQ, and InverseQ to all
            // be padded up to half the modulus size.
            int halfModulus = modulusSize / 2;

            RSAParameters rsaParameters = new RSAParameters
            {
                Modulus = Crypto.ExtractBignum(n, modulusSize),
                Exponent = Crypto.ExtractBignum(e, 0),
            };

            if (includePrivateParameters)
            {
                rsaParameters.D = Crypto.ExtractBignum(d, modulusSize);
                rsaParameters.P = Crypto.ExtractBignum(p, halfModulus);
                rsaParameters.DP = Crypto.ExtractBignum(dmp1, halfModulus);
                rsaParameters.Q = Crypto.ExtractBignum(q, halfModulus);
                rsaParameters.DQ = Crypto.ExtractBignum(dmq1, halfModulus);
                rsaParameters.InverseQ = Crypto.ExtractBignum(iqmp, halfModulus);
            }

            return rsaParameters;
        }
  ///
  /// SEQUENCE (a)
  ///  +- INTEGER (V)              // Version - 0 (v1998)
  ///  +- SEQUENCE (b)
  ///  |   +- OID (oid)            // 1.2.840.113549.1.1.1
  ///  |   +- Nil (c)
  ///  +- OCTETSTRING(PRVKY) (os)  // Private Key Parameter
  ///
  ///  However, OCTETSTRING(PRVKY) wraps
  ///    SEQUENCE(
  ///      INTEGER(0)              // Version - 0 (v1998)
  ///      INTEGER(N)
  ///      INTEGER(E)
  ///      INTEGER(D)
  ///      INTEGER(P)
  ///      INTEGER(Q)
  ///      INTEGER(DP)
  ///      INTEGER(DQ)
  ///      INTEGER(InvQ)
  ///    )
  public static byte[] RSAKeyToASN1(RSAParameters PrivateKey) {
    ASN1 v = ASN1Convert.FromUnsignedBigInteger(new byte[] {0});

    ASN1 b = PKCS7.AlgorithmIdentifier ("1.2.840.113549.1.1.1");

    ASN1 os = new ASN1(0x30);
    os.Add(ASN1Convert.FromUnsignedBigInteger(new byte[] {0}));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Modulus));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Exponent));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.D));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.P));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.Q));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DP));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.DQ));
    os.Add(ASN1Convert.FromUnsignedBigInteger(PrivateKey.InverseQ));

    ASN1 pem = new ASN1(0x30);
    pem.Add(v);
    pem.Add(b);
    // Make this into an OCTET string
    pem.Add(new ASN1(0x04, os.GetBytes()));
    return pem.GetBytes();
  }
        /// <inheritdoc/>
        public ICryptographicKey CreateKeyPair(int keySize)
        {
            Requires.Range(keySize > 0, "keySize");

            var keyGen = KeyPairGenerator.GetInstance("RSA");
            keyGen.Initialize(keySize);
            var key = keyGen.GenerateKeyPair();

            var privateKeyParameters = key.Private.JavaCast<IRSAPrivateCrtKey>();
            var parameters = new RSAParameters
            {
                Modulus = privateKeyParameters.Modulus.ToByteArray(),
                Exponent = privateKeyParameters.PublicExponent.ToByteArray(),
                P = privateKeyParameters.PrimeP.ToByteArray(),
                Q = privateKeyParameters.PrimeQ.ToByteArray(),
                DP = privateKeyParameters.PrimeExponentP.ToByteArray(),
                DQ = privateKeyParameters.PrimeExponentQ.ToByteArray(),
                InverseQ = privateKeyParameters.CrtCoefficient.ToByteArray(),
                D = privateKeyParameters.PrivateExponent.ToByteArray(),
            };

            return new RsaCryptographicKey(key.Public, key.Private, parameters, this.algorithm);
        }
示例#14
0
        /// <summary>
        /// Determines whether the specified RSA parameters
        /// can be represented in the CAPI format.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <returns><c>true</c> if CAPI is compatible with these parameters; <c>false</c> otherwise.</returns>
        internal static bool IsCapiCompatible(RSAParameters parameters)
        {
            // Only private keys have this restriction.
            if (!KeyFormatter.HasPrivateKey(parameters))
            {
                return true;
            }

            int halfModulusLength = (parameters.Modulus.Length + 1) / 2;

            // These are the same assertions that Windows crypto lib itself
            // follows when it returns 'bad data'.
            // CAPI's file format does not include lengths for parameters.
            // Instead it makes some assumptions about their relative lengths
            // which make it fundamentally incompatible with some private keys
            // generated by iOS.
            return
                halfModulusLength == parameters.P.Length &&
                halfModulusLength == parameters.Q.Length &&
                halfModulusLength == parameters.DP.Length &&
                halfModulusLength == parameters.DQ.Length &&
                halfModulusLength == parameters.InverseQ.Length &&
                parameters.Modulus.Length == parameters.D.Length;
        }
示例#15
0
        public static RSA CreateRsaProviderFromPublicKey(string publicKeyString, string signType)
        {
            byte[] seqOid = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq    = new byte[15];

            var x509Key = Convert.FromBase64String(publicKeyString);

            using (MemoryStream mem = new MemoryStream(x509Key))
            {
                using (BinaryReader binr = new BinaryReader(mem))
                {
                    byte   bt       = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    seq = binr.ReadBytes(15);
                    if (!CompareBytearrays(seq, seqOid))
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8203)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    bt = binr.ReadByte();
                    if (bt != 0x00)
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    byte lowbyte  = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102)
                    {
                        lowbyte = binr.ReadByte();
                    }
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte();
                        lowbyte  = binr.ReadByte();
                    }
                    else
                    {
                        return(null);
                    }
                    byte[] modint  = { lowbyte, highbyte, 0x00, 0x00 };
                    int    modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        binr.ReadByte();
                        modsize -= 1;
                    }

                    byte[] modulus = binr.ReadBytes(modsize);

                    if (binr.ReadByte() != 0x02)
                    {
                        return(null);
                    }
                    int    expbytes = binr.ReadByte();
                    byte[] exponent = binr.ReadBytes(expbytes);

                    RSA rsa = System.Security.Cryptography.RSA.Create();
                    rsa.KeySize = signType == "RSA" ? 1024 : 2048;
                    RSAParameters rsaKeyInfo = new RSAParameters
                    {
                        Modulus  = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);

                    return(rsa);
                }
            }
        }
示例#16
0
    /*	static void Main()
    {
        try
        {
            //Create a UnicodeEncoder to convert between byte array and string.
            UnicodeEncoding ByteConverter = new UnicodeEncoding();

            //Create byte arrays to hold original, encrypted, and decrypted data.
            byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
            byte[] encryptedData;
            byte[] decryptedData;

            //Create a new instance of RSACryptoServiceProvider to generate
            //public and private key data.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Pass the data to ENCRYPT, the public key information
            //(using RSACryptoServiceProvider.ExportParameters(false),
            //and a boolean flag specifying no OAEP padding.
            encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(false), false);

            //Pass the data to DECRYPT, the private key information
            //(using RSACryptoServiceProvider.ExportParameters(true),
            //and a boolean flag specifying no OAEP padding.
            decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false);

            //Display the decrypted plaintext to the console.
            Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
        }
        catch(ArgumentNullException)
        {
            //Catch this exception in case the encryption did
            //not succeed.
            Console.WriteLine("Encryption failed.");

        }
    }
    */
    public void RSAcreatekeys(int size)
    {
        //Generate a public/private key pair.
        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(size);
        rsaks = size;

        //Save the public key information to an RSAParameters structure.
        rsaki = RSA.ExportParameters(true);
    }
示例#17
0
 public RSAOpenSsl(RSAParameters parameters)
 {
     throw new NotImplementedException();
 }
示例#18
0
        private static void DispatchPost(HttpListenerContext context)
        {
            var request = context.Request;
            var response = context.Response;

            string poster = request.Headers.Get("Post-User");
            string signature = request.Headers.Get("Post-Signature");

            if ((poster == null) || (signature == null))
                throw new InvalidOperationException("Invalid request.");

            byte[] payload;
            using (var ms = new MemoryStream())
            {
                request.InputStream.CopyTo(ms);
                payload = ms.ToArray();
            }

            string pubkey;
            {
                var cmd = db.CreateCommand();
                cmd.CommandText = @"SELECT `Pubkey` FROM `Writers` WHERE `Name`=@name;";
                cmd.Parameters.AddWithValue("@name", poster);
                pubkey = cmd.ExecuteScalar() as string;
            }

            RSAParameters args = new RSAParameters();
            args.Exponent = GetHexBytes(pubkey.Split('-')[0]);
            args.Modulus = GetHexBytes(pubkey.Split('-')[1]);

            if (VerifyData(payload, signature, args) == false)
            {
                response.StatusCode = 400;
                return;
            }

            int uid;
            {
                var cmd = db.CreateCommand();
                cmd.CommandText = @"SELECT `ID` FROM `Writers` WHERE `Name`=@name;";
                cmd.Parameters.AddWithValue("@name", poster);
                uid = (int)(long)cmd.ExecuteScalar();
            }

            WritePost(uid, Encoding.UTF8.GetString(payload));
        }
示例#19
0
        internal static void ValidateParameters(ref RSAParameters rsaParams)
        {
            Assert.NotNull(rsaParams.Modulus);
            Assert.NotNull(rsaParams.Exponent);

            // Key compatibility: RSA as an algorithm is achievable using just N (Modulus),
            // E (public Exponent) and D (private exponent).  Having all of the breakdowns
            // of D make the algorithm faster, and shipped versions of RSACryptoServiceProvider
            // have thrown if D is provided and the rest of the private key values are not.
            // So, here we're going to assert that none of them were null for private keys.

            if (rsaParams.D == null)
            {
                Assert.Null(rsaParams.P);
                Assert.Null(rsaParams.DP);
                Assert.Null(rsaParams.Q);
                Assert.Null(rsaParams.DQ);
                Assert.Null(rsaParams.InverseQ);
            }
            else
            {
                Assert.NotNull(rsaParams.P);
                Assert.NotNull(rsaParams.DP);
                Assert.NotNull(rsaParams.Q);
                Assert.NotNull(rsaParams.DQ);
                Assert.NotNull(rsaParams.InverseQ);
            }
        }
示例#20
0
        public static RSAParameters GetRsaParameters_2048_Bit_PKCS1_v1_5(byte[] publicKey)
        {
            // From RFC 2313, PKCS #1, Version 1.5:http://tools.ietf.org/html/rfc2313
            // 7.1 Public-key syntax
            //
            // An RSA public key shall have ASN.1 type RSAPublicKey:
            //
            // RSAPublicKey ::= SEQUENCE {
            //      modulus INTEGER, -- n
            //      publicExponent INTEGER -- e }
            //
            // (This type is specified in X.509 and is retained here for
            // compatibility.)
            //
            // The fields of type RSAPublicKey have the following meanings:
            //
            // o    modulus is the modulus n.
            //
            // o    publicExponent is the public exponent e.
            //

            // BER Encoding
            // http://en.wikipedia.org/wiki/Distinguished_Encoding_Rules#DER_encoding
            //
            // ASN.1 Format with DER (subset of BER) encoding
            // http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One

            // It's important to know that the RSAPublicKey is encoded in an ASN.1 (Abstract Syntax Notation One)
            // representation using DER encoding. I had to use a couple articles on Wikipedia to understand
            // ASN.1 and then I manually decoded the public key to determine where the modulus and exponent were
            // located within the 2048 bit public key from Google.
            //
            // Bytes of sample 2048 bit Public Key (hexadecimal) with ASN.1 decoding shown for each byte
            // 30		Identifier: 30 hex = 00110000, P/C = Constructed (1), TAG = SEQUENCE (10000)
            // 82		Length: 82 hex = 130 decimal = 10000010, Long Form Length with 2 octects for length
            // 01		Byte 1/2 of long form length
            // 22		Byte 2/2 of long form length, 0x01 0x22, 00000001 00100010 = 290 bytes
            // 30		Identifier: 30 hex = 00110000, P/C = Constructed (1), TAG = SEQUENCE (10000)
            // 0d		Length: 0d hex = 13 decimal
            // 06		Identifier: 06 hex = 00000110, P/C = Primitive (0), TAG = OBJECT IDENTIFIER (00110)
            // 09		Length: 09 hex = 9 decimal
            // 2a		Byte 1/9 of OBJECT IDENTIFIER
            // 86		Byte 2/9 of OBJECT IDENTIFIER
            // 48		Byte 3/9 of OBJECT IDENTIFIER
            // 86		Byte 4/9 of OBJECT IDENTIFIER
            // f7		Byte 5/9 of OBJECT IDENTIFIER
            // 0d		Byte 6/9 of OBJECT IDENTIFIER
            // 01		Byte 7/9 of OBJECT IDENTIFIER
            // 01		Byte 8/9 of OBJECT IDENTIFIER
            // 01		Byte 9/9 of OBJECT IDENTIFIER
            // 05		Identifier: 05 hex = 00000101, P/C = Primitive (0), TAG = NULL (00101)
            // 00		Length: 00 hex = 0 decimal
            // 03		Identifier: 03 hex = 00000011, P/C = Primitive (0), TAG = BIT STRING (00011)
            // 82		Length: 82 hex = 130 decimal = 10000010, Long Form Length with 2 octects for length
            // 01		Byte 1/2 of long form length
            // 0f		Byte 2/2 of long form length, 0x01 0x0f, 00000001 00010000 = 272 bytes
            // 00		???? Why 0, what does this mean?
            // 30		Identifier: 30 hex = 00110000, P/C = Constructed (1), TAG = SEQUENCE (10000)
            // 82		Length: 82 hex = 130 decimal = 10000010, Long Form Length with 2 octects for length
            // 01		Byte 1/2 of long form length
            // 0a		Byte 2/2 of long form length, 0x01 0x0a, 00000001 00001010 = 266 bytes
            // 02		Identifier: 02 hex = 00000010, P/C = Primitive (0), TAG = INTEGER (00010)
            // 82		Length: 82 hex = 130 decimal = 10000010, Long Form Length with 2 octects for length
            // 01		Byte 1/2 of long form length
            // 01		Byte 2/2 of long form length, 0x01 0x01, 00000001 00000001 = 257 bytes
            // 00		Byte 1/257 of modulus (padded left with a 0, leaves 256 actual values)
            // a9		Byte 2/257 of modulus... public key (modulus) starts here??
            // 87		Byte 3/257 of modulus
            // ....
            // 8f		Byte 255/257 of modulus
            // 14		Byte 256/257 of modulus93		Byte 257/257 of modulus
            // 02		Identifier: 02 hex = 00000010, P/C = Primitive (0), TAG = INTEGER (00010)
            // 03		Length: 03 hex = 3 decimal
            // 01		Byte 1/3 of exponent
            // 00		Byte 2/3 of exponent
            // 01		Byte 3/3 of exponent

            // Modulus starts at byte offset 33 and is 2048 bits (256 bytes)
            // Exponent starts at byte offset 291 and is 3 bytes

            RSAParameters rsaParameters = new RSAParameters();

            int modulusOffset  = 33;        // See comments above
            int modulusBytes   = 256;       // 2048 bit key
            int exponentOffset = 291;       // See comments above
            int exponentBytes  = 3;         // See comments above

            byte[] modulus = new byte[modulusBytes];
            for (int i = 0; i < modulusBytes; i++)
            {
                modulus[i] = publicKey[modulusOffset + i];
            }

            byte[] exponent = new byte[exponentBytes];
            for (int i = 0; i < exponentBytes; i++)
            {
                exponent[i] = publicKey[exponentOffset + i];
            }

            rsaParameters.Modulus  = modulus;
            rsaParameters.Exponent = exponent;

            return(rsaParameters);
        }
        public void MainFunction()
        {
            TcpListener Listener = null;
            TcpClient   client   = null;

            while (czyZalogowano == false)
            {
            }
            ;
            this.Dispatcher.Invoke(() => Login.Content = "Zalogowano");

            //Kryptografia asymetryczna
            var csp = new RSACryptoServiceProvider(2048);

            privKey = csp.ExportParameters(true);
            pubKey  = csp.ExportParameters(false);

            string pubKeyString;
            {
                var sw = new System.IO.StringWriter();
                var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                xs.Serialize(sw, pubKey);
                pubKeyString = sw.ToString();
            }


            {
                var sw = new System.IO.StringWriter();
                var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                xs.Serialize(sw, privKey);
                privKeyString = sw.ToString();
            }

            Encryption encryptPrivKey = new Encryption();

            byte[] newKey = new byte[32];
            byte[] tmpIV  = new byte[16];
            byte[] hash;

            SHA1 sha = new SHA1CryptoServiceProvider();

            hash = sha.ComputeHash(ASCIIEncoding.ASCII.GetBytes("user" + IdUser));
            Array.Copy(hash, newKey, hash.Length > 32 ? 32 : hash.Length);

            encryptPrivKey.Initialize(newKey, tmpIV);


            //Zaszyfriwanie klucza prywatnego z AES
            byte[] encryptedKey = encryptPrivKey.Encrypt(ASCIIEncoding.ASCII.GetBytes(privKeyString));

            //Zapisanie kluczy asymetrycznych
            File.WriteAllBytes("./Keys/PrivateKeys/" + IdUser, encryptedKey);
            File.WriteAllBytes("../../../../Keys/PublicKeys/" + IdUser, ASCIIEncoding.ASCII.GetBytes(pubKeyString));


            //Próba połącznia z serwerem
            int           tries     = 0;
            NetworkStream netstream = null;

            while (tries++ < 100)
            {
                try
                {
                    client    = new TcpClient("127.0.0.1", 5001);
                    netstream = client.GetStream();
                    break;
                }
                catch (Exception e1) { }
            }

            //// Wysyłannie IdUser
            //byte[] bytesToSend = BitConverter.GetBytes(IdUser);
            //netstream.Write(bytesToSend, 0, bytesToSend.Length);
            //// Potwierdzenie
            //while (netstream.ReadByte() != 'O') { };

            try
            {
                Listener = new TcpListener(IPAddress.Any, 5000);
                Listener.Start();
            }
            catch (Exception ex)
            {
                this.Dispatcher.Invoke(() => UserConsole.Text += ex.Message + "\n");
                return;
            }

            for (; ;)
            {
                try
                {
                    if (Listener.Pending())
                    {
                        client = Listener.AcceptTcpClient();
                        ReceiveFile(client);
                    }
                }
                catch (Exception ex)
                {
                    this.Dispatcher.Invoke(() => UserConsole.Text += ex.Message + "\n");
                }
            }
        }
示例#22
0
 /// <summary>
 /// Verifies a PKS1 signature of SHA1 digest
 /// </summary>
 /// <param name="xParam">Keys</param>
 /// <param name="xHash">Hash to sign</param>
 /// <param name="xSignature">Outputs the signature</param>
 /// <returns></returns>
 public static bool SignatureVerify(RSAParameters xParam, byte[] xHash, byte[] xSignature)
 {
     RSACryptoServiceProvider xRSACrypto = new RSACryptoServiceProvider();
     RSAPKCS1SignatureDeformatter xRSASigDeformat = new RSAPKCS1SignatureDeformatter();
     try { xRSACrypto.ImportParameters(xParam); }
     catch (Exception xerror) { throw xerror; }
     xRSASigDeformat.SetHashAlgorithm("SHA1");
     xRSASigDeformat.SetKey(xRSACrypto);
     try { return xRSASigDeformat.VerifySignature(xHash, xSignature); }
     catch { throw CryptoExcepts.CryptoVeri; }
 }
示例#23
0
        public static void Main(string[] args)
        {
            // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\Application.cs

            // X:\jsc.svn\examples\java\hybrid\JVMCLRCryptoKeyGenerate\JVMCLRCryptoKeyGenerate\Program.cs

            // Use Release Build to use jsc to generate java program
            // Use Debug Build to develop on .net

            //Revision: 1935
            //Author: zproxy
            //Date: Friday, July 24, 2009 5:16:24 PM
            //Message:
            //more RSA

            //Added : /core/ScriptCoreLibJava/BCLImplementation/System/Security/Cryptography/AsymmetricAlgorithm.cs
            //Added : /core/ScriptCoreLibJava/BCLImplementation/System/Security/Cryptography/RSA.cs
            //Added : /core/ScriptCoreLibJava/BCLImplementation/System/Security/Cryptography/RSACryptoServiceProvider.cs
            //Added : /core/ScriptCoreLibJava/BCLImplementation/System/Security/Cryptography/RSAParameters.cs



            System.Console.WriteLine("jvm ready! " + typeof(object).FullName);

            Console.WriteLine("System_Security_Cryptography_RSA. Crosscompiled from C# to Java. ");


            // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201511/20151103
            // will this work on chrome too? CSP bytes?
            var x = new byte[]
            {
                0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x82, 0x01
                , 0x00, 0x95, 0xcf, 0x63, 0x7d, 0x62, 0x1c, 0x23, 0xba, 0xae, 0x0f, 0xa4, 0xae, 0xb9, 0x91, 0x3d
                , 0xa5, 0x84, 0x4d, 0x94, 0x26, 0x0a, 0x75, 0x49, 0x53, 0xbb, 0x28, 0xa2, 0x07, 0x49, 0x0b, 0xbb
                , 0x68, 0x01, 0xe1, 0xf7, 0x85, 0x4d, 0x9f, 0xa8, 0xc3, 0x56, 0x56, 0x7f, 0xfa, 0xbe, 0x30, 0xe7
                , 0x4a, 0x80, 0x44, 0x57, 0x71, 0xf0, 0xfc, 0xcf, 0x13, 0x6f, 0x70, 0x51, 0x3d, 0x22, 0x22, 0xee
                , 0x50, 0x25, 0x0c, 0x96, 0x66, 0x59, 0xd4, 0x2e, 0xcd, 0x97, 0x71, 0x26, 0x34, 0x09, 0xe9, 0x72
                , 0xaa, 0x9d, 0x9e, 0x3a, 0x4e, 0xed, 0xdf, 0x5c, 0x64, 0x2a, 0x0a, 0xd0, 0x02, 0x90, 0x4c, 0xdf
                , 0x93, 0x08, 0x08, 0xeb, 0x62, 0x23, 0x66, 0xd8, 0x09, 0xa7, 0x40, 0xd7, 0xfc, 0x26, 0x77, 0x0b
                , 0x18, 0xda, 0xe9, 0x2a, 0x3b, 0x9b, 0x14, 0x42, 0x7a, 0x2e, 0xaa, 0x97, 0x4c, 0xf0, 0x4b, 0x30
                , 0xfe, 0xf5, 0x27, 0x32, 0x59, 0xcb, 0x85, 0x21, 0x35, 0x8d, 0xd5, 0x28, 0xb3, 0x7b, 0xeb, 0x97
                , 0x54, 0x28, 0x5f, 0x77, 0x01, 0x2e, 0x95, 0xb0, 0x7f, 0xd4, 0x2f, 0x7a, 0x5e, 0x67, 0x21, 0x11
                , 0xd5, 0x6c, 0x3a, 0x00, 0x4b, 0x88, 0x38, 0x09, 0xb9, 0x6b, 0x55, 0xa1, 0xe2, 0x3e, 0x78, 0xe1
                , 0x54, 0x53, 0x1d, 0xf3, 0x7d, 0x9d, 0x53, 0x8f, 0x81, 0x28, 0x02, 0xaf, 0x76, 0x82, 0x90, 0x0e
                , 0x1c, 0xfe, 0x7b, 0xf5, 0xdc, 0xba, 0xf7, 0xd3, 0x26, 0x75, 0xc7, 0xe1, 0x1e, 0x1e, 0x9d, 0x10
                , 0xc1, 0x4b, 0x9d, 0xc0, 0xfb, 0x30, 0x9e, 0x68, 0x3a, 0x8c, 0xb4, 0xb4, 0xae, 0xa9, 0x19, 0xf7
                , 0x7d, 0xeb, 0xc1, 0xbe, 0xe3, 0x7e, 0x9b, 0xa3, 0xa5, 0xf2, 0xe2, 0xbf, 0xa9, 0x73, 0xb1, 0x34
                , 0x38, 0x50, 0xfb, 0xcc, 0x06, 0x9f, 0x97, 0xd9, 0x4b, 0x3c, 0x98, 0x81, 0xd2, 0x2a, 0x54, 0x68
                , 0xcf, 0x82, 0x04, 0x72, 0x9d, 0x83, 0x9d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
                , 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
            };
            var data = new BinaryReader(new MemoryStream(x));

            data.BaseStream.Position = 0x1E;

            #region modulus
            var modulus_tag    = (byte)data.ReadByte();
            var modulus_length = (ushort)data.ReadByte();

            if (modulus_tag != 0x81)
            {
                modulus_length <<= 8;
                modulus_length  += (byte)data.ReadByte();
            }

            var modulus_data = data.ReadBytes(modulus_length);

            var exponent_tag    = (byte)data.ReadByte();
            var exponent_length = (ushort)data.ReadByte();

            var exponent_data = data.ReadBytes(exponent_length);
            #endregion

            RSACryptoServiceProvider rsa        = new RSACryptoServiceProvider();
            RSAParameters            RSAKeyInfo = new RSAParameters();
            RSAKeyInfo.Modulus  = modulus_data;
            RSAKeyInfo.Exponent = exponent_data;
            rsa.ImportParameters(RSAKeyInfo);
            rsa.ToXmlString(false).ToConsole();
        }
示例#24
0
        public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;


            // --------- Set up stream to decode the asn.1 encoded RSA private key ------
            MemoryStream mem      = new MemoryStream(privkey);
            BinaryReader binr     = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte         bt       = 0;
            ushort       twobytes = 0;
            int          elems    = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }


                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102) //version number
                {
                    return(null);
                }
                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }



                //------ all private key components are Integer sequences ----
                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);


                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);


                System.Console.WriteLine("showing components ..");
                if (verbose)
                {
                    showBytes("\nModulus", MODULUS);
                    showBytes("\nExponent", E);
                    showBytes("\nD", D);
                    showBytes("\nP", P);
                    showBytes("\nQ", Q);
                    showBytes("\nDP", DP);
                    showBytes("\nDQ", DQ);
                    showBytes("\nIQ", IQ);
                }


                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                CspParameters CspParameters = new CspParameters();
                CspParameters.Flags = CspProviderFlags.UseMachineKeyStore;
                RSACryptoServiceProvider RSA       = new RSACryptoServiceProvider(1024, CspParameters);
                RSAParameters            RSAparams = new RSAParameters();
                RSAparams.Modulus  = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D        = D;
                RSAparams.P        = P;
                RSAparams.Q        = Q;
                RSAparams.DP       = DP;
                RSAparams.DQ       = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch (Exception ex)
            {
                return(null);
            }
            finally
            {
                binr.Close();
            }
        }
        internal ServerNetwork(IServerContext context, INetworkHelper networkHelper, NetworkConfiguration configuration, RSAParameters rsaParameters) : base(
                networkHelper, configuration
                )
        {
            Context = context ?? throw new ArgumentNullException(nameof(context));

            Guid = Guid.NewGuid();

            var lidgrenInterface = new LidgrenInterface(this, typeof(NetServer), rsaParameters);

            lidgrenInterface.OnConnected           += HandleInterfaceOnConnected;
            lidgrenInterface.OnConnectionApproved  += HandleInterfaceOnConnectonApproved;
            lidgrenInterface.OnDisconnected        += HandleInterfaceOnDisconnected;
            lidgrenInterface.OnUnconnectedMessage  += HandleOnUnconnectedMessage;
            lidgrenInterface.OnConnectionRequested += HandleConnectionRequested;
            AddNetworkLayerInterface(lidgrenInterface);
        }
示例#26
0
        /// <summary>
        /// Gets the asn1 encoded public key for.
        /// </summary>
        /// <param name="keyParameters">The key parameters.</param>
        /// <returns></returns>
        public static byte[] GetAsn1EncodedPublicKeyFor(RSAParameters keyParameters)
        {
            var pubKey = GetRsaPublicKeyParameters(keyParameters);

            return(EncodeAsAsn1(pubKey));
        }
示例#27
0
        /// <summary>
        /// Verifies a simple RSA signature of the specified hash based on PKCS#1 1.5 padding schemes.
        /// </summary>
        /// <param name="rsa">The RSA.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="hashValue">The hash value.</param>
        /// <param name="signature">The signature.</param>
        /// <returns></returns>
        public static bool VerifySign(RSAParameters parameters, string hashAlgorithm, byte[] bytes, byte[] signature)
        {
            var hasher = HashAlgorithm.Create(hashAlgorithm);

            return(VerifySignHash(parameters, hashAlgorithm, hasher.ComputeHash(bytes), signature));
        }
示例#28
0
        public static void RSAParametersToBlob_PublicOnly()
        {
            byte[] blob;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(TestData.RSA1024Params);
                blob = rsa.ExportCspBlob(false);
            }

            RSAParameters exported;

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportCspBlob(blob);

                Assert.True(rsa.PublicOnly);

                exported = rsa.ExportParameters(false);
            }

            RSAParameters expected = new RSAParameters
            {
                Modulus = TestData.RSA1024Params.Modulus,
                Exponent = TestData.RSA1024Params.Exponent,
            };

            ImportExport.AssertKeyEquals(ref expected, ref exported);
        }
示例#29
0
 /// <summary>
 ///  构造函数
 /// </summary>
 /// <param name="rsap">包含公私钥的对象</param>
 public RSAEncrypt(RSAParameters rsap)
 {
     this.rsap = rsap;
 }
示例#30
0
 public RsaSigner(RSAParameters rsaParameters)
     : this()
 {
     myCryptoServiceProvider.ImportParameters(rsaParameters);
 }
示例#31
0
 /// <summary>
 ///  构造函数第一次重载
 /// </summary>
 /// <param name="exponent">公钥Exponent节</param>
 /// <param name="modulus">公钥Modulus节</param>
 public RSAEncrypt(string exponent, string modulus)
 {
     rsap          = new RSAParameters();
     rsap.Exponent = Encoding.UTF8.GetBytes(exponent);
     rsap.Modulus  = Encoding.UTF8.GetBytes(modulus);
 }
示例#32
0
        /// <summary>
        /// Performs a simple RSA signing of the specified bytes based on PKCS#1 1.5 padding schemes.
        /// </summary>
        /// <param name="rsa">The RSA.</param>
        /// <param name="hashAlgorithm">The hash algorithm.</param>
        /// <param name="bytes">The bytes.</param>
        /// <returns></returns>
        public static byte[] SimpleSign(RSAParameters parameters, string hashAlgorithm, byte[] bytes)
        {
            var hasher = HashAlgorithm.Create(hashAlgorithm);

            return(SimpleSignHash(parameters, hashAlgorithm, hasher.ComputeHash(bytes)));
        }
示例#33
0
        private static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
        {
            byte[] MODULUS, E, D, P, Q, DP, DQ, IQ;

            // ---------  Set up stream to decode the asn.1 encoded RSA private key  ------
            MemoryStream mem      = new MemoryStream(privkey);
            BinaryReader binr     = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte         bt       = 0;
            ushort       twobytes = 0;
            int          elems    = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();    //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)    //version number
                {
                    return(null);
                }
                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }


                //------  all private key components are Integer sequences ----
                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA       = new RSACryptoServiceProvider();
                RSAParameters            RSAparams = new RSAParameters();
                RSAparams.Modulus  = MODULUS;
                RSAparams.Exponent = E;
                RSAparams.D        = D;
                RSAparams.P        = P;
                RSAparams.Q        = Q;
                RSAparams.DP       = DP;
                RSAparams.DQ       = DQ;
                RSAparams.InverseQ = IQ;
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }
            finally { binr.Close(); }
        }
示例#34
0
        /// <summary>
        /// Writes a key to the specified stream.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="parameters">The RSA parameters of the key.</param>
        protected override void WriteCore(Stream stream, RSAParameters parameters)
        {
            if (!IsCapiCompatible(parameters))
            {
                // Try to get the RSA parameters to conform to CAPI's requirements.
                parameters = NegotiateSizes(parameters);
            }

            VerifyCapiCompatibleParameters(parameters);

            var writer = new BinaryWriter(stream);

            int bytelen = parameters.Modulus[0] == 0 // if high-order byte is zero, it's for sign bit; don't count in bit-size calculation
                ? parameters.Modulus.Length - 1
                : parameters.Modulus.Length;
            int bitlen = 8 * bytelen;

            writer.Write(KeyFormatter.HasPrivateKey(parameters) ? PrivateKeyBlobHeader : PublicKeyBlobHeader);
            writer.Write(CurrentBlobVersion);
            writer.Write((short)0); // reserved
            writer.Write(KeySpecKeyExchange);
            writer.Write(Encoding.UTF8.GetBytes(KeyFormatter.HasPrivateKey(parameters) ? PrivateKeyMagicHeader : PublicKeyMagicHeader));
            writer.Write(bitlen);

            // Ensure that the exponent occupies 4 bytes in the serialized stream,
            // even if in the parameters structure it does not.
            // We cannot use BitConverter.ToInt32 to help us do this because
            // its behavior varies based on the endianness of the platform,
            // yet RSAParameters is defined to always be Big Endian, and the
            // key blob format is defined to always be Little Endian, so we have to be careful.
            byte[] exponentPadding = new byte[4 - parameters.Exponent.Length];
            WriteReversed(writer, parameters.Exponent);
            writer.Write(exponentPadding);

            // bytelen drops the sign byte if it is present (which is good)
            WriteReversed(writer, parameters.Modulus, bytelen);

            if (KeyFormatter.HasPrivateKey(parameters))
            {
                WriteReversed(writer, parameters.P, bytelen / 2);
                WriteReversed(writer, parameters.Q, bytelen / 2);
                WriteReversed(writer, parameters.DP, bytelen / 2);
                WriteReversed(writer, parameters.DQ, bytelen / 2);
                WriteReversed(writer, parameters.InverseQ, bytelen / 2);
                WriteReversed(writer, parameters.D, bytelen);
            }

            writer.Flush();
            writer.Dispose();
        }
示例#35
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(Id.Text) &&
                !string.IsNullOrWhiteSpace(Password.Text) &&
                !string.IsNullOrWhiteSpace(ConfirmPassword.Text) &&
                !string.IsNullOrWhiteSpace(UserName.Text) &&
                !string.IsNullOrWhiteSpace(Email.Text) &&
                Gender.SelectedIndex != -1 &&
                Department.SelectedIndex != -1 &&
                position.SelectedIndex != -1 &&
                !string.IsNullOrWhiteSpace(Tel.Text) &&
                !string.IsNullOrWhiteSpace(Cel.Text) &&
                !string.IsNullOrWhiteSpace(Birthday.Text))
            //如果TextBox1跟TextBox2的text不是空白的跟DropDownList2的SelectedIndex不是-1就執行

            {
                if (Password.Text != ConfirmPassword.Text)
                {
                    Response.Write(" <script language=JavaScript> alert( ' 確認密碼不一致 '); </script> ");
                }
                else
                {
                    string tmpSQL = @"Insert Into UserInfo (EID,Name,UserID,Pwd,Gender,Email,Tel,Cel,Birthday,PK,Department,position,Permission) 
                                       Values (@EID,@Name,@UserID2,@Pwd,@Gender,@Email,@Tel,@Cel,@Birthday,@PK,@Department,@position,@Permission)"; //建立SQL語法新增輸入的資料
                    using (SqlConnection cn = new SqlConnection(tmpdbhelper.DB_CnStr))                                                              //使用using可以確保close
                    {
                        SqlCommand cmd = new SqlCommand();                                                                                          //設定一個叫cmd的命令實體
                        cmd.Connection  = cn;
                        cmd.CommandText = @"SELECT UserID FROM UserInfo WHERE UserID=@UserID";
                        cmd.Parameters.AddWithValue("@UserID", Id.Text);

                        cn.Open();
                        bool isExist = false;
                        using (SqlDataReader reader = cmd.ExecuteReader())
                        {
                            if (reader.Read())
                            {
                                isExist = true;
                            }
                        }

                        if (!isExist)
                        {
                            // 建立 RSA 演算法物件的執行個體
                            RSACryptoServiceProvider rsaProviderReceiver = new RSACryptoServiceProvider();

                            // 匯出金鑰組。
                            RSAParameters publicKeyReceiver  = rsaProviderReceiver.ExportParameters(false);   //匯出金鑰,參數 false 表示不含私鑰。
                            RSAParameters privateKeyReceiver = rsaProviderReceiver.ExportParameters(true);    //匯出金鑰

                            // 以 XML 格式匯出金鑰組。
                            string txt_PublicKeyrsaProviderReceiver  = rsaProviderReceiver.ToXmlString(false);             //以 XML 格式匯出金鑰,參數 false 表示不含私鑰。
                            string txt_PrivateKeyrsaProviderReceiver = rsaProviderReceiver.ToXmlString(true);              //以 XML 格式匯出金鑰
                                                                                                                           // 建立 CspParameters 物件
                            CspParameters cspParaReceiver = new CspParameters();

                            // 指定 KeyContainerName
                            cspParaReceiver.KeyContainerName = "AsymmetricExampleReceiver";

                            // 建立 RSA 演算法物件的執行個體
                            rsaProviderReceiver = new RSACryptoServiceProvider(cspParaReceiver);

                            // 設定 PersistKeyInCsp 屬性為 true。
                            rsaProviderReceiver.PersistKeyInCsp = true;       // 指出金鑰是否應保存 (Persist) 在密碼編譯服務供應者 (CSP) 中。

                            // 上面最後一行程式碼,.NET Framework 會自動建立金鑰容器並儲存金鑰。
                            // 若再度執行相同的應用程式,.NET Framework 會偵測同名的金鑰容器是否已存,若存在,則取出存於其中的私密金鑰

                            //把物件的值抓進參數裡面↓
                            cmd.CommandText = tmpSQL;
                            cmd.Parameters.AddWithValue("@EID", DateTime.Now.ToString("yyyyMMddhhmmss"));
                            cmd.Parameters.AddWithValue("@Name", UserName.Text);
                            cmd.Parameters.AddWithValue("@UserID2", Id.Text);
                            cmd.Parameters.AddWithValue("@Pwd", Password.Text);
                            cmd.Parameters.AddWithValue("@Gender", Gender.SelectedValue);
                            cmd.Parameters.AddWithValue("@Email", Email.Text);
                            cmd.Parameters.AddWithValue("@Tel", Tel.Text);
                            cmd.Parameters.AddWithValue("@Cel", Cel.Text);
                            cmd.Parameters.AddWithValue("@Birthday", Birthday.Text);
                            cmd.Parameters.AddWithValue("@PK", txt_PublicKeyrsaProviderReceiver);
                            cmd.Parameters.AddWithValue("@Department", Department.SelectedValue);
                            cmd.Parameters.AddWithValue("@position", position.SelectedValue);
                            cmd.Parameters.AddWithValue("@Permission", "1");

                            cmd.ExecuteNonQuery();//執行命令
                            SaveKey2File(txt_PrivateKeyrsaProviderReceiver, @"D:\" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt");
                            Response.Write("<script>alert('帳戶建立成功!');location.href='Home.aspx';</script>");
                        }
                        else
                        {
                            Response.Write(" <script language=JavaScript> alert( ' 此帳戶已被申請 '); </script> ");
                            Id.Text = "";
                        }
                    }
                }
            }
            Response.Write(" <script language=JavaScript> alert( ' 尚有空的欄位未填寫 '); </script> ");
        }
        public static void SignatureAlgorithm_Encoding(string hashAlgorithmName)
        {
            // PSS-MGF1-with-SHA-2-* end up differing in only three bytes:
            // 1) hashAlgorithm.algorithmId's last byte
            // 2) mgf.parameters.algorithmId's last byte
            // 3) saltLen.

            byte lastOidByte;
            byte saltLenByte;

            switch (hashAlgorithmName)
            {
            case "SHA256":
                lastOidByte = 0x01;
                saltLenByte = 256 / 8;
                break;

            case "SHA384":
                lastOidByte = 0x02;
                saltLenByte = 384 / 8;
                break;

            case "SHA512":
                lastOidByte = 0x03;
                saltLenByte = 512 / 8;
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(hashAlgorithmName));
            }

            string expectedHex =
                // SEQUENCE (AlgorithmIdentifier)
                "303D" +
                // OBJECT IDENTIFIER (AlgorithmIdentifier.algorithm == Oids.RsaPss)
                "06092A864886F70D01010A" +
                // SEQUENCE (AlgorithmIdentifier.params == RSASSA-PSS-params)
                "3030" +
                // CONSTRUCTED CONTEXT SPECIFIC 0 (params.hashAlgorithm)
                "A00D" +
                // SEQUENCE (AlgorithmIdentifier)
                "300B" +
                // OBJECT IDENTIFIER (params.hashAlgorithm.algorithm)
                "06096086480165030402" + lastOidByte.ToString("X2") +
                // CONSTRUCTED CONTEXT SPECIFIC 1 (params.maskGenAlgorithm)
                "A11A" +
                // SEQUENCE (MaskGenAlgorithm)
                "3018" +
                // OBJECT IDENTIFIER (MaskGenAlgorithm.algorithm == Oids.Mgf1)
                "06092A864886F70D010108" +
                // SEQUENCE (MaskGenAlgorithm.params)
                "300B" +
                // OBJECT IDENTIFIER (MGF PRF == same hash algorithm as above)
                "06096086480165030402" + lastOidByte.ToString("X2") +
                // CONSTRUCTED CONTEXT SPECIFIC 2 (params.saltLength)
                "A203" +
                // INTEGER (saltLength == size of hash)
                "0201" + saltLenByte.ToString("X2");

            using (RSA rsa = RSA.Create())
            {
                RSAParameters parameters = TestData.RsaBigExponentParams;
                rsa.ImportParameters(parameters);

                HashAlgorithmName hashAlgorithm = new HashAlgorithmName(hashAlgorithmName);
                var    signatureGenerator       = X509SignatureGenerator.CreateForRSA(rsa, RSASignaturePadding.Pss);
                byte[] sigAlg = signatureGenerator.GetSignatureAlgorithmIdentifier(hashAlgorithm);

                Assert.Equal(expectedHex, sigAlg.ByteArrayToHex());
            }
        }
示例#37
0
文件: RSAHelper.cs 项目: xin2015/SAW
 public void ImportParameters(RSAParameters parameters)
 {
     _rsa.ImportParameters(parameters);
 }
示例#38
0
        private static RSA DecodeRSAPrivateKey(byte[] privkey, string signType)
        {
            byte[]       MODULUS, E, D, P, Q, DP, DQ, IQ;
            MemoryStream mem      = new MemoryStream(privkey);
            BinaryReader binr     = new BinaryReader(mem);
            byte         bt       = 0;
            ushort       twobytes = 0;
            int          elems    = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130)
                {
                    binr.ReadByte();
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes != 0x0102)
                {
                    return(null);
                }

                bt = binr.ReadByte();
                if (bt != 0x00)
                {
                    return(null);
                }

                elems   = GetIntegerSize(binr);
                MODULUS = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                E     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                D     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                P     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                Q     = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DP    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                DQ    = binr.ReadBytes(elems);

                elems = GetIntegerSize(binr);
                IQ    = binr.ReadBytes(elems);

                int bitLen = 1024;
                if ("RSA2".Equals(signType))
                {
                    bitLen = 2048;
                }

                RSA RSA = RSA.Create();
                RSA.KeySize = bitLen;
                RSAParameters RSAparams = new RSAParameters
                {
                    Modulus  = MODULUS,
                    Exponent = E,
                    D        = D,
                    P        = P,
                    Q        = Q,
                    DP       = DP,
                    DQ       = DQ,
                    InverseQ = IQ
                };
                RSA.ImportParameters(RSAparams);
                return(RSA);
            }
            catch
            {
                return(null);
            }
            finally
            {
                binr.Close();
            }
        }
        public static string CreateEncryptedJweToken(JsonObject jwtPayload, RSAParameters publicKey)
        {
            //From: http://self-issued.info/docs/draft-ietf-jose-json-web-encryption-09.html#RSACBCExample
            var jweHeader = new JsonObject
            {
                { "alg", "RSA-OAEP" },
                { "enc", "A128CBC-HS256" },
                { "kid", Convert.ToBase64String(publicKey.Modulus).Substring(0, 3) },
            };

            var jweHeaderBase64Url = jweHeader.ToJson().ToUtf8Bytes().ToBase64UrlSafe();

            var authKey          = new byte[128 / 8];
            var cryptKey         = new byte[128 / 8];
            var cryptAuthKeys256 = AesUtils.CreateKey();

            Buffer.BlockCopy(cryptAuthKeys256, 0, authKey, 0, authKey.Length);
            Buffer.BlockCopy(cryptAuthKeys256, authKey.Length, cryptKey, 0, cryptKey.Length);

            var aes = Aes.Create();

            aes.KeySize   = 128;
            aes.BlockSize = 128;
            aes.Mode      = CipherMode.CBC;
            aes.Padding   = PaddingMode.PKCS7;
            using (aes)
            {
                aes.GenerateIV();
                var iv = aes.IV;
                aes.Key = cryptKey;

                var jweEncKey          = RsaUtils.Encrypt(cryptAuthKeys256, publicKey, UseRsaKeyLength);
                var jweEncKeyBase64Url = jweEncKey.ToBase64UrlSafe();
                var ivBase64Url        = iv.ToBase64UrlSafe();

                var aad          = jweHeaderBase64Url + "." + jweEncKeyBase64Url;
                var aadBytes     = aad.ToUtf8Bytes();
                var payloadBytes = jwtPayload.ToJson().ToUtf8Bytes();

                using (var cipherStream = MemoryStreamFactory.GetStream())
                    using (var encrypter = aes.CreateEncryptor(cryptKey, iv))
                        using (var cryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
                            using (var writer = new BinaryWriter(cryptoStream))
                            {
                                writer.Write(payloadBytes);
                                cryptoStream.FlushFinalBlock();

                                using (var hmac = new HMACSHA256(authKey))
                                    using (var encryptedStream = MemoryStreamFactory.GetStream())
                                        using (var bw = new BinaryWriter(encryptedStream))
                                        {
                                            bw.Write(aadBytes);
                                            bw.Write(iv);
                                            bw.Write(cipherStream.GetBuffer(), 0, (int)cipherStream.Length);
                                            bw.Flush();

                                            var tag = hmac.ComputeHash(encryptedStream.GetBuffer(), 0, (int)encryptedStream.Length);

                                            var cipherTextBase64Url = cipherStream.ToBase64UrlSafe();
                                            var tagBase64Url        = tag.ToBase64UrlSafe();

                                            var jweToken = jweHeaderBase64Url + "."
                                                           + jweEncKeyBase64Url + "."
                                                           + ivBase64Url + "."
                                                           + cipherTextBase64Url + "."
                                                           + tagBase64Url;

                                            return(jweToken);
                                        }
                            }
            }
        }
 /// <summary>
 /// Imports an RSA key into the iOS keychain.
 /// </summary>
 /// <param name="parameters">The RSA parameters.</param>
 /// <param name="tag">The tag by which this key will be known.</param>
 /// <returns>The security key.</returns>
 private static SecKey ImportKey(RSAParameters parameters, string tag)
 {
     using (var keyQueryDictionary = RsaCryptographicKey.CreateKeyQueryDictionary(tag))
     {
         byte[] pkcs1Key = KeyFormatter.Pkcs1PrependZeros.Write(parameters, parameters.D != null);
         keyQueryDictionary[KSec.ValueData] = NSData.FromArray(pkcs1Key);
         keyQueryDictionary[KSec.AttrKeyClass] = parameters.D != null ? KSec.AttrKeyClassPrivate : KSec.AttrKeyClassPublic;
         keyQueryDictionary[KSec.ReturnRef] = NSNumber.FromBoolean(true);
         IntPtr handle;
         int status = RsaCryptographicKey.SecItemAdd(keyQueryDictionary.Handle, out handle);
         Verify.Operation(status == 0, "SecItemAdd returned {0}", status);
         return new SecKey(handle, true);
     }
 }
示例#41
0
        internal RSAParameters ParseRSAPublicKey()
        {
            RSAParameters parameters = new RSAParameters();

            // Current value
            byte[] value = null;

            // Sanity Check
            int length = 0;

            // Checkpoint
            int position = parser.CurrentPosition();

            // Ignore Sequence - PublicKeyInfo
            length = parser.NextSequence();
            if (length != parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect Sequence RenderSize. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = parser.CurrentPosition();

            // Ignore Sequence - AlgorithmIdentifier
            length = parser.NextSequence();
            if (length > parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect AlgorithmIdentifier RenderSize. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = parser.CurrentPosition();
            // Grab the OID
            value = parser.NextOID();
            byte[] oid = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01 };
            if (!EqualOid(value, oid))
            {
                throw new BerDecodeException("Expected OID 1.2.840.113549.1.1.1", position);
            }

            // Optional Parameters
            if (parser.IsNextNull())
            {
                parser.NextNull();
                // Also OK: value = parser.Next();
            }
            else
            {
                // Gracefully skip the optional data
                value = parser.Next();
            }

            // Checkpoint
            position = parser.CurrentPosition();

            // Ignore BitString - PublicKey
            length = parser.NextBitString();
            if (length > parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect PublicKey RenderSize. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                (parser.RemainingBytes()).ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            // Checkpoint
            position = parser.CurrentPosition();

            // Ignore Sequence - RSAPublicKey
            length = parser.NextSequence();
            if (length < parser.RemainingBytes())
            {
                StringBuilder sb = new StringBuilder("Incorrect RSAPublicKey RenderSize. ");
                sb.AppendFormat("Specified: {0}, Remaining: {1}",
                                length.ToString(CultureInfo.InvariantCulture),
                                parser.RemainingBytes().ToString(CultureInfo.InvariantCulture));
                throw new BerDecodeException(sb.ToString(), position);
            }

            parameters.Modulus  = TrimLeadingZero(parser.NextInteger());
            parameters.Exponent = TrimLeadingZero(parser.NextInteger());

            Debug.Assert(0 == parser.RemainingBytes());

            return(parameters);
        }
示例#42
0
文件: PublicKey.cs 项目: GirlD/mono
		static internal RSA DecodeRSA (byte[] rawPublicKey)
		{
			RSAParameters rsaParams = new RSAParameters ();
			try {
				// for RSA rawPublicKey contains 2 ASN.1 integers
				// the modulus and the public exponent
				ASN1 pubkey = new ASN1 (rawPublicKey);
				if (pubkey.Count == 0)
					throw new CryptographicException (Locale.GetText ("Missing RSA modulus and exponent."));
				ASN1 modulus = pubkey [0];
				if ((modulus == null) || (modulus.Tag != 0x02))
					throw new CryptographicException (Locale.GetText ("Missing RSA modulus."));
				ASN1 exponent = pubkey [1];
				if (exponent.Tag != 0x02)
					throw new CryptographicException (Locale.GetText ("Missing RSA public exponent."));

				rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
				rsaParams.Exponent = exponent.Value;
			}
			catch (Exception e) {
				string msg = Locale.GetText ("Error decoding the ASN.1 structure.");
				throw new CryptographicException (msg, e);
			}

			int keySize = (rsaParams.Modulus.Length << 3);
			RSA rsa = (RSA) new RSACryptoServiceProvider (keySize);
			rsa.ImportParameters (rsaParams);
			return rsa;
		}
示例#43
0
        public static Dictionary <string, object> Validate(License licenseKey, RSAParameters rsaParameters)
        {
            var keys = ExtractKeys(licenseKey.Keys);

            var result = new Dictionary <string, object>();

            using (var ms = new MemoryStream())
                using (var br = new BinaryReader(ms))
                {
                    var buffer = keys.Attributes;
                    ms.Write(buffer, 0, buffer.Length);
                    ms.Position = 0;

                    while (ms.Position < buffer.Length)
                    {
                        var    token = ms.ReadByte();
                        var    index = token & 0x1F;
                        object val;
                        var    curr = (ValueType)(token >> TypeBitsToShift);
                        switch (curr)
                        {
                        case ValueType.False:
                            val = false;
                            break;

                        case ValueType.True:
                            val = true;
                            break;

                        case ValueType.Int8:
                            val = (int)br.ReadByte();
                            break;

                        case ValueType.Int32:
                            val = br.ReadInt32();
                            break;

                        case ValueType.Date:
                            val = FromDosDate(br.ReadUInt16());
                            break;

                        case ValueType.String:
                            var valLength = (int)br.ReadByte();
                            val = Encoding.UTF8.GetString(br.ReadBytes(valLength));
                            break;

                        default:
                            throw new ArgumentOutOfRangeException();
                        }

                        if (index >= Terms.Length)
                        {
                            continue; // new field, just skip
                        }
                        result[Terms[index]] = val;
                    }

                    var attributesLen = ms.Position;
                    ms.SetLength(attributesLen);

                    using (var binaryWriter = new BinaryWriter(ms))
                        using (var rsa = RSA.Create())
                        {
                            binaryWriter.Write(licenseKey.Id.ToByteArray());
                            binaryWriter.Write(licenseKey.Name);

                            rsa.ImportParameters(rsaParameters);

                            using (var sha1 = SHA1.Create())
                            {
                                ms.Position = 0;
                                var hash = sha1.ComputeHash(ms);

                                if (rsa.VerifyHash(hash, keys.Signature, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1) == false)
                                {
                                    throw new InvalidDataException("Could not validate signature on license");
                                }
                            }
                        }

                    return(result);
                }
        }
示例#44
0
    public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
    {
        try
        {
            //Create a new instance of RSACryptoServiceProvider.
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

            //Import the RSA Key information. This only needs
            //toinclude the public key information.
            RSA.ImportParameters(RSAKeyInfo);

            //Encrypt the passed byte array and specify OAEP padding.
            //OAEP padding is only available on Microsoft Windows XP or
            //later.
            return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
        }
            //Catch and display a CryptographicException
            //to the console.
        catch(CryptographicException e)
        {
            Console.WriteLine(e.Message);

            return null;
        }
    }
示例#45
0
        private static RSACryptoServiceProvider DecodeRSAPublicKey(byte[] publickey)
        {
            // encoded OID sequence for  PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] seq    = new byte[15];
            // ---------  Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob  ------
            MemoryStream mem      = new MemoryStream(publickey);
            BinaryReader binr     = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading
            byte         bt       = 0;
            ushort       twobytes = 0;

            try
            {
                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                seq = binr.ReadBytes(15);            //read the Sequence OID
                if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8203)
                {
                    binr.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                bt = binr.ReadByte();
                if (bt != 0x00)     //expect null byte next
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
                {
                    binr.ReadByte();    //advance 1 byte
                }
                else if (twobytes == 0x8230)
                {
                    binr.ReadInt16();   //advance 2 bytes
                }
                else
                {
                    return(null);
                }

                twobytes = binr.ReadUInt16();
                byte lowbyte  = 0x00;
                byte highbyte = 0x00;

                if (twobytes == 0x8102)        //data read as little endian order (actual data order for Integer is 02 81)
                {
                    lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
                }
                else if (twobytes == 0x8202)
                {
                    highbyte = binr.ReadByte(); //advance 2 bytes
                    lowbyte  = binr.ReadByte();
                }
                else
                {
                    return(null);
                }
                byte[] modint  = { lowbyte, highbyte, 0x00, 0x00 };  //reverse byte order since asn.1 key uses big endian order
                int    modsize = BitConverter.ToInt32(modint, 0);

                byte firstbyte = binr.ReadByte();
                binr.BaseStream.Seek(-1, SeekOrigin.Current);

                if (firstbyte == 0x00)
                {                    //if first byte (highest order) of modulus is zero, don't include it
                    binr.ReadByte(); //skip this null byte
                    modsize -= 1;    //reduce modulus buffer size by 1
                }

                byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes

                if (binr.ReadByte() != 0x02)              //expect an Integer for the exponent data
                {
                    return(null);
                }
                int    expbytes = (int)binr.ReadByte();     // should only need one byte for actual exponent data (for all useful values)
                byte[] exponent = binr.ReadBytes(expbytes);

                // ------- create RSACryptoServiceProvider instance and initialize with public key -----
                RSACryptoServiceProvider RSA        = new RSACryptoServiceProvider();
                RSAParameters            RSAKeyInfo = new RSAParameters();
                RSAKeyInfo.Modulus  = modulus;
                RSAKeyInfo.Exponent = exponent;
                RSA.ImportParameters(RSAKeyInfo);
                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }

            finally { binr.Close(); }
        }
示例#46
0
        public static RSA CreateRsaFromPublicKey(string publicKeyString)
        {
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] x509key;

            x509key = Convert.FromBase64String(publicKeyString.Replace("\n", ""));
            using (var mem = new MemoryStream(x509key))
            {
                using (var binr = new BinaryReader(mem))
                {
                    byte   bt       = 0;
                    ushort twobytes = 0;

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    var seq = binr.ReadBytes(15);
                    if (!CompareBytearrays(seq, SeqOID))
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8103)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8203)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    bt = binr.ReadByte();
                    if (bt != 0x00)
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    if (twobytes == 0x8130)
                    {
                        binr.ReadByte();
                    }
                    else if (twobytes == 0x8230)
                    {
                        binr.ReadInt16();
                    }
                    else
                    {
                        return(null);
                    }

                    twobytes = binr.ReadUInt16();
                    byte lowbyte  = 0x00;
                    byte highbyte = 0x00;

                    if (twobytes == 0x8102)
                    {
                        lowbyte = binr.ReadByte();
                    }
                    else if (twobytes == 0x8202)
                    {
                        highbyte = binr.ReadByte();
                        lowbyte  = binr.ReadByte();
                    }
                    else
                    {
                        return(null);
                    }
                    byte[] modint  = { lowbyte, highbyte, 0x00, 0x00 };
                    int    modsize = BitConverter.ToInt32(modint, 0);

                    int firstbyte = binr.PeekChar();
                    if (firstbyte == 0x00)
                    {
                        binr.ReadByte();
                        modsize -= 1;
                    }

                    byte[] modulus = binr.ReadBytes(modsize);

                    if (binr.ReadByte() != 0x02)
                    {
                        return(null);
                    }
                    int    expbytes = (int)binr.ReadByte();
                    byte[] exponent = binr.ReadBytes(expbytes);

                    var rsa        = RSA.Create();
                    var rsaKeyInfo = new RSAParameters
                    {
                        Modulus  = modulus,
                        Exponent = exponent
                    };
                    rsa.ImportParameters(rsaKeyInfo);
                    return(rsa);
                }
            }
        }
        public static void SignHash_PublicKey()
        {
            using (var rsa = new RSACryptoServiceProvider())
            {
                RSAParameters publicParams = new RSAParameters
                {
                    Modulus = TestData.RSA1024Params.Modulus,
                    Exponent = TestData.RSA1024Params.Exponent,
                };

                rsa.ImportParameters(publicParams);

                Assert.Throws<CryptographicException>(() => rsa.SignHash(Array.Empty<byte>(), "SHA384"));
            }
        }
示例#48
0
 /// <summary>
 /// Generate a PKS1 Signature of SHA1 digest
 /// </summary>
 /// <param name="xParam"></param>
 /// <param name="xHash"></param>
 /// <returns></returns>
 public static byte[] SignatureGenerate(RSAParameters xParam, byte[] xHash)
 {
     RSACryptoServiceProvider xRSACrypto = new RSACryptoServiceProvider();
     RSAPKCS1SignatureFormatter xRSASigFormat = new RSAPKCS1SignatureFormatter();
     try { xRSACrypto.ImportParameters(xParam); }
     catch (Exception xerror) { throw xerror; }
     xRSASigFormat.SetHashAlgorithm("SHA1");
     xRSASigFormat.SetKey(xRSACrypto);
     try { return xRSASigFormat.CreateSignature(xHash); }
     catch { throw CryptoExcepts.CryptoSign; }
 }
示例#49
0
        public static void ImportNoModulus()
        {
            RSAParameters imported = new RSAParameters
            {
                Exponent = TestData.RSA1024Params.Exponent,
            };

            using (RSA rsa = new RSACryptoServiceProvider())
            {
                Assert.Throws<CryptographicException>(() => rsa.ImportParameters(imported));
            }
        }
 public override void ImportParameters(RSAParameters parameters);
示例#51
0
 /// <summary>
 /// Determines whether [is valid public key] [the specified key parameters].
 /// </summary>
 /// <param name="keyParameters">The key parameters.</param>
 /// <returns>
 ///   <c>true</c> if [is valid public key] [the specified key parameters]; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsValidPublicKey(RSAParameters keyParameters)
 {
     return(keyParameters.Modulus != null && keyParameters.Exponent != null);
 }
示例#52
0
        public static void PublicOnlyPrivateExport()
        {
            RSAParameters imported = new RSAParameters
            {
                Modulus = TestData.RSA1024Params.Modulus,
                Exponent = TestData.RSA1024Params.Exponent,
            };

            using (RSA rsa = new RSACryptoServiceProvider())
            {
                rsa.ImportParameters(imported);
                Assert.Throws<CryptographicException>(() => rsa.ExportParameters(true));
            }
        }
示例#53
0
        private void ConfigureServer(string domain, string certificatePath, RSAParameters key, string siteName, string binding)
        {
            var certificateHash = serverConfiguration.InstallCertificateWithPrivateKey(certificatePath, "my", key);

            serverConfiguration.ConfigureServer(domain, certificateHash, "my", siteName, binding);
        }
示例#54
0
 internal static void AssertKeyEquals(ref RSAParameters expected, ref RSAParameters actual)
 {
     Assert.Equal(expected.Modulus, actual.Modulus);
     Assert.Equal(expected.Exponent, actual.Exponent);
     Assert.Equal(expected.D, actual.D);
     Assert.Equal(expected.P, actual.P);
     Assert.Equal(expected.DP, actual.DP);
     Assert.Equal(expected.Q, actual.Q);
     Assert.Equal(expected.DQ, actual.DQ);
     Assert.Equal(expected.InverseQ, actual.InverseQ);
 }
 /// <summary>Constructor</summary>
 /// <param name="param">RSAParameters</param>
 public JWS_RS512_Param(RSAParameters param)
 {
     this.DigitalSignParam = new DigitalSignParam(param, JWS_RS512.DigitalSignAlgorithm);
 }
示例#56
0
        private static RSACryptoServiceProvider DecodeX509PublicKey(byte[] X509Key)
        {
            // Encoded OID sequence for  PKCS#1 RSAEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
            byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
            byte[] Seq    = new byte[15];

            // ---------  Set up stream to read the ASN.1 encoded SubjectPublicKeyInfo blob  ------

            MemoryStream MemoryStream = new MemoryStream(X509Key);
            BinaryReader BinaryReader = new BinaryReader(MemoryStream); // Wrap Memory Stream with BinaryReader for easy reading

            byte   Byte     = 0;
            ushort TwoBytes = 0;

            try
            {
                TwoBytes = BinaryReader.ReadUInt16();

                if (TwoBytes == 0x8130)      // Data read as little endian order (actual data order for Sequence is 30 81)
                {
                    BinaryReader.ReadByte(); // Advance 1 byte
                }
                else if (TwoBytes == 0x8230)
                {
                    BinaryReader.ReadInt16();   // Advance 2 bytes
                }
                else
                {
                    return(null);
                }

                Seq = BinaryReader.ReadBytes(15);    // Read the Sequence OID

                if (!CompareByteArrays(Seq, SeqOID)) // Make sure Sequence for OID is correct
                {
                    return(null);
                }

                TwoBytes = BinaryReader.ReadUInt16();

                if (TwoBytes == 0x8103)      // Data read as little endian order (actual data order for Bit String is 03 81)
                {
                    BinaryReader.ReadByte(); // Advance 1 byte
                }
                else if (TwoBytes == 0x8203)
                {
                    BinaryReader.ReadInt16();   // Advance 2 bytes
                }
                else
                {
                    return(null);
                }

                Byte = BinaryReader.ReadByte();

                if (Byte != 0x00)   // Expect null byte next
                {
                    return(null);
                }

                TwoBytes = BinaryReader.ReadUInt16();

                if (TwoBytes == 0x8130)      // Data read as little endian order (actual data order for Sequence is 30 81)
                {
                    BinaryReader.ReadByte(); // Advance 1 byte
                }
                else if (TwoBytes == 0x8230)
                {
                    BinaryReader.ReadInt16();   // Advance 2 bytes
                }
                else
                {
                    return(null);
                }

                TwoBytes = BinaryReader.ReadUInt16();

                byte LowByte  = 0x00;
                byte HighByte = 0x00;

                if (TwoBytes == 0x8102)                // Data read as little endian order (actual data order for Integer is 02 81)
                {
                    LowByte = BinaryReader.ReadByte(); // Read next bytes which is bytes in modulus
                }
                else if (TwoBytes == 0x8202)
                {
                    HighByte = BinaryReader.ReadByte(); // Advance 2 bytes
                    LowByte  = BinaryReader.ReadByte();
                }
                else
                {
                    return(null);
                }

                byte[] ModInt  = { LowByte, HighByte, 0x00, 0x00 }; // Reverse byte order since ASN.1 key uses big endian order
                int    ModSize = BitConverter.ToInt32(ModInt, 0);

                byte FirstByte = BinaryReader.ReadByte();
                BinaryReader.BaseStream.Seek(-1, SeekOrigin.Current);

                if (FirstByte == 0x00)       // If first byte (highest order) of modulus is zero, don't include it
                {
                    BinaryReader.ReadByte(); // Skip this null byte
                    ModSize -= 1;            // Reduce modulus buffer size by 1
                }

                byte[] Modulus = BinaryReader.ReadBytes(ModSize); // Read the modulus bytes

                if (BinaryReader.ReadByte() != 0x02)              // Expect an Integer for the exponent data
                {
                    return(null);
                }

                int    ExponentBytes = (int)BinaryReader.ReadByte(); // Should only need one byte for actual exponent data (for all useful values)
                byte[] Exponent      = BinaryReader.ReadBytes(ExponentBytes);

                // ------- Create RSACryptoServiceProvider instance and initialize with public key -----

                RSACryptoServiceProvider RSA        = new RSACryptoServiceProvider();
                RSAParameters            RSAKeyInfo = new RSAParameters()
                {
                    Modulus  = Modulus,
                    Exponent = Exponent
                };

                RSA.ImportParameters(RSAKeyInfo);

                return(RSA);
            }
            catch (Exception)
            {
                return(null);
            }
            finally
            {
                BinaryReader.Close();
            }
        }
示例#57
0
 public override void ImportParameters(RSAParameters parameters)
 {
     throw new NotImplementedException();
 }
示例#58
0
        /// <summary>
        /// Creates a cert with the connectionstring (token) and stores it in the given cert store.
        /// </summary>
        public static async Task WriteAsync(string name, string connectionString, string storeType, string storePath)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                throw new ArgumentException("Token not found in X509Store and no new token provided!");
            }

            SecureRandom            random = new SecureRandom();
            KeyGenerationParameters keyGenerationParameters = new KeyGenerationParameters(random, 2048);
            RsaKeyPairGenerator     keyPairGenerator        = new RsaKeyPairGenerator();

            keyPairGenerator.Init(keyGenerationParameters);
            AsymmetricCipherKeyPair keys = keyPairGenerator.GenerateKeyPair();

            ArrayList nameOids = new ArrayList();

            nameOids.Add(X509Name.CN);
            ArrayList nameValues = new ArrayList();

            nameValues.Add(name);
            X509Name subjectDN = new X509Name(nameOids, nameValues);
            X509Name issuerDN  = subjectDN;

            X509V3CertificateGenerator cg = new X509V3CertificateGenerator();

            cg.SetSerialNumber(BigIntegers.CreateRandomInRange(BigInteger.One, BigInteger.ValueOf(Int64.MaxValue), random));
            cg.SetIssuerDN(issuerDN);
            cg.SetSubjectDN(subjectDN);
            cg.SetNotBefore(DateTime.Now);
            cg.SetNotAfter(DateTime.Now.AddMonths(12));
            cg.SetPublicKey(keys.Public);
            cg.AddExtension(X509Extensions.KeyUsage, true, new KeyUsage(KeyUsage.DataEncipherment));

            // encrypt the token with the public key so only the owner of the assoc. private key can decrypt it and
            // "hide" it in the instruction code cert extension
            RSA              rsa       = RSA.Create();
            RSAParameters    rsaParams = new RSAParameters();
            RsaKeyParameters keyParams = (RsaKeyParameters)keys.Public;

            rsaParams.Modulus = new byte[keyParams.Modulus.ToByteArrayUnsigned().Length];
            keyParams.Modulus.ToByteArrayUnsigned().CopyTo(rsaParams.Modulus, 0);

            rsaParams.Exponent = new byte[keyParams.Exponent.ToByteArrayUnsigned().Length];
            keyParams.Exponent.ToByteArrayUnsigned().CopyTo(rsaParams.Exponent, 0);

            rsa.ImportParameters(rsaParams);
            if (rsa != null)
            {
                byte[] bytes = rsa.Encrypt(Encoding.ASCII.GetBytes(connectionString), RSAEncryptionPadding.OaepSHA1);
                if (bytes != null)
                {
                    cg.AddExtension(X509Extensions.InstructionCode, false, bytes);
                }
                else
                {
                    throw new CryptographicException("Can not encrypt IoTHub security token using generated public key!");
                }
            }

            // sign the cert with the private key
            ISignatureFactory signatureFactory = new Asn1SignatureFactory("SHA256WITHRSA", keys.Private, random);

            Org.BouncyCastle.X509.X509Certificate x509 = cg.Generate(signatureFactory);

            // create a PKCS12 store for the cert and its private key
            X509Certificate2 certificate = null;

            using (MemoryStream pfxData = new MemoryStream())
            {
                Pkcs12StoreBuilder builder = new Pkcs12StoreBuilder();
                builder.SetUseDerEncoding(true);
                Pkcs12Store            pkcsStore = builder.Build();
                X509CertificateEntry[] chain     = new X509CertificateEntry[1];
                string passcode = Guid.NewGuid().ToString();
                chain[0] = new X509CertificateEntry(x509);
                pkcsStore.SetKeyEntry(name, new AsymmetricKeyEntry(keys.Private), chain);
                pkcsStore.Save(pfxData, passcode.ToCharArray(), random);

                // create X509Certificate2 object from PKCS12 file
                certificate = CertificateFactory.CreateCertificateFromPKCS12(pfxData.ToArray(), passcode);

                // handle each store type differently
                switch (storeType)
                {
                case CertificateStoreType.Directory:
                {
                    // Add to DirectoryStore
                    using (DirectoryCertificateStore store = new DirectoryCertificateStore())
                    {
                        store.Open(storePath);
                        X509CertificateCollection certificates = await store.Enumerate().ConfigureAwait(false);

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                await store.Delete(cert.Thumbprint).ConfigureAwait(false);
                            }
                        }

                        // add new one
                        await store.Add(certificate).ConfigureAwait(false);
                    }
                    break;
                }

                case CertificateStoreType.X509Store:
                {
                    // Add to X509Store
                    using (X509Store store = new X509Store(storePath, StoreLocation.CurrentUser))
                    {
                        store.Open(OpenFlags.ReadWrite);

                        // remove any existing cert with our name from the store
                        foreach (X509Certificate2 cert in store.Certificates)
                        {
                            if (cert.SubjectName.Decode(X500DistinguishedNameFlags.None | X500DistinguishedNameFlags.DoNotUseQuotes).Equals("CN=" + name, StringComparison.OrdinalIgnoreCase))
                            {
                                store.Remove(cert);
                            }
                        }

                        // add new cert to store
                        try
                        {
                            store.Add(certificate);
                        }
                        catch (Exception e)
                        {
                            throw new Exception($"Not able to add cert to the requested store type '{storeType}' (exception message: '{e.Message}'.");
                        }
                    }
                    break;
                }

                default:
                {
                    throw new Exception($"The requested store type '{storeType}' is not supported. Please change.");
                }
                }
                return;
            }
        }
示例#59
0
        private async Task <CertificateResponse> RequestCertificateForDomain(string domain, RSAParameters key)
        {
            var csr = CreateCertificateRequest(domain, key);

            return(await client.NewCertificateRequestAsync(csr));
        }
示例#60
-1
        /// <summary>
        /// Initializes a new instance of the <see cref="RsaCryptographicKey" /> class.
        /// </summary>
        /// <param name="publicKey">The public key.</param>
        /// <param name="parameters">The RSA instance, if available.</param>
        /// <param name="algorithm">The algorithm.</param>
        internal RsaCryptographicKey(IPublicKey publicKey, RSAParameters parameters, AsymmetricAlgorithm algorithm)
        {
            Requires.NotNull(publicKey, "publicKey");

            this.publicKey = publicKey.JavaCast<IRSAPublicKey>();
            this.parameters = parameters;
            this.algorithm = algorithm;
        }