ExportParameters() public abstract method

public abstract ExportParameters ( bool includePrivateParameters ) : RSAParameters
includePrivateParameters bool
return RSAParameters
Beispiel #1
0
 /// <summary>
 /// constructs a new RSA object
 /// </summary>
 public RSA(int keySize = -1)
 {
     _keySize = keySize != -1 ? keySize : _rsa.LegalKeySizes?[0].MaxSize ?? _rsa.KeySize;
     //foreach(var s in _rsa.LegalKeySizes)
     //    Log.i("Min:{0}, Max:{1}, Skip:{2}", s.MinSize, s.MaxSize, s.SkipSize);
     _rsa.KeySize = _keySize;
     PrivateKey   = _rsa.ExportParameters(true);
     PublicKey    = _rsa.ExportParameters(false);
 }
Beispiel #2
0
        public void LoadKey() {
            string import = "";
            using(StreamReader streamReader = new StreamReader(KeyStore))
                import = streamReader.ReadToEnd();

            publicKey = new RSACryptoServiceProvider();
            publicKey.FromXmlString(import);

            AsymmetricCipherKeyPair cipherKeyPair = DotNetUtilities.GetRsaKeyPair(publicKey.ExportParameters(true));
            privateKey = cipherKeyPair.Private;
            publicKey.ImportParameters(publicKey.ExportParameters(false));
            
            Directory.CreateDirectory(DestDir);
        }
        public static RSAKey CreateRsaKey(System.Security.Cryptography.RSA rsa)
        {
            Check.Argument.IsNotNull(rsa, nameof(rsa));

            string publicKey  = rsa.ToJsonString(false);
            string privateKey = rsa.ToJsonString(true);

            return(new RSAKey()
            {
                PublicKey = publicKey,
                PrivateKey = privateKey,
                Exponent = rsa.ExportParameters(false).Exponent.ToHexString(),
                Modulus = rsa.ExportParameters(false).Modulus.ToHexString()
            });
        }
        public bool Matches(RSA rsa)
        {
            if (rsa == null)
                return false;

            RSAParameters rsaParameters = rsa.ExportParameters(false);
            return SecurityUtils.MatchesBuffer(this.rsaParameters.Modulus, rsaParameters.Modulus) &&
                SecurityUtils.MatchesBuffer(this.rsaParameters.Exponent, rsaParameters.Exponent);
        }
 public bool Matches(RSA rsa)
 {
     if (rsa == null)
     {
         return false;
     }
     RSAParameters parameters = rsa.ExportParameters(false);
     return (System.IdentityModel.SecurityUtils.MatchesBuffer(this.rsaParameters.Modulus, parameters.Modulus) && System.IdentityModel.SecurityUtils.MatchesBuffer(this.rsaParameters.Exponent, parameters.Exponent));
 }
Beispiel #6
0
 public RSA(int keysize)
 {
     _rsa         = System.Security.Cryptography.RSA.Create();
     _rsa.KeySize = keysize;//默认是2048,也就是_parameter.Modulus是256字节,但是js那边的算法会卡死
     //把公钥适当转换,准备发往客户端
     _parameter   = _rsa.ExportParameters(true);
     _KeyExponent = BytesToHexString(_parameter.Exponent);
     _KeyModulus  = BytesToHexString(_parameter.Modulus);
 }
        public RsaKeyIdentifierClause(RSA rsa)
            : base(clauseType)
        {
            if (rsa == null)
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rsa");

            this.rsa = rsa;
            this.rsaParameters = rsa.ExportParameters(false);
        }
        public static RSAKey CreateRsaKey(RsaSize rsaSize = RsaSize.R2048)
        {
            using (System.Security.Cryptography.RSA rsa = System.Security.Cryptography.RSA.Create())
            {
                rsa.KeySize = (int)rsaSize;



                string publicKey  = rsa.ToJsonString(false);
                string privateKey = rsa.ToJsonString(true);

                return(new RSAKey()
                {
                    PublicKey = publicKey,
                    PrivateKey = privateKey,
                    Exponent = rsa.ExportParameters(false).Exponent.ToHexString(),
                    Modulus = rsa.ExportParameters(false).Modulus.ToHexString()
                });
            }
        }
Beispiel #9
0
        /// <summary>
        /// 获取RSA Key序列化XML
        /// </summary>
        /// <param name="rsa">RSA实例<see cref="RSA"/></param>
        /// <param name="includePrivateParameters">是否包含私钥</param>
        /// <returns></returns>
        public static string ToLvccXmlString(this System.Security.Cryptography.RSA rsa, bool includePrivateParameters)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            return(string.Format("<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                                 parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null,
                                 parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null,
                                 parameters.P != null ? Convert.ToBase64String(parameters.P) : null,
                                 parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null,
                                 parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null,
                                 parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null,
                                 parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null,
                                 parameters.D != null ? Convert.ToBase64String(parameters.D) : null));
        }
        public static string GetPublicKeyInPkcs1(this MsRSA rsa)
        {
            var privateKeyParameters = rsa.ExportParameters(false);
            var rsaKeyParameters     = new RsaKeyParameters(
                false,
                new BigInteger(1, privateKeyParameters.Modulus),
                new BigInteger(1, privateKeyParameters.Exponent));

            using var writer = new StringWriter();
            var pemWriter = new PemWriter(writer);

            pemWriter.WriteObject(rsaKeyParameters);
            pemWriter.Writer.Close();
            return(writer.ToString());
        }
        public static string ExportKeyInLvccXml(this MsRSA rsa, bool includePrivateParameters)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            // ReSharper disable once UseStringInterpolation
            return(string.Format(
                       "<RSAKeyValue><Modulus>{0}</Modulus><Exponent>{1}</Exponent><P>{2}</P><Q>{3}</Q><DP>{4}</DP><DQ>{5}</DQ><InverseQ>{6}</InverseQ><D>{7}</D></RSAKeyValue>",
                       parameters.Modulus != null ? Convert.ToBase64String(parameters.Modulus) : null,
                       parameters.Exponent != null ? Convert.ToBase64String(parameters.Exponent) : null,
                       parameters.P != null ? Convert.ToBase64String(parameters.P) : null,
                       parameters.Q != null ? Convert.ToBase64String(parameters.Q) : null,
                       parameters.DP != null ? Convert.ToBase64String(parameters.DP) : null,
                       parameters.DQ != null ? Convert.ToBase64String(parameters.DQ) : null,
                       parameters.InverseQ != null ? Convert.ToBase64String(parameters.InverseQ) : null,
                       parameters.D != null ? Convert.ToBase64String(parameters.D) : null));
        }
        internal static string ExportKeyInJson(this MsRSA rsa, bool includePrivateParameters)
        {
            var parameters = rsa.ExportParameters(includePrivateParameters);

            var parasJson = new RsaJsonParameters()
            {
                Modulus = parameters.Modulus != null?Convert.ToBase64String(parameters.Modulus) : null,
                              Exponent                                                                                                                          = parameters.Exponent != null?Convert.ToBase64String(parameters.Exponent) : null,
                                                                               P                                                                                = parameters.P != null?Convert.ToBase64String(parameters.P) : null,
                                                                                                                 Q                                              = parameters.Q != null?Convert.ToBase64String(parameters.Q) : null,
                                                                                                                                           DP                   = parameters.DP != null?Convert.ToBase64String(parameters.DP) : null,
                                                                                                                                                             DQ = parameters.DQ != null?Convert.ToBase64String(parameters.DQ) : null,
                                                                                                                                                                      InverseQ                 = parameters.InverseQ != null?Convert.ToBase64String(parameters.InverseQ) : null,
                                                                                                                                                                                             D = parameters.D != null?Convert.ToBase64String(parameters.D) : null
            };

            return(JsonConvert.SerializeObject(parasJson));
        }
Beispiel #13
0
        /// <summary>
        /// 获取RSA Key序列化Json
        /// </summary>
        /// <param name="rsa">RSA实例<see cref="RSA"/></param>
        /// <param name="includePrivateParameters">是否包含私钥</param>
        /// <returns></returns>
        internal static string ToJsonString(this System.Security.Cryptography.RSA rsa, bool includePrivateParameters)
        {
            RSAParameters parameters = rsa.ExportParameters(includePrivateParameters);

            var parasJson = new RSAParametersJson()
            {
                Modulus = parameters.Modulus != null?Convert.ToBase64String(parameters.Modulus) : null,
                              Exponent                                                                                                                          = parameters.Exponent != null?Convert.ToBase64String(parameters.Exponent) : null,
                                                                               P                                                                                = parameters.P != null?Convert.ToBase64String(parameters.P) : null,
                                                                                                                 Q                                              = parameters.Q != null?Convert.ToBase64String(parameters.Q) : null,
                                                                                                                                           DP                   = parameters.DP != null?Convert.ToBase64String(parameters.DP) : null,
                                                                                                                                                             DQ = parameters.DQ != null?Convert.ToBase64String(parameters.DQ) : null,
                                                                                                                                                                      InverseQ                 = parameters.InverseQ != null?Convert.ToBase64String(parameters.InverseQ) : null,
                                                                                                                                                                                             D = parameters.D != null?Convert.ToBase64String(parameters.D) : null
            };

            return(JsonConvert.SerializeObject(parasJson));
        }
Beispiel #14
0
        public static bool VerifyRsaPKCS1(RSA key, byte[] signature, byte[] hash, bool allowNoPadding)
        {
            var parameters = key.ExportParameters(false);

            var e = Utils.BigIntegerFromBigEndian(parameters.Exponent, 0, parameters.Exponent.Length);
            var mod = Utils.BigIntegerFromBigEndian(parameters.Modulus, 0, parameters.Modulus.Length);
            var m = Utils.BigIntegerFromBigEndian(signature, 0, signature.Length);
            var decryptedArr = Utils.BigEndianFromBigInteger(BigInteger.ModPow(m, e, mod));

            /*
            PKCS padding used in TLS 1.0/TLS 1.1:
            00 01 [k-3-hashlen 0xff bytes] 00 (hash)
            OR, for only TLS 1.0, there may be no padding (or equivalently, 00 00 [k-3-hashlen 00 bytes] 00 (hash))
            where k is the keylen
            */

            if (allowNoPadding && decryptedArr.Length <= hash.Length)
            {
                int zeros = hash.Length - decryptedArr.Length;
                for (var i = 0; i < zeros; i++)
                {
                    if (hash[i] != 0)
                        return false;
                }
                return Utils.ArraysEqual(decryptedArr, 0, hash, zeros, hash.Length - zeros);
            }

            if (decryptedArr.Length != parameters.Modulus.Length - 1)
                return false;

            if (decryptedArr[0] != 1)
                return false;

            for (var i = 1; i < decryptedArr.Length - hash.Length - 1; i++)
            {
                if (decryptedArr[i] != 0xff)
                    return false;
            }
            if (decryptedArr[decryptedArr.Length - hash.Length - 1] != 0)
                return false;

            return Utils.ArraysEqual(decryptedArr, decryptedArr.Length - hash.Length, hash, 0, hash.Length);
        }
 private static JsonWebKey CreateJWK(RSA rsa)
 {
     if (rsa == null)
         throw new ArgumentNullException("rsa");
     RSAParameters rsaParameters = rsa.ExportParameters(true);
     var webKey = new JsonWebKey() 
     { 
         Kty = JsonWebKeyType.Rsa,
         E = rsaParameters.Exponent,
         N = rsaParameters.Modulus,
         D = rsaParameters.D,
         DP = rsaParameters.DP,
         DQ = rsaParameters.DQ,
         QI = rsaParameters.InverseQ,
         P = rsaParameters.P,
         Q = rsaParameters.Q
     };
     
     return webKey;
 }
Beispiel #16
0
        public void SelfSignedCertificateTest()
        {
            string subject = "CN=Test Certificate, O=Org";

            var cert = Certificate.GenerateSelfSigned(subject);

            Assert.IsInstanceOfType(cert, typeof(X509Certificate2));
            Assert.AreEqual(cert.Subject, subject);
            Assert.IsTrue(cert.HasPrivateKey);

            // Export private and public key for CryptoServiceProvider
            System.Security.Cryptography.RSA priv = (System.Security.Cryptography.RSA)cert.PrivateKey;
            System.Security.Cryptography.RSA pub  = (System.Security.Cryptography.RSA)cert.PublicKey.Key;

            string message       = "Hello world";
            string encryptedText = RSA.Encrypt(message, pub.ExportParameters(false));
            string plainText     = RSA.Decrypt(encryptedText, priv.ExportParameters(true));

            Assert.AreEqual(message, plainText);
        }
        public static string GetPrivateKeyInPkcs1(this MsRSA rsa)
        {
            var privateKeyParameters       = rsa.ExportParameters(true);
            var rsaPrivateCrtKeyParameters = new RsaPrivateCrtKeyParameters(
                new BigInteger(1, privateKeyParameters.Modulus),
                new BigInteger(1, privateKeyParameters.Exponent),
                new BigInteger(1, privateKeyParameters.D),
                new BigInteger(1, privateKeyParameters.P),
                new BigInteger(1, privateKeyParameters.Q),
                new BigInteger(1, privateKeyParameters.DP),
                new BigInteger(1, privateKeyParameters.DQ),
                new BigInteger(1, privateKeyParameters.InverseQ));

            using var writer = new StringWriter();
            var pemWriter = new PemWriter(writer);

            pemWriter.WriteObject(rsaPrivateCrtKeyParameters);
            pemWriter.Writer.Close();
            return(writer.ToString());
        }
Beispiel #18
0
        public static void ExportToXmlString(this System.Security.Cryptography.RSA rsa, bool includePrivateParameters)
        {
            var parameters = rsa.ExportParameters(includePrivateParameters);

            var xmlSettings = new XmlWriterSettings {
                Indent = true
            };

            var xmlContent = includePrivateParameters
                ? $"<RSAKeyValue><Modulus>{Convert.ToBase64String(parameters.Modulus)}</Modulus><Exponent>{Convert.ToBase64String(parameters.Exponent)}</Exponent><P>{Convert.ToBase64String(parameters.P)}</P><Q>{Convert.ToBase64String(parameters.Q)}</Q><DP>{Convert.ToBase64String(parameters.DP)}</DP><DQ>{Convert.ToBase64String(parameters.DQ)}</DQ><InverseQ>{Convert.ToBase64String(parameters.InverseQ)}</InverseQ><D>{Convert.ToBase64String(parameters.D)}</D></RSAKeyValue>"
                : $"<RSAKeyValue><Modulus>{Convert.ToBase64String(parameters.Modulus)}</Modulus><Exponent>{Convert.ToBase64String(parameters.Exponent)}</Exponent></RSAKeyValue>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlContent);

            using (var xmlWriter =
                       XmlWriter.Create($"{(includePrivateParameters ? "privateKey.xml" : "publicKey.xml")}", xmlSettings))
            {
                xml.WriteTo(xmlWriter);
            }
        }
Beispiel #19
0
        public static byte[] SignRsaPKCS1(RSA key, byte[] hash)
        {
            // NOTE: The X509Certificate2 must be initialized with the X509KeyStorageFlags.Exportable flag
            var parameters = key.ExportParameters(true);

            var dp = Utils.BigIntegerFromBigEndian(parameters.DP, 0, parameters.DP.Length);
            var dq = Utils.BigIntegerFromBigEndian(parameters.DQ, 0, parameters.DQ.Length);
            var qinv = Utils.BigIntegerFromBigEndian(parameters.InverseQ, 0, parameters.InverseQ.Length);
            var p = Utils.BigIntegerFromBigEndian(parameters.P, 0, parameters.P.Length);
            var q = Utils.BigIntegerFromBigEndian(parameters.Q, 0, parameters.Q.Length);

            var data = new byte[parameters.D.Length - 1];
            data[0] = 1;
            for (var i = 1; i < data.Length - hash.Length - 1; i++)
            {
                data[i] = 0xff;
            }
            data[data.Length - hash.Length - 1] = 0;
            Buffer.BlockCopy(hash, 0, data, data.Length - hash.Length, hash.Length);

            var m = Utils.BigIntegerFromBigEndian(data, 0, data.Length);

            var m1 = BigInteger.ModPow(m, dp, p);
            var m2 = BigInteger.ModPow(m, dq, q);
            var h = qinv * (m1 - m2) % p;
            if (h.Sign == -1)
                h += p;
            var signature = Utils.BigEndianFromBigInteger(m2 + h * q);

            Utils.ClearArray(parameters.D);
            Utils.ClearArray(parameters.DP);
            Utils.ClearArray(parameters.DQ);
            Utils.ClearArray(parameters.InverseQ);
            Utils.ClearArray(parameters.P);
            Utils.ClearArray(parameters.Q);

            return signature;
        }
Beispiel #20
0
        /// <summary>
        /// Converter Rsa to pem ,
        /// </summary>
        /// <param name="rsa"><see cref="RSACryptoServiceProvider"/></param>
        /// <param name="includePrivateParameters">if false only return publick key</param>
        /// <param name="isPKCS8">default is false,if true return PKCS#8 pem else return PKCS#1 pem </param>
        /// <returns></returns>
        internal static string ToPem(System.Security.Cryptography.RSA rsa, bool includePrivateParameters, bool isPKCS8 = false)
        {
            var ms = new MemoryStream();

            Action <int> writeLenByte = (len) =>
            {
                if (len < 0x80)
                {
                    ms.WriteByte((byte)len);
                }
                else if (len <= 0xff)
                {
                    ms.WriteByte(0x81);
                    ms.WriteByte((byte)len);
                }
                else
                {
                    ms.WriteByte(0x82);
                    ms.WriteByte((byte)(len >> 8 & 0xff));
                    ms.WriteByte((byte)(len & 0xff));
                }
            };
            //write moudle data
            Action <byte[]> writeBlock = (byts) =>
            {
                var addZero = (byts[0] >> 4) >= 0x8;
                ms.WriteByte(0x02);
                var len = byts.Length + (addZero ? 1 : 0);
                writeLenByte(len);

                if (addZero)
                {
                    ms.WriteByte(0x00);
                }
                ms.Write(byts, 0, byts.Length);
            };

            Func <int, byte[], byte[]> writeLen = (index, byts) =>
            {
                var len = byts.Length - index;

                ms.SetLength(0);
                ms.Write(byts, 0, index);
                writeLenByte(len);
                ms.Write(byts, index, len);

                return(ms.ToArray());
            };


            if (!includePrivateParameters)
            {
                /****Create public key****/
                var param = rsa.ExportParameters(false);

                ms.WriteByte(0x30);
                var index1 = (int)ms.Length;

                // Encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
                ms.Write(_SeqOID);

                //Start with 0x00
                ms.WriteByte(0x03);
                var index2 = (int)ms.Length;
                ms.WriteByte(0x00);

                //Content length
                ms.WriteByte(0x30);
                var index3 = (int)ms.Length;

                //Write Modulus
                writeBlock(param.Modulus);

                //Write Exponent
                writeBlock(param.Exponent);

                var bytes = ms.ToArray();

                bytes = writeLen(index3, bytes);
                bytes = writeLen(index2, bytes);
                bytes = writeLen(index1, bytes);


                return("-----BEGIN PUBLIC KEY-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END PUBLIC KEY-----");
            }
            else
            {
                /****Create private key****/
                var param = rsa.ExportParameters(true);

                //Write total length
                ms.WriteByte(0x30);
                int index1 = (int)ms.Length;

                //Write version
                ms.Write(_Ver);


                //PKCS8
                int index2 = -1, index3 = -1;
                if (isPKCS8)
                {
                    ms.Write(_SeqOID);

                    ms.WriteByte(0x04);
                    index2 = (int)ms.Length;

                    ms.WriteByte(0x30);
                    index3 = (int)ms.Length;

                    ms.Write(_Ver);
                }

                //Write data
                writeBlock(param.Modulus);
                writeBlock(param.Exponent);
                writeBlock(param.D);
                writeBlock(param.P);
                writeBlock(param.Q);
                writeBlock(param.DP);
                writeBlock(param.DQ);
                writeBlock(param.InverseQ);

                var bytes = ms.ToArray();

                if (index2 != -1)
                {
                    bytes = writeLen(index3, bytes);
                    bytes = writeLen(index2, bytes);
                }
                bytes = writeLen(index1, bytes);


                var flag = " PRIVATE KEY";
                if (!isPKCS8)
                {
                    flag = " RSA" + flag;
                }
                return("-----BEGIN" + flag + "-----\n" + TextBreak(Convert.ToBase64String(bytes), 64) + "\n-----END" + flag + "-----");
            }
        }
Beispiel #21
0
 public static Rsa Clone(Rsa rsa)
 {
     return(Rsa.Create(rsa.ExportParameters(true)) ?? throw new FactoryException());
 }
Beispiel #22
0
        /// <summary>
        /// Does the actual calculation of a combined ID from a value and an RSA key.
        /// </summary>
        /// <param name="issuerKey">The key of the issuer of the token</param>
        /// <param name="claimValue">the claim value to hash with.</param>
        /// <returns></returns>
        public static string ComputeCombinedId(RSA issuerKey, string claimValue)
        {
            int nameLength = Encoding.UTF8.GetByteCount(claimValue);
            RSAParameters rsaParams = issuerKey.ExportParameters(false);
            byte[] shaInput;
            byte[] shaOutput;

            int i = 0;
            shaInput = new byte[rsaParams.Modulus.Length + rsaParams.Exponent.Length + nameLength];
            rsaParams.Modulus.CopyTo(shaInput, i);
            i += rsaParams.Modulus.Length;
            rsaParams.Exponent.CopyTo(shaInput, i);
            i += rsaParams.Exponent.Length;
            i += Encoding.UTF8.GetBytes(claimValue, 0, claimValue.Length, shaInput, i);

            using (SHA256 sha = SHA256.Create())
            {
                shaOutput = sha.ComputeHash(shaInput);
            }

            return Convert.ToBase64String(shaOutput);
        }
		public static RsaKeyParameters GetRsaPublicKey(
			RSA rsa)
		{
			return GetRsaPublicKey(rsa.ExportParameters(false));
		}
 /// <summary>
 /// Converts a RSA object to a WebKey of type RSA.
 /// </summary>
 /// <param name="rsaProvider">The RSA object to convert</param>
 /// <param name="includePrivateParameters">True to include the RSA private key parameters</param>
 /// <returns>A WebKey representing the RSA object</returns>
 public JsonWebKey( RSA rsaProvider, bool includePrivateParameters = false ) 
     : this( rsaProvider.ExportParameters( includePrivateParameters ) )
 {
 }
Beispiel #25
0
 public override RSAParameters ExportParameters(bool includePrivateParameters) =>
     _impl.ExportParameters(includePrivateParameters);
Beispiel #26
0
 public static AsymmetricCipherKeyPair GetRsaKeyPair(
     System.Security.Cryptography.RSA rsa)
 {
     return(GetRsaKeyPair(rsa.ExportParameters(true)));
 }
        public static byte[] ToCapiPrivateKeyBlob(RSA rsa) {
            RSAParameters p = rsa.ExportParameters(true);
            int keyLength = p.Modulus.Length; // in bytes
            var blob = new byte[20 + (keyLength << 2) + (keyLength >> 1)];

            blob[0] = 0x07; // Type - PRIVATEKEYBLOB (0x07)
            blob[1] = 0x02; // Version - Always CUR_BLOB_VERSION (0x02)
            // [2], [3]		// RESERVED - Always 0
            blob[5] = 0x24; // ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
            blob[8] = 0x52; // Magic - RSA2 (ASCII in hex)
            blob[9] = 0x53;
            blob[10] = 0x41;
            blob[11] = 0x32;

            byte[] bitlen = GetBytesLE(keyLength << 3);
            blob[12] = bitlen[0]; // bitlen
            blob[13] = bitlen[1];
            blob[14] = bitlen[2];
            blob[15] = bitlen[3];

            // public exponent (DWORD)
            int pos = 16;
            int n = p.Exponent.Length;
            while (n > 0) {
                blob[pos++] = p.Exponent[--n];
            }
            // modulus
            pos = 20;
            byte[] part = p.Modulus;
            int len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;
            // private key
            part = p.P;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;

            part = p.Q;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;

            part = p.DP;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;

            part = p.DQ;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;

            part = p.InverseQ;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);
            pos += len;

            part = p.D;
            len = part.Length;
            Array.Reverse(part, 0, len);
            Buffer.BlockCopy(part, 0, blob, pos, len);

            return blob;
        }
		private static string ComputeCombinedId(RSA issuerKey, string claimValue) {
			Requires.NotNull(issuerKey, "issuerKey");
			Requires.NotNull(claimValue, "claimValue");
			Contract.Ensures(Contract.Result<string>() != null);

			int nameLength = Encoding.UTF8.GetByteCount(claimValue);
			RSAParameters rsaParams = issuerKey.ExportParameters(false);
			byte[] shaInput;
			byte[] shaOutput;

			int i = 0;
			shaInput = new byte[rsaParams.Modulus.Length + rsaParams.Exponent.Length + nameLength];
			rsaParams.Modulus.CopyTo(shaInput, i);
			i += rsaParams.Modulus.Length;
			rsaParams.Exponent.CopyTo(shaInput, i);
			i += rsaParams.Exponent.Length;
			i += Encoding.UTF8.GetBytes(claimValue, 0, claimValue.Length, shaInput, i);

			using (SHA256 sha = SHA256.Create()) {
				shaOutput = sha.ComputeHash(shaInput);
			}

			return Convert.ToBase64String(shaOutput);
		}
		public static AsymmetricCipherKeyPair GetRsaKeyPair(
			RSA rsa)
		{
			return GetRsaKeyPair(rsa.ExportParameters(true));
		}
Beispiel #30
0
 public static byte[] getExponent(RSA rsa)
 {
     return rsa.ExportParameters(false).Exponent;
 }
        public static Byte[] CreateCustomSecureKeyVerifyStruct(RSA rsa)
        {
            Int32 modSizeInBytes = (rsa.KeySize >> 3);
              Int32 keyStructSize = 8 + modSizeInBytes;
              Byte[] modData = new Byte[modSizeInBytes];
              Byte[] keyVerifyStruct = new Byte[keyStructSize];

              // Zero out the array
              Array.Clear(keyVerifyStruct,0,keyStructSize);

              // Get the RSA Public Key Params
              RSAParameters RSAParams = rsa.ExportParameters(false);

              RSAParams.Exponent.CopyTo(keyVerifyStruct,0);

              BitConverter.GetBytes((Int16) (modSizeInBytes>>1)).CopyTo(keyVerifyStruct,6);

              // Modulus Bytes Need to be reversed for RSA code in ROM to work
              RSAParams.Modulus.CopyTo(modData,0);
              Array.Reverse(modData);
              modData.CopyTo(keyVerifyStruct,8);

              return keyVerifyStruct;
        }
        public static ASN1 ToAsn1Key(RSA rsa)
        {
            EnsureNotNull(rsa, "rsa");

            RSAParameters parameters = rsa.ExportParameters(false);

            ASN1 asnKey = new ASN1(0x30);
            asnKey.Add(ASN1Convert.FromUnsignedBigInteger(parameters.Modulus));
            asnKey.Add(ASN1Convert.FromUnsignedBigInteger(parameters.Exponent));
            return asnKey;
        }
Beispiel #33
0
 /// <summary>
 /// Initializes a new instance of the StrongNameFile class.
 /// </summary>
 /// <param name="rsa">The private key that this strong name file represents.</param>
 /// <exception cref="ArgumentNullException"><paramref name="rsa"/> is a null reference.</exception>
 public StrongNameFile(RSA rsa)
 {
     if (rsa == null)
         throw new ArgumentNullException("rsa");
     RSAParameters parameters;
     bool includePrivate = true;
     try {
         parameters = rsa.ExportParameters(true);
     } catch {
         // retry without private parameters
         parameters = rsa.ExportParameters(false);
         includePrivate = false;
     }
     InitializeFromParameters(parameters, includePrivate);
 }
Beispiel #34
0
        /// <summary>
        /// Export an RSA key to a PEM format string
        /// </summary>
        /// <param name="rsa">The RSA key to export (must be exportable)</param>
        /// <param name="password">An optional password</param>
        /// <returns>A PEM string form of the key</returns>
        public static string ExportToPEM(RSA rsa, SecureString password)
        {
            StringWriter swriter = new StringWriter();
            PemWriter writer = new PemWriter(swriter);

            RSAParameters ps = rsa.ExportParameters(true);

            BigInteger modulus = new BigInteger(1, ps.Modulus);
            BigInteger exp = new BigInteger(1, ps.Exponent);
            BigInteger d = new BigInteger(1, ps.D);
            BigInteger p = new BigInteger(1, ps.P);
            BigInteger q = new BigInteger(1, ps.Q);
            BigInteger dp = new BigInteger(1, ps.DP);
            BigInteger dq = new BigInteger(1, ps.DQ);
            BigInteger qinv = new BigInteger(1, ps.InverseQ);

            RsaPrivateCrtKeyParameters privKey = new RsaPrivateCrtKeyParameters(modulus, exp, d, p, q, dp, dq, qinv);

            if (password != null)
            {
                writer.WriteObject(privKey, "DES-EDE3-CBC",
                    SecureStringToCharArray(password), new Org.BouncyCastle.Security.SecureRandom());
            }
            else
            {
                writer.WriteObject(privKey);
            }

            return swriter.ToString();
        }
Beispiel #35
0
		static public byte[] ToCapiPublicKeyBlob (RSA rsa) 
		{
			RSAParameters p = rsa.ExportParameters (false);
			int keyLength = p.Modulus.Length; // in bytes
			byte[] blob = new byte [20 + keyLength];

			blob [0] = 0x06;	// Type - PUBLICKEYBLOB (0x06)
			blob [1] = 0x02;	// Version - Always CUR_BLOB_VERSION (0x02)
			// [2], [3]		// RESERVED - Always 0
			blob [5] = 0x24;	// ALGID - Always 00 24 00 00 (for CALG_RSA_SIGN)
			blob [8] = 0x52;	// Magic - RSA1 (ASCII in hex)
			blob [9] = 0x53;
			blob [10] = 0x41;
			blob [11] = 0x31;

			byte[] bitlen = GetBytesLE (keyLength << 3);
			blob [12] = bitlen [0];	// bitlen
			blob [13] = bitlen [1];	
			blob [14] = bitlen [2];	
			blob [15] = bitlen [3];

			// public exponent (DWORD)
			int pos = 16;
			int n = p.Exponent.Length;
			while (n > 0)
				blob [pos++] = p.Exponent [--n];
			// modulus
			pos = 20;
			byte[] part = p.Modulus;
			int len = part.Length;
			Array.Reverse (part, 0, len);
			Buffer.BlockCopy (part, 0, blob, pos, len);
			pos += len;
			return blob;
		}
		private RSA getClientCertRSA(RSA privKey)
		{
			RSAParameters rsaParams		= new RSAParameters();
			RSAParameters privateParams = privKey.ExportParameters(true);

			// for RSA m_publickey contains 2 ASN.1 integers
			// the modulus and the public exponent
			ASN1 pubkey = new ASN1 (this.Context.ClientSettings.Certificates[0].GetPublicKey());
			ASN1 modulus = pubkey [0];
			if ((modulus == null) || (modulus.Tag != 0x02))
			{
				return null;
			}
			ASN1 exponent = pubkey [1];
			if (exponent.Tag != 0x02)
			{
				return null;
			}

			rsaParams.Modulus = this.getUnsignedBigInteger(modulus.Value);
			rsaParams.Exponent = exponent.Value;

			// Set private key parameters
			rsaParams.D			= privateParams.D;
			rsaParams.DP		= privateParams.DP;
			rsaParams.DQ		= privateParams.DQ;
			rsaParams.InverseQ	= privateParams.InverseQ;
			rsaParams.P			= privateParams.P;
			rsaParams.Q			= privateParams.Q;			

			// BUG: MS BCL 1.0 can't import a key which 
			// isn't the same size as the one present in
			// the container.
			int keySize = (rsaParams.Modulus.Length << 3);
			RSAManaged rsa = new RSAManaged(keySize);
			rsa.ImportParameters (rsaParams);

			return (RSA)rsa;
		}
Beispiel #37
0
			/*
			 * RSAPrivateKey ::= SEQUENCE {
			 *	version           Version, 
			 *	modulus           INTEGER,  -- n
			 *	publicExponent    INTEGER,  -- e
			 *	privateExponent   INTEGER,  -- d
			 *	prime1            INTEGER,  -- p
			 *	prime2            INTEGER,  -- q
			 *	exponent1         INTEGER,  -- d mod (p-1)
			 *	exponent2         INTEGER,  -- d mod (q-1) 
			 *	coefficient       INTEGER,  -- (inverse of q) mod p
			 *	otherPrimeInfos   OtherPrimeInfos OPTIONAL 
			 * }
			 */
			static public byte[] Encode (RSA rsa) 
			{
				RSAParameters param = rsa.ExportParameters (true);

				ASN1 rsaPrivateKey = new ASN1 (0x30);
				rsaPrivateKey.Add (new ASN1 (0x02, new byte [1] { 0x00 }));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Modulus));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Exponent));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.D));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.P));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.Q));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DP));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.DQ));
				rsaPrivateKey.Add (ASN1Convert.FromUnsignedBigInteger (param.InverseQ));

				return rsaPrivateKey.GetBytes ();
			}
Beispiel #38
0
 public static byte[] getModulus(RSA rsa)
 {
     return rsa.ExportParameters(false).Modulus;
 }