ImportParameters() public method

Imports the specified RSAParameters
public ImportParameters ( RSAParameters parameters ) : void
parameters RSAParameters
return void
		public static D2LSecurityToken CreateTokenWithTimeRemaining(
			TimeSpan remaining,
			Guid? id = null
		) {

			id = id ?? Guid.NewGuid();

			var validTo = DateTime.UtcNow + remaining;
			var validFrom = validTo - TimeSpan.FromHours( 1 );

			RSAParameters privateKey;
			using( var csp = new RSACryptoServiceProvider( Keys.Constants.GENERATED_RSA_KEY_SIZE ) {
				PersistKeyInCsp = false
			} ) {
				privateKey = csp.ExportParameters( includePrivateParameters: true );
			}

			return new D2LSecurityToken(
				id.Value,
				validFrom,
				validTo,
				keyFactory: () => {
					var csp = new RSACryptoServiceProvider() { PersistKeyInCsp = false };
					csp.ImportParameters( privateKey );
					var key = new RsaSecurityKey( csp );
					return new Tuple<AsymmetricSecurityKey, IDisposable>( key, csp );
				}
			);
		}
Example #2
1
        public static void EncryptionKeyRequest(MinecraftClient client, IPacket _packet)
        {
            var packet = (EncryptionKeyRequestPacket)_packet;
            var random = RandomNumberGenerator.Create();
            client.SharedSecret = new byte[16];
            random.GetBytes(client.SharedSecret); // Generate a secure AES key

            if (packet.ServerId != "-") // Online mode
            {
                // Authenticate with minecraft.net
                var data = Encoding.ASCII.GetBytes(packet.ServerId)
                    .Concat(client.SharedSecret)
                    .Concat(packet.PublicKey).ToArray();
                var hash = Cryptography.JavaHexDigest(data);
                var webClient = new WebClient();
                string result = webClient.DownloadString("http://session.minecraft.net/game/joinserver.jsp?user="******"&sessionId=" + Uri.EscapeUriString(client.Session.SessionId) +
                    "&serverId=" + Uri.EscapeUriString(hash));
                if (result != "OK")
                    LogProvider.Log("Unable to verify session: " + result);
            }

            var parser = new AsnKeyParser(packet.PublicKey);
            var key = parser.ParseRSAPublicKey();

            // Encrypt shared secret and verification token
            var crypto = new RSACryptoServiceProvider();
            crypto.ImportParameters(key);
            var encryptedSharedSecret = crypto.Encrypt(client.SharedSecret, false);
            var encryptedVerification = crypto.Encrypt(packet.VerificationToken, false);
            var response = new EncryptionKeyResponsePacket(encryptedSharedSecret, encryptedVerification);
            client.SendPacket(response);
        }
Example #3
1
        static async Task MainAsync(string[] args)
        {
            var keyClient = new KeyVaultClient((authority, resource, scope) =>
            {
                var adCredential = new ClientCredential(applicationId, applicationSecret);
                var authenticationContext = new AuthenticationContext(authority, null);
                return authenticationContext.AcquireToken(resource, adCredential).AccessToken;
            });

            // Get the key details
            var keyIdentifier = "https://testvaultrahul.vault.azure.net/keys/rahulkey/0f653b06c1d94159bc7090596bbf7784";
            var key = await keyClient.GetKeyAsync(keyIdentifier);
            var publicKey = Convert.ToBase64String(key.Key.N);

            using (var rsa = new RSACryptoServiceProvider())
            {
                var p = new RSAParameters() { Modulus = key.Key.N, Exponent = key.Key.E };
                rsa.ImportParameters(p);
                var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
                
                // Encrypt and Decrypt
                var encryptedText = rsa.Encrypt(byteData, true);
                var decryptedData = await keyClient.DecryptDataAsync(keyIdentifier, "RSA_OAEP", encryptedText);
                var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);

                // Sign and Verify
                var hasher = new SHA256CryptoServiceProvider();
                var digest = hasher.ComputeHash(byteData);
                var signature = await keyClient.SignAsync(keyIdentifier, "RS256", digest);
                var isVerified = rsa.VerifyHash(digest, "Sha256", signature.Result);
            }
        }
Example #4
0
        public static RSAViewModel rsa2(RSAViewModel model)
        {
            try
            {
                int keySize = 1024;
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize);

                RSAParameters publickey = rsa.ExportParameters(false); // don't export private key
                RSAParameters privatekey = rsa.ExportParameters(true); // export private key
                //\b 123\b0
                model.PublicKey = "e=" + ByteToString(publickey.Exponent) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus);
                model.PrivateKey = "d=" + ByteToString(privatekey.D) + Environment.NewLine + "n=" + ByteToString(publickey.Modulus);

                rsa.ImportParameters(publickey);
                byte[] encryptedData = rsa.Encrypt(StringToByte(model.PlainText), true);

                model.CipherText=ByteToString(encryptedData);

                rsa.ImportParameters(privatekey);
                byte[] decryptedData = rsa.Decrypt(encryptedData, true);

                model.DecryptedText = ByteToAscii(decryptedData);

            }
            catch (CryptographicException ex)
            {

            }
            return model;
        }
Example #5
0
        private readonly static RSAParameters PrivateParams = Rsa.ExportParameters(true); //Complete key pairs.

        /// <summary>
        /// Encrypt an input string 
        /// </summary>
        /// <param name="input">the input string to be encrpty</param>
        /// <param name="signature">the private key signature</param>
        /// <returns>A Base 64 encrypted string or empty if can't encrpyt</returns>
        public static string Encrpyt(string input, out byte[] signature)
        {
            signature = null;
            try
            {
                if (string.IsNullOrEmpty(input)) return string.Empty;
                var provider = new RSACryptoServiceProvider(new CspParameters { Flags = CspProviderFlags.UseMachineKeyStore });
                provider.ImportParameters(PublicParams);

                var buffer = Encoding.ASCII.GetBytes(input);
                var encryptedbuffer = provider.Encrypt(buffer, false);

                var hash = new SHA1Managed();
                provider.ImportParameters(PrivateParams);
                var hashedData = hash.ComputeHash(encryptedbuffer);
                signature = provider.SignHash(hashedData, CryptoConfig.MapNameToOID("SHA1"));

                var stringBuilder = new StringBuilder();
                stringBuilder.Append(Convert.ToBase64String(encryptedbuffer));

                return stringBuilder.ToString();
            }
            catch
            {
                return string.Empty;
            }
        }
Example #6
0
 public static string DecryptPublicRSA(string input, string key, bool KeyIsPublic)
 {
     SysCrypt.RSACryptoServiceProvider rsa = new SysCrypt.RSACryptoServiceProvider();
     if (!KeyIsPublic)
     {
         rsa.ImportParameters(GetPrivateKeyParams(key));
         SysCrypt.RSAParameters p = rsa.ExportParameters(false);
         rsa.ImportParameters(p);
     }
     else
         rsa.ImportParameters(GetPublicKeyParams(key));
     return DoDecrypt(input, rsa);
 }
Example #7
0
        /// <summary>
        /// Проверяет, действительна ли лицензия.
        /// Это включает проверку подписи на ней,
        /// а также сроков ее действия.
        /// </summary>
        /// <param name="license">Лицензия</param>
        /// <returns>true если лицензия действительна. Иначе false.</returns>
        public bool IsValid(LicenseInfo license)
        {
            if (license == null)
                throw new ArgumentNullException("license cannot be null");

            try
            {
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
                rsa.ImportParameters(_publicKey);
                if (!rsa.VerifyData(
                    GetBytesToSign(license),
                    "SHA1",
                    license.Signature
                    )
                    )
                    return false;

                if (!(license.IssueDate <= DateTime.Now &&
                    DateTime.Now <= license.IssueDate + license.Duration)
                    )
                    return false;
            }
            catch
            {
                return false;
            }

            return true;
        }
        public void GetProviderFromDerEncodedRsaPrivateKey()
        {
            string keyValid;
            string keyDER = null;

            RSAParameters parameters = new RSAParameters();
            parameters.D = Convert.FromBase64String(@"pRgiRK2tfvFdYcGbiqyJ+rgi/HTAPEnR/dtr87I5ctDwOzBG0qOaB3oiUW7qEU0G0iy4hNc1zaHsjhSZYgKZEHP+Xgs7RJZYOTPI9sqbymrDJDLur7h2pMvsqLhcJjEn6qz+hnLMT046D9uSMg9Tpr0Z6FUiOoAwnUZcSK50gj0=");
            parameters.DP = Convert.FromBase64String(@"w49jS+lsTPP5l8QLmMWeyKQ1PzWpRWsV0DJPHRZFHdjNtQkW1zMn5yJsGJ0a9yqXROv6n3BY18iuqY0S/c2PYw==");
            parameters.DQ = Convert.FromBase64String(@"tzis4VqnqbIsZ/CkcBE6Nz3/Rk9nnU5Bw6JyZMs2DVY3JJtOVdmqzZmQ4KquonW5IH6ti3W3844ao+sHm3o3xQ==");
            parameters.Exponent = Convert.FromBase64String(@"AQAB");
            parameters.InverseQ = Convert.FromBase64String(@"/ihX2MBotgMyCIhbyR8l/7G877/nF5BFIC8RGUJqh0SFovYRHVEleLTK7Pi7eA7+OokKEwshZlfwPuE7xiIKyw==");
            parameters.Modulus = Convert.FromBase64String(@"9ws/iSH6l00F/3HUhoJQyY2Y1iorw0roP9BcZRxEmtEfRzPmLnWwrQpusWJUfK71LQu/OLPD9qtnfQdVIGBMns7gfFJBGq+Dsef7CVRb0HIZv3kqUAh8AI46KIx3xRKsdVY4mh7QZcSdAyHHUi0839yNVbObhXDUNETgT5CzKFU=");
            parameters.P = Convert.FromBase64String(@"/u0mEbvml8X8DrbKBiB0QGX9+G2ALRN+SwasDi7jW65SeBf49ENPxH8iC5XXB/yxQpBV2RojferhdE4Nh1+btw==");
            parameters.Q = Convert.FromBase64String(@"+BWZ2QG6x2gL5qOqfZd6wtP/eQRLVz9OC2IUfw0ZojHuWXt45ybw/F+o+bQmyQcTFYES6hFYTUtWjMgn5IG0Uw==");

            using (RSACryptoServiceProvider providerValid = new RSACryptoServiceProvider())
            {
                providerValid.ImportParameters(parameters);
                keyValid = providerValid.ToXmlString(true);
            }

            byte[] fileBytes = File.ReadAllBytes(@"..\..\..\..\Resources\Tests\private.der");
            using (RSACryptoServiceProvider providerDER = RSACryptoHelper.GetProviderFromDerEncodedRsaPrivateKey(fileBytes))
            {
                if (providerDER != null)
                    keyDER = providerDER.ToXmlString(true);
            }

            Assert.AreEqual(keyValid, keyDER);
        }
Example #9
0
 /// <summary>
 /// 加密成base64字符串
 /// </summary>
 /// <param name="publicKey"></param>
 /// <param name="content"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public static string Encrypt2Base64(RSAParameters publicKey, string content, int size = 1024)
 {
     var rsa = new RSACryptoServiceProvider(size);
     rsa.ImportParameters(publicKey);
     var cipherbytes = rsa.Encrypt(content.ToUtf8Bytes(), false);
     return cipherbytes.Bytes2Base64();
 }
Example #10
0
        /// <summary>
        /// 证书方式签名(多证书时使用),指定证书路径。
        /// </summary>
        /// <param name="reqData">请求的数据源</param>
        /// <param name="certRawData">证书数据</param>
        /// <param name="certPwd">证书密码</param>
        /// <param name="encoding">编码方式</param>
        public static void SignByCertInfo(Dictionary <string, string> reqData, byte[] certRawData, string certPwd, Encoding encoding)
        {
            var cert = new X509Certificate2(certRawData, certPwd, X509KeyStorageFlags.Exportable);

            reqData["certId"] = new System.Numerics.BigInteger(cert.GetSerialNumber()).ToString();

            //将Dictionary信息转换成key1=value1&key2=value2的形式
            string stringData = SDKUtil.CreateLinkString(reqData, true, false, encoding);

            byte[] signDigest       = System.Security.Cryptography.SHA256.Create().ComputeHash(encoding.GetBytes(stringData));
            string stringSignDigest = SDKUtil.ByteArray2HexString(signDigest);

            //bug 修复,类型对不上, 直接继承公共的基类,避免类型错误。
            var rsa = cert.PrivateKey as System.Security.Cryptography.RSA;

            // Create a new RSACryptoServiceProvider
            var rsaClear = new System.Security.Cryptography.RSACryptoServiceProvider();

            // Export RSA parameters from 'rsa' and import them into 'rsaClear'
            rsaClear.ImportParameters(rsa.ExportParameters(true));
            byte[] byteSign = rsaClear.SignData(encoding.GetBytes(stringSignDigest), System.Security.Cryptography.SHA256.Create());

            string stringSign = Convert.ToBase64String(byteSign);

            //设置签名域值
            reqData["signature"] = stringSign;
        }
Example #11
0
        public static string SignData(byte[] message, RSAParameters privateKey)
        {
            //// The array to store the signed message in bytes
            byte[] signedBytes;
            using (var rsa = new RSACryptoServiceProvider())
            {
                byte[] originalData = message;

                try
                {
                    //// Import the private key used for signing the message
                    rsa.ImportParameters(privateKey);

                    //// Sign the data, using SHA512 as the hashing algorithm
                    signedBytes = rsa.SignData(originalData, CryptoConfig.MapNameToOID("SHA512"));
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return null;
                }
                finally
                {
                    //// Set the keycontainer to be cleared when rsa is garbage collected.
                    rsa.PersistKeyInCsp = false;
                }
            }
            //// Convert the a base64 string before returning
            return Convert.ToBase64String(signedBytes);
        }
Example #12
0
		/// <summary>
		/// for clients; pass null as privateKey
		/// </summary>
		internal void SetRSAKey(byte[] publicKey, byte[] privateKey)
		{
			m_rsa = new RSACryptoServiceProvider();

			RSAParameters prm = new RSAParameters();
			prm.Exponent = Extract(publicKey, 0, 3);
			prm.Modulus = Extract(publicKey, 3, 128);

			if (privateKey != null)
			{
				int ptr = 0;
				prm.D = Extract(privateKey, ptr, 128); ptr += 128;
				prm.DP = Extract(privateKey, ptr, 64); ptr += 64;
				prm.DQ = Extract(privateKey, ptr, 64); ptr += 64;
				prm.InverseQ = Extract(privateKey, ptr, 64); ptr += 64;
				prm.P = Extract(privateKey, ptr, 64); ptr += 64;
				prm.Q = Extract(privateKey, ptr, 64); ptr += 64;
			}

			m_rsa.ImportParameters(prm);

			// also generate random symmetric key
			byte[] newKey = new byte[16];
			NetRandom.Default.NextBytes(newKey);
			SetSymmetricKey(newKey);
		}
Example #13
0
        public byte[] Decrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.ImportParameters(RSAKeyInfo);

                return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
        }
Example #14
0
        public frmWEB_Test()
        {
            InitializeComponent();

            // classe per la comunicazione col webservice
            m_ArchivaASP = new Archiva.ASP.Test.ArchivaASP.ArchivaASP();
            m_ArchivaASP.Timeout = 60 * 60 * 1000;

            // ottengo la chiave pubblica del server
            String sKey = "";
            if (m_ArchivaASP.GetKey(ref sKey, ref m_RSA_KeyLength) != 0)
            {
                grpLogin.Enabled = false;
                return;
            }

            // creo il servizio RSA per il server
            m_RSA_Server = new RSACryptoServiceProvider((int)m_RSA_KeyLength);
            ArchivaASP_KEY ServerKey = (ArchivaASP_KEY)ArchivaASP_SERIALIZER.DeserializeObject(sKey, typeof(ArchivaASP_KEY));
            RSAParameters ServerParameters = new RSAParameters();
            ServerParameters.Exponent = ServerKey.Exp;
            ServerParameters.Modulus = ServerKey.Mod;
            m_RSA_Server.ImportParameters(ServerParameters);

            // creo il servizio RSA per il client
            m_RSA_Client = new RSACryptoServiceProvider((int)m_RSA_KeyLength);
            RSAParameters RSA_Param = m_RSA_Client.ExportParameters(false);
            m_UserKey = new ArchivaASP_KEY();
            m_UserKey.Mod = RSA_Param.Modulus;
            m_UserKey.Exp = RSA_Param.Exponent;
        }
        public static string Encrypt(string toEncrypt)
        {
            string retval;

            var csp = new RSACryptoServiceProvider();

            RSAParameters pubKey;
            using (StreamReader sr = new StreamReader("pub.key"))
            {
                string readdata = sr.ReadLine();
                var stringReader = new System.IO.StringReader(readdata);
                var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
                pubKey = (RSAParameters)xs.Deserialize(sr);
            }
            csp.ImportParameters(pubKey);

            var bytesPlainTextData = Encoding.Unicode.GetBytes(toEncrypt);

            var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

            var cypherText = Convert.ToBase64String(bytesCypherText);


            return cypherText;
        }
Example #16
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                using (MemoryStream mS = new MemoryStream(Encoding.UTF8.GetBytes(txtRSAKey.Text)))
                {
                    _parameters = PEMFormat.ReadRSAPrivateKey(mS);
                }

                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(_parameters);

                    if (rsa.KeySize < 4096)
                    {
                        MessageBox.Show("The RSA private key must be at least 4096-bit. The current key is " + rsa.KeySize + "-bit.", "Short RSA Private Key", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                this.DialogResult = System.Windows.Forms.DialogResult.OK;
                this.Close();
            }
            catch
            {
                MessageBox.Show("Error in reading PEM format. Please make sure you have pasted the RSA private key in a proper PEM format.", "Invalid PEM Format", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #17
0
        public bool verify(byte[] sig)
        {
            m_cs.Close();
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.ImportParameters(m_RSAKeyInfo);
            RSAPKCS1SignatureDeformatter RSADeformatter = new RSAPKCS1SignatureDeformatter(RSA);
            RSADeformatter.SetHashAlgorithm("SHA1");

            long i = 0;
            long j = 0;
            byte[] tmp;

            if (sig[0] == 0 && sig[1] == 0 && sig[2] == 0)
            {
                long i1 = (sig[i++] << 24) & 0xff000000;
                long i2 = (sig[i++] << 16) & 0x00ff0000;
                long i3 = (sig[i++] << 8) & 0x0000ff00;
                long i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                i += j;

                i1 = (sig[i++] << 24) & 0xff000000;
                i2 = (sig[i++] << 16) & 0x00ff0000;
                i3 = (sig[i++] << 8) & 0x0000ff00;
                i4 = (sig[i++]) & 0x000000ff;
                j = i1 | i2 | i3 | i4;

                tmp = new byte[j];
                Array.Copy(sig, i, tmp, 0, j);
                sig = tmp;
            }
            return RSADeformatter.VerifySignature(m_sha1, sig);
        }
Example #18
0
        static void Main(string[] args)
        {
            var rsa = new RSACryptoServiceProvider();
            _publicKey = rsa.ExportParameters(false);
            _privateKey = rsa.ExportParameters(true);
            Console.WriteLine("\n********* Public key info *******************");
            printInfo(_publicKey);
            Console.WriteLine("\n********* Private key info *******************");
            printInfo(_privateKey);

            var message = "I am a plain text message";
            var messageContent = Encoding.UTF8.GetBytes(message.ToCharArray());

            Console.WriteLine("**** Plain Message ****");
            Console.WriteLine(Encoding.UTF8.GetString(messageContent));

            var encrypter = new RSACryptoServiceProvider();
            encrypter.ImportParameters(_publicKey);
            var encryptedMessage = encrypter.Encrypt(messageContent, true);

            Console.WriteLine("**** Encrypted Message ****");
            Console.WriteLine(Convert.ToBase64String(encryptedMessage));

            var decrypter = new RSACryptoServiceProvider();
            decrypter.ImportParameters(_privateKey);
            var decryptedMessage = decrypter.Decrypt(encryptedMessage, true);

            Console.WriteLine("**** Decrypted Message ****");
            Console.WriteLine(Encoding.UTF8.GetString(decryptedMessage));
        }
 /// <summary>Extracts the <see cref="Key"/> from the given PKCS8 private key.</summary>
 public Initializer FromPrivateKey(string privateKey)
 {
     RSAParameters rsaParameters = ConvertPKCS8ToRSAParameters(privateKey);
     Key = new RSACryptoServiceProvider();
     Key.ImportParameters(rsaParameters);
     return this;
 }
Example #20
0
 /// <summary>
 /// 从base64字符串解密
 /// </summary>
 /// <param name="privateKey"></param>
 /// <param name="content"></param>
 /// <param name="size"></param>
 /// <returns></returns>
 public static string DecryptFromBase64(RSAParameters privateKey, string content, int size = 1024)
 {
     var rsa = new RSACryptoServiceProvider(size);
     rsa.ImportParameters(privateKey);
     var cipherbytes = rsa.Decrypt(content.Base64ToBytes(), false);
     return cipherbytes.FromUtf8Bytes();
 }
Example #21
0
        /// <summary>
        /// Decrypt a base 64 string hash
        /// </summary>
        /// <param name="hash">The encrypted hash</param>
        /// <param name="signature">the private key signature</param>
        /// <returns>If is valid return decrypt hash, else return empty string</returns>
        public static string Decrypt(string hash, byte[] signature)
        {
            if (!VerifyHash(hash, signature)) return string.Empty;
            try
            {
                var provider = new RSACryptoServiceProvider();
                provider.ImportParameters(PrivateParams);

                var encryptedbuffer = Convert.FromBase64String(hash);

                var decryptedbuffer = provider.Decrypt(encryptedbuffer, false);
                var arrayList = new ArrayList();

                arrayList.AddRange(decryptedbuffer);
                var converted = arrayList.ToArray(typeof(byte)) as byte[];

                if (converted != null) return Encoding.ASCII.GetString(converted);

                return string.Empty;
            }
            catch 
            {
                return string.Empty;
            }
        }
Example #22
0
        public static bool VerifyData(string originalMessage, string signedMessage, RSAParameters Parameters)
        {
            bool success = false;
            var encoder = new UTF8Encoding();
            byte[] bytesToVerify = encoder.GetBytes(originalMessage);
            byte[] signedBytes = Convert.FromBase64String(signedMessage);

            RSAParameters parameters = Parameters;

            using (var rsa = new RSACryptoServiceProvider())
            {
                try
                {
                    rsa.ImportParameters(parameters);
                    SHA256Managed Hash = new SHA256Managed();

                    byte[] hashedData = Hash.ComputeHash(bytesToVerify);
                    success = rsa.VerifyData(hashedData, CryptoConfig.MapNameToOID("SHA256"), signedBytes);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
            return success;
        }
Example #23
0
		static OAuthServerHelper()
		{
			RSAParameters privateRsaParameters;
			RSAParameters publicRsaParameters;
			using (var rsaKeyGen = new RSACryptoServiceProvider(RsaKeySize))
			{
				privateRsaParameters = rsaKeyGen.ExportParameters(true);
				publicRsaParameters = rsaKeyGen.ExportParameters(false);
			}

			Tuple<byte[], byte[]> aesKeyAndIV;
			using (var aesKeyGen = new AesCryptoServiceProvider())
			{
				aesKeyAndIV = Tuple.Create(aesKeyGen.Key, aesKeyGen.IV);
			}

			rsa = new ThreadLocal<RSACryptoServiceProvider>(() =>
			{
				var result = new RSACryptoServiceProvider();
				result.ImportParameters(privateRsaParameters);
				return result;
			});

			aes = new ThreadLocal<AesCryptoServiceProvider>(() =>
			{
				var result = new AesCryptoServiceProvider();
				result.Key = aesKeyAndIV.Item1;
				result.IV = aesKeyAndIV.Item2;
				return result;
			});

			rsaExponent = OAuthHelper.BytesToString(publicRsaParameters.Exponent);
			rsaModulus = OAuthHelper.BytesToString(publicRsaParameters.Modulus);
		}
Example #24
0
        public static bool VerifyLicense(string licenseTo, string licenseKey) {
            AssertKeyIsNotBanned(licenseKey);

            const string modulusString =
                "tccosXHxEfxzsO1NgsAbGT0X+WuQMUYcj7r2UJCHDqqq3TbR7UoAgzjm3MV1k/eJxRnURypw2wj98eafyajeprk3lK6BnWa5tG8S7p3QU5kkUo7TnmTj8rRkTk9RwArIGGjKfCVZToE06UQudsJmw1UK3mku1qF0/hD909cSiCM=";
            const string exponentString = "AQAB";

            byte[] data = Encoding.UTF8.GetBytes(licenseTo);

            RSAParameters rsaParameters = new RSAParameters {
                Modulus = Convert.FromBase64String(modulusString),
                Exponent = Convert.FromBase64String(exponentString)
            };
#if STANDARD
            using( var rsa = System.Security.Cryptography.RSA.Create() )
#else
            using (RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
#endif
            {
                byte[] licenseData = Convert.FromBase64String(licenseKey);
                rsa.ImportParameters(rsaParameters);

                bool verified = false;

#if STANDARD
                verified = rsa.VerifyData(data, licenseData, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
#else
                verified = rsa.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), licenseData);
#endif
                return verified;
            }
        }
        //static RSACryptoServiceProvider RSA;

        //public static void ExportParameters()
        //{
        //    var publicKey = RSA.ExportParameters(false);

        //    //            +Exponent    { byte[3]}
        //    //+Modulus { byte[256]}


        //}


        public async Task<byte[]> Encrypt(byte[] Exponent, byte[] Modulus)
        {
			// https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323

			// encrypted state sharing.

			// what about import?

			// http://bouncy-castle.1462172.n4.nabble.com/Interoperability-issue-with-SunJCE-OAEP-td4656157.html

			// http://www.w3.org/TR/WebCryptoAPI/#rsa-oaep
			// RSA/ECB/OAEPWithSHA-1AndMGF1Padding

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

			//var n = new RSACryptoServiceProvider(2048);
			var n = new RSACryptoServiceProvider();

			// can we import in java android?
            n.ImportParameters(
                new RSAParameters { Exponent = Exponent, Modulus = Modulus }
            );

            // http://stackoverflow.com/questions/9839274/rsa-encryption-by-supplying-modulus-and-exponent

            var value = n.Encrypt(
                Encoding.UTF8.GetBytes("hello from server"), fOAEP: true
            );

            //Array.Reverse(value);

            return value;
        }
Example #26
0
        public RSACrypto( byte[] key )
        {
            AsnKeyParser keyParser = new AsnKeyParser( key );

            rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters( keyParser.ParseRSAPublicKey() );
        }
Example #27
0
        public static string ToPEM (RSAKeyPair RSAKeyPair) {

            var Provider = RSAKeyPair.Provider;
            Assert.Null(Provider, NoProviderSpecified.Throw);

            var RSAParameters = Provider.ExportParameters(true);
            Assert.Null(RSAParameters, PrivateKeyNotAvailable.Throw);

            var NewProvider = new RSACryptoServiceProvider();
            NewProvider.ImportParameters(RSAParameters);


            RSAParameters.Dump();

            var RSAPrivateKey = new RSAPrivateKey(RSAParameters);

            var Builder = new StringBuilder();

            Builder.Append("-----BEGIN RSA PRIVATE KEY-----");

            var KeyDER = RSAPrivateKey.DER();
            Builder.AppendBase64(KeyDER);


            Builder.Append("\n-----END RSA PRIVATE KEY-----\n");


            return Builder.ToString();

            }
Example #28
0
        static void Main(string[] args)
        {
            // Create message and signature on your end
            string message = "Here is the license message";
            var secret = "wangchunlei";
            var converter = new ASCIIEncoding();
            byte[] plainText = converter.GetBytes(secret);

            var rsaWrite = new RSACryptoServiceProvider();
            var privateParams = rsaWrite.ExportParameters(true);

            // Generate the public key / these can be sent to the user.
            var publicParams = rsaWrite.ExportParameters(false);

            byte[] signature =
                rsaWrite.SignData(plainText, new SHA1CryptoServiceProvider());

            // Verify from the user's side. Note that only the public parameters
            // are needed.
            var rsaRead = new RSACryptoServiceProvider();
            rsaRead.ImportParameters(publicParams);
            if (rsaRead.VerifyData(plainText,
                                new SHA1CryptoServiceProvider(),
                                signature))
            {
                Console.WriteLine("Verified!");
            }
            else
            {
                Console.WriteLine("NOT verified!");
            }
        }
Example #29
0
        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                //Create a new instance of RSACryptoServiceProvider. 
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    //Import the RSA Key information. This needs 
                    //to include the private key information.
                    RSA.ImportParameters(RSAKeyInfo);

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

        }
        public string EncryptData(string data)
        {
            try
            {
                //initialze the byte arrays to the public key information.
                byte[] PublicKey = _publicKey.ToArray();
                byte[] Exponent = _exponent.ToArray();

                //Create a new instance of RSACryptoServiceProvider.
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Create a new instance of RSAParameters.
                RSAParameters RSAKeyInfo = new RSAParameters();

                //Set RSAKeyInfo to the public key values.
                RSAKeyInfo.Modulus = PublicKey;
                RSAKeyInfo.Exponent = Exponent;

                //Import key parameters into RSA.
                RSA.ImportParameters(RSAKeyInfo);

                var dataBytes = ASCIIEncoding.ASCII.GetBytes(data);
                var encryptedBytes = RSA.Encrypt(dataBytes, false);
                var encryptedValue = BitConverter.ToString(encryptedBytes).Replace("-", "").ToLower();
                return encryptedValue;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
            }

            return null;
        }
Example #31
0
        public override void Encrypt()
            {
                //RSA Rsa = new RSA();
                //base.Component.Text = Rsa.encode(base.Component.tp.Text);

                try
                {
                    UnicodeEncoding ByteConverter = new UnicodeEncoding();
                    byte[] encryptedData;
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSA.ImportParameters(RSA.ExportParameters(false));
  
                        
                        byte[] Data = ByteConverter.GetBytes(base.Component.tp.Text.ToString());
                        encryptedData = RSA.Encrypt(Data , false);
                    }
                    base.Component.Text = ByteConverter.GetString(encryptedData);
                }
                //Catch and display a CryptographicException  
                //to the console.
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    base.Component.Text = base.Component.tp.Text.ToString();
                }
               
            }
Example #32
0
 /// <summary>
 /// Decrypts a string which was previously encrypted with the Encrypt method
 /// </summary>
 /// <param name="cipher">The encrypted byte array</param>
 /// <param name="privateKey">The private key used to decrypt the data</param>
 /// <returns>A byte array containing the decrypted value</returns>
 public static string Decrypt(string cipher, RSAParameters privateKey)
 {
     using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
     {
         //ImportParameters sets the keySize according to the size used to create the privateKey
         rsa.ImportParameters(privateKey);
         int base64BlockSize = ((rsa.KeySize / 8) % 3 != 0) ? (((rsa.KeySize / 8) / 3) * 4) + 4 : ((rsa.KeySize / 8) / 3) * 4;
         int iterations      = cipher.Length / base64BlockSize;
         //var arrayList = new ArrayList();
         var fullBytes = new byte[0];
         for (int i = 0; i < iterations; i++)
         {
             byte[] encryptedBytes = Convert.FromBase64String(cipher.Substring(base64BlockSize * i, base64BlockSize));
             // Be aware the RSACryptoServiceProvider reverses the order of
             // encrypted bytes after encryption and before decryption.
             // If you do not require compatibility with Microsoft Cryptographic
             // API (CAPI) and/or other vendors.
             // Comment out the next line and the corresponding one in the
             // EncryptString function.
             Array.Reverse(encryptedBytes);
             var bytes = rsa.Decrypt(encryptedBytes, true);
             var len   = fullBytes.Length;
             Array.Resize(ref fullBytes, len + bytes.Length);
             Array.Copy(bytes, 0, fullBytes, len, bytes.Length);
             //arrayList.AddRange(bytes);
         }
         return(Encoding.UTF32.GetString(fullBytes));
         //return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
     }
 }
Example #33
0
        public static bool VerifyLicense(string licenseTo, string licenseKey)
        {
            AssertKeyIsNotBanned(licenseKey);

            const string modulusString =
                "vBgOPQiBhRR22ClUzIBJCmxcaOWfuAweUNpodRuZWDn8whviOe4JdA/sjzqw54KGh1qHJIc7JY5sGTCxNZQiSuyZQ6iHK2ykmU0Yb+QBvbqG33x2R7Di8MoNA1Tv2fX7SSny++IKEOQEEvwYhYr6oRU8sVItMcybUjiaaSw1rbU=";
            const string exponentString = "AQAB";

            var data = Encoding.UTF8.GetBytes(licenseTo);

            var rsaParameters = new RSAParameters
            {
                Modulus  = Convert.FromBase64String(modulusString),
                Exponent = Convert.FromBase64String(exponentString)
            };

#if STANDARD
            using (var rsa = System.Security.Cryptography.RSA.Create())
#else
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
#endif
            {
                var licenseData = Convert.FromBase64String(licenseKey);
                rsa.ImportParameters(rsaParameters);

                bool verified = false;

#if STANDARD
                verified = rsa.VerifyData(data, licenseData, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
#else
                verified = rsa.VerifyData(data, CryptoConfig.MapNameToOID("SHA256"), licenseData);
#endif
                return(verified);
            }
        }
Example #34
0
File: RSA.cs Project: dr1s/rom_tool
        static public byte[] RSAEncrypt(int bits, byte[] dataToEncrypt, RSAParameters rsaKeyInfo, bool doOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (var rsa = new RSACryptoServiceProvider(bits))
                {

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

                    var rsaExportParameters = rsa.ExportParameters(true);

                    var rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);
                    rsaFormatter.SetHashAlgorithm("SHA256");

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

                return null;
            }

        }
            /// <summary>Extracts the <see cref="Key"/> from the given PKCS8 private key.</summary>
            public Initializer FromPrivateKey(string privateKey)
            {
                RSAParameters rsaParameters = Pkcs8.DecodeRsaParameters(privateKey);

                Key = (RsaKey)RSA.Create();
                Key.ImportParameters(rsaParameters);
                return(this);
            }
        /// <inheritdoc/>
        public ICryptographicKey ImportPublicKey(byte[] keyBlob, CryptographicPublicKeyBlobType blobType = CryptographicPublicKeyBlobType.X509SubjectPublicKeyInfo)
        {
            Requires.NotNull(keyBlob, "keyBlob");

            var rsa = new Platform.RSACryptoServiceProvider();

            rsa.ImportParameters(KeyFormatter.ToPlatformParameters(KeyFormatter.GetFormatter(blobType).Read(keyBlob)));
            return(new RsaCryptographicKey(rsa, this.algorithm));
        }
Example #37
0
        public static string RSAKeysToXmlString(RSAParameters nKey, bool nIncludePrivateParameters)
        {
            RSACryptoServiceProvider.UseMachineKeyStore = true;

            var rsa = new System.Security.Cryptography.RSACryptoServiceProvider();

            rsa.ImportParameters(nKey);

            return(rsa.ToXmlString(nIncludePrivateParameters));
        }
Example #38
0
 public static bool verify(string content, string signedString, string publicKey, string input_charset)
 {
     System.Text.Encoding encoding = System.Text.Encoding.GetEncoding(input_charset);
     byte[] bytes     = encoding.GetBytes(content);
     byte[] signature = System.Convert.FromBase64String(signedString);
     System.Security.Cryptography.RSAParameters            parameters = RSAFromPkcs8.ConvertFromPublicKey(publicKey);
     System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
     rSACryptoServiceProvider.ImportParameters(parameters);
     System.Security.Cryptography.SHA1 halg = new System.Security.Cryptography.SHA1CryptoServiceProvider();
     return(rSACryptoServiceProvider.VerifyData(bytes, halg, signature));
 }
Example #39
0
        public RsaSecurityKey GetKey()
        {
            if (NeedsUpdate())
            {
                GenerateKeyAndSave();
            }
            var provider = new System.Security.Cryptography.RSACryptoServiceProvider();

            provider.ImportParameters(GetKeyParameters());
            return(new RsaSecurityKey(provider));
        }
Example #40
0
        public static string decrypt(string elementToDesencrypt, string pathPublicKey)
        {
            string pem = System.IO.File.ReadAllText(pathPublicKey);

            byte[] Buffer = getBytesFromPEMFile(pem, "RSA PRIVATE KEY");
            System.Security.Cryptography.RSACryptoServiceProvider rsa      = new System.Security.Cryptography.RSACryptoServiceProvider();
            System.Security.Cryptography.RSAParameters            rsaParam = rsa.ExportParameters(false);
            rsaParam.Modulus = Buffer;
            rsa.ImportParameters(rsaParam);
            byte[] text = Encoding.UTF8.GetBytes(elementToDesencrypt); //Convert.FromBase64String(elementToDesencrypt)
            byte[] encryptedMessageByte = rsa.Decrypt(text, false);
            return(Convert.ToBase64String(encryptedMessageByte));
        }
Example #41
0
        /// <summary>
        /// 基于证书对 RSA 签名校验
        /// </summary>
        /// <param name="data">要签名的文本</param>
        /// <param name="signatureText">签名(十六进制格式文本)</param>
        /// <param name="publicKeyPemString">公钥内容(PEM格式的,即base64格式的证书文件内容)</param>
        /// <returns></returns>
        public static bool VerifySignature(string data, string signatureText, string publicKeyPemString)
        {
            publicKeyPemString = publicKeyPemString.Replace("-----BEGIN PUBLIC KEY-----", "")
                                 .Replace("-----END PUBLIC KEY-----", "");
            var signatureBytes           = HexStringToBytes(signatureText);
            var rsaCryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();

            rsaCryptoServiceProvider.ImportParameters(CreateRsaParametersFromPublicKey(publicKeyPemString));
            var RSADeformatter = new RSAPKCS1SignatureDeformatter(rsaCryptoServiceProvider);

            RSADeformatter.SetHashAlgorithm("MD5");
            var           plainTextBytes = Encoding.UTF8.GetBytes(data);
            HashAlgorithm md5            = HashAlgorithm.Create("MD5");
            var           hashBytes      = md5.ComputeHash(plainTextBytes);

            return(RSADeformatter.VerifySignature(hashBytes, signatureBytes));
        }
Example #42
0
        /*
         * converts a bouncy castle private key to a windows private key
         */
        private static sys2.AsymmetricAlgorithm ConvertToSystemKey(RsaPrivateCrtKeyParameters privateKey)
        {
            sys2.CspParameters cspPars = new sys2.CspParameters
            {
                KeyContainerName = Guid.NewGuid().ToString(),
                KeyNumber        = (int)sys2.KeyNumber.Exchange
            };

            sys2.RSACryptoServiceProvider rsaCryptoProvider = new sys2.RSACryptoServiceProvider(cspPars);
            sys2.RSAParameters            rsaParameters     = new sys2.RSAParameters
            {
                Modulus  = privateKey.Modulus.ToByteArrayUnsigned(),
                P        = privateKey.P.ToByteArrayUnsigned(),
                Q        = privateKey.Q.ToByteArrayUnsigned(),
                DP       = privateKey.DP.ToByteArrayUnsigned(),
                DQ       = privateKey.DQ.ToByteArrayUnsigned(),
                InverseQ = privateKey.QInv.ToByteArrayUnsigned(),
                D        = privateKey.Exponent.ToByteArrayUnsigned(),
                Exponent = privateKey.PublicExponent.ToByteArrayUnsigned()
            };

            rsaCryptoProvider.ImportParameters(rsaParameters);
            return(rsaCryptoProvider);
        }
Example #43
0
        public async void StartMQTT(string clientid, string cafile, string clientcertfile, string clientprivate, string clientprivatepassword = "")
        {
            var ca = new X509Certificate(cafile, "");

            var reader     = new PemReader(File.OpenText(clientprivate));
            var privatekey = (AsymmetricCipherKeyPair)reader.ReadObject();
            var pkinfo     = (Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters)privatekey.Private;

            var ce1 = new X509Certificate2(File.ReadAllBytes(clientcertfile), clientprivatepassword,
                                           X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
            CspParameters parms = new CspParameters();

            parms.Flags            = CspProviderFlags.NoFlags;
            parms.KeyContainerName = Guid.NewGuid().ToString().ToUpperInvariant();
            parms.ProviderType     = ((Environment.OSVersion.Version.Major > 5) || ((Environment.OSVersion.Version.Major == 5) && (Environment.OSVersion.Version.Minor >= 1))) ? 0x18 : 1;

            System.Security.Cryptography.RSACryptoServiceProvider rcsp =
                new System.Security.Cryptography.RSACryptoServiceProvider(parms)
            {
                PersistKeyInCsp = true
            };

            rcsp.ImportParameters(DotNetUtilities.ToRSAParameters(pkinfo));
            ce1.PrivateKey = rcsp;

            //var clientcert = CertificatesToDBandBack.Certificate.GetCertificateFromPEMstring(File.ReadAllText(clientcertfile), File.ReadAllText(clientprivate), clientprivatepassword);

            MQTTClient = new MqttFactory().CreateMqttClient();
            var options = new MqttClientOptionsBuilder()
                          .WithTcpServer(mqtt_host, mqtt_port).WithClientId(clientid).WithTls(new MqttClientOptionsBuilderTlsParameters
            {
                AllowUntrustedCertificates        = false,
                IgnoreCertificateChainErrors      = false,
                IgnoreCertificateRevocationErrors = false,
                UseTls       = true,
                SslProtocol  = System.Security.Authentication.SslProtocols.Tls12,
                Certificates = new List <byte[]>
                {
                    ca.Export(X509ContentType.SerializedCert),
                    ce1.Export(X509ContentType.SerializedCert)
                },
                CertificateValidationCallback = (X509Certificate x, X509Chain y, SslPolicyErrors z, IMqttClientOptions o) =>
                {
                    return(true);
                }
            }).Build();

            MQTTClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e =>
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {Encoding.UTF8.GetString(e.ApplicationMessage.Payload)}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
            });
            MQTTClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### CONNECTED WITH SERVER ###");
                await MQTTClient.SubscribeAsync(new TopicFilterBuilder().WithTopic("#").Build());
            });
            MQTTClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(async a =>
            {
                Console.WriteLine("### DISCONNECTED FROM SERVER ###");
            });

            var connect = await MQTTClient.ConnectAsync(options);

            var sub = MQTTClient.SubscribeAsync(new TopicFilter
            {
                Topic = "test", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce
            });
        }
Example #44
0
        public void TestRfc7515Example_A_2_1()
        {
            string protectedSample = // From the RFC example
                                     "{\"alg\":\"RS256\"}";

            byte[] protectedBytesExpected = // From the RFC example
            {
                123, 34, 97, 108, 103, 34, 58, 34, 82, 83, 50, 53, 54, 34, 125
            };
            byte[] protectedBytesActual = Encoding.UTF8.GetBytes(protectedSample);
            CollectionAssert.AreEqual(protectedBytesExpected, protectedBytesActual);

            string protectedB64uExpected = "eyJhbGciOiJSUzI1NiJ9"; // From the RFC example
            string protectedB64uActual   = CryptoHelper.Base64.UrlEncode(protectedBytesActual);

            Assert.AreEqual(protectedB64uExpected, protectedB64uActual);

            string payloadSample = // From the RFC example
                                   "{\"iss\":\"joe\",\r\n" +
                                   " \"exp\":1300819380,\r\n" +
                                   " \"http://example.com/is_root\":true}";

            byte[] payloadBytesActual = Encoding.UTF8.GetBytes(payloadSample);
            string payloadB64uActual  = CryptoHelper.Base64.UrlEncode(payloadBytesActual);
            string signingInput       = $"{protectedB64uActual}.{payloadB64uActual}";

            byte[] signingBytesExpected = // From the RFC example
            {
                101, 121,  74, 104,  98,  71,  99, 105,  79, 105,  74, 83,  85, 122,  73,
                49,   78, 105,  74,  57,  46, 101, 121,  74, 112,  99, 51,  77, 105,  79,105,
                74,  113,  98,  50,  85, 105,  76,  65,  48,  75,  73, 67,  74, 108, 101, 72,
                65,  105,  79, 106,  69, 122,  77,  68,  65,  52,  77, 84, 107, 122,  79, 68,
                65,  115,  68,  81, 111, 103,  73, 109, 104,  48, 100, 72,  65,  54,  76,
                121,  57, 108, 101,  71,  70, 116,  99,  71, 120, 108, 76, 109,  78, 118,
                98,   83,  57, 112,  99,  49,  57, 121,  98,  50,  57, 48,  73, 106, 112, 48,
                99,  110,  86, 108, 102, 81
            };
            byte[] signingBytesActual = Encoding.ASCII.GetBytes(signingInput);
            CollectionAssert.AreEqual(signingBytesExpected, signingBytesActual);


            byte[] sigExpected = // From the RFC example
            {
                112,  46,  33, 137,  67, 232, 143, 209,  30, 181, 216,  45, 191, 120,  69,
                243,  65,   6, 174,  27, 129, 255, 247, 115,  17,  22, 173, 209, 113, 125,
                131, 101, 109,  66,  10, 253,  60, 150, 238, 221, 115, 162, 102,  62,  81,
                102, 104, 123,   0,  11, 135,  34, 110,   1, 135, 237,  16, 115, 249,  69,
                229, 130, 173, 252, 239,  22, 216,  90, 121, 142, 232, 198, 109, 219,
                61,  184, 151,  91,  23, 208, 148,   2, 190, 237, 213, 217, 217, 112,   7,
                16,  141, 178, 129,  96, 213, 248,   4,  12, 167,  68,  87,  98, 184,  31,
                190, 127, 249, 217,  46,  10, 231, 111,  36, 242,  91,  51, 187, 230, 244,
                74,  230,  30, 177,   4,  10, 203,  32,   4,  77,  62, 249,  18, 142, 212,1,
                48,  121,  91, 212, 189,  59,  65, 238, 202, 208, 102, 171, 101,  25, 129,
                253, 228, 141, 247, 127,  55,  45, 195, 139, 159, 175, 221,  59, 239,
                177, 139,  93, 163, 204,  60,  46, 176,  47, 158,  58,  65, 214,  18, 202,
                173,  21, 145,  18, 115, 160,  95,  35, 185, 232,  56, 250, 175, 132, 157,
                105, 132,  41, 239,  90,  30, 136, 121, 130,  54, 195, 212,  14,  96,  69,
                34,  165,  68, 200, 242, 122, 122,  45, 184,   6,  99, 209, 108, 247, 202,
                234,  86, 222,  64,  92, 178,  33,  90,  69, 178, 194,  85, 102, 181,  90,
                193, 167,  72, 160, 112, 223, 200, 163,  42,  70, 149,  67, 208,  25, 238,
                251, 71
            };
            byte[] sigActual = null;
            using (var rsa = new System.Security.Cryptography.RSACryptoServiceProvider())
            {
                rsa.ImportParameters(GetRsaParamsForRfc7515Example_A_2_1());
                using (var sha256 = new System.Security.Cryptography.SHA256CryptoServiceProvider())
                {
                    sigActual = rsa.SignData(signingBytesExpected, sha256);
                }
            }
            CollectionAssert.AreEqual(sigExpected, sigActual);

            string sigB64uExpected = // From the RFC example
                                     "cC4hiUPoj9Eetdgtv3hF80EGrhuB__dzERat0XF9g2VtQgr9PJbu3XOiZj5RZmh7" +
                                     "AAuHIm4Bh-0Qc_lF5YKt_O8W2Fp5jujGbds9uJdbF9CUAr7t1dnZcAcQjbKBYNX4" +
                                     "BAynRFdiuB--f_nZLgrnbyTyWzO75vRK5h6xBArLIARNPvkSjtQBMHlb1L07Qe7K" +
                                     "0GarZRmB_eSN9383LcOLn6_dO--xi12jzDwusC-eOkHWEsqtFZESc6BfI7noOPqv" +
                                     "hJ1phCnvWh6IeYI2w9QOYEUipUTI8np6LbgGY9Fs98rqVt5AXLIhWkWywlVmtVrB" +
                                     "p0igcN_IoypGlUPQGe77Rw";
            string sigB64uActual = CryptoHelper.Base64.UrlEncode(sigActual);

            Assert.AreEqual(sigB64uExpected, sigB64uActual);
        }
Example #45
0
    //===============================================================================
    // Name: Function IALUGenerator_GenKey
    // Input:
    //   ByRef Lic As ActiveLock3.ProductLicense - Product license
    //   ByVal InstCode As String - Installation Code sent by the user
    //   ByVal RegisteredLevel As String - Registration Level for the license. Default is "0"
    // Output:
    //   String - Liberation key for the license
    // Purpose: Given the Installation Code, generates an Activelock license liberation key.
    // Remarks: None
    //===============================================================================
    private string IALUGenerator_GenKey(ref ActiveLock3_6NET.ProductLicense Lic, string InstCode, [System.Runtime.InteropServices.OptionalAttribute, System.Runtime.InteropServices.DefaultParameterValueAttribute("0")]      // ERROR: Optional parameters aren't supported in C#
                                        string RegisteredLevel)
    {
        // Take request code and decrypt it.
        string strReq = null;

        // 05.13.05 - ialkan Modified to merge DLLs into one
        strReq = modBase64.Base64_Decode(ref InstCode);

        // strReq now contains the {LockCode + vbLf + User} string
        string strLock = string.Empty;
        string strUser = string.Empty;

        GetLockAndUserFromInstallCode(strReq, ref strLock, ref strUser);

        Lic.Licensee = strUser;
        // registration date
        string strRegDate = null;

        // registered level
        Lic.RegisteredLevel = RegisteredLevel;
        strRegDate          = Lic.RegisteredDate;

        string strEncrypted = null;

        // @todo Rethink this bit about encrypting the dates.
        // We need to keep in mind that the app does not have access to the private key, so and any decryption that requires private key
        // would not be possible.
        // Perhaps instead of encrypting, we could do MD5 hash of (regdate+lockcode)?
        //ActiveLockEventSink_ValidateValue strRegDate, strEncrypted
        // hash it
        //strEncrypted = ActiveLock3.MD5Hash(strEncrypted)
        strEncrypted = strRegDate;

        // get software codes
        ProductInfo ProdInfo = null;

        ProdInfo       = IALUGenerator_RetrieveProduct(Lic.ProductName, Lic.ProductVer);
        Lic.ProductKey = ProdInfo.VCode;

        string strLic = null;

        strLic = Lic.ToString_Renamed() + Constants.vbLf + strLock;
        System.Diagnostics.Debug.WriteLine("strLic: " + Constants.vbCrLf + strLic);

        if (modALUGEN.strLeft(ProdInfo.VCode, 3) != "RSA")
        {
            // sign it
            string strSig = null;
            strSig = new string(Strings.Chr(0), 1024);
            // 05.13.05 - ialkan Modified to merge DLLs into one. Moved RSASign into a module
            strSig = modActiveLock.RSASign(ProdInfo.VCode, ProdInfo.GCode, strLic);

            // Create liberation key.  This will be a base-64 encoded string of the whole license.
            string strLicKey = null;
            // 05.13.05 - ialkan Modified to merge DLLs into one
            strLicKey = modBase64.Base64_Encode(ref strSig);
            // update Lic with license key
            Lic.LicenseKey = strLicKey;
            // Print some info for debugging purposes
            System.Diagnostics.Debug.WriteLine("VCode: " + ProdInfo.VCode);
            System.Diagnostics.Debug.WriteLine("Lic: " + strLic);
            System.Diagnostics.Debug.WriteLine("Lic hash: " + modMD5.Hash(ref strLic));
            System.Diagnostics.Debug.WriteLine("LicKey: " + strLicKey);
            System.Diagnostics.Debug.WriteLine("Sig: " + strSig);
            System.Diagnostics.Debug.WriteLine("Verify: " + modActiveLock.RSAVerify(ProdInfo.VCode, strLic, modBase64.Base64_Decode(ref strLicKey)));
            System.Diagnostics.Debug.WriteLine("====================================================");
        }

        else
        {
            try {
                System.Security.Cryptography.RSACryptoServiceProvider rsaCSP = new System.Security.Cryptography.RSACryptoServiceProvider();
                string strPublicBlob  = null;
                string strPrivateBlob = null;

                strPublicBlob  = ProdInfo.VCode;
                strPrivateBlob = ProdInfo.GCode;

                if (modALUGEN.strLeft(ProdInfo.GCode, 6) == "RSA512")
                {
                    strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 6);
                }
                else
                {
                    strPrivateBlob = modALUGEN.strRight(ProdInfo.GCode, Strings.Len(ProdInfo.GCode) - 7);
                }
                // import private key params into instance of RSACryptoServiceProvider
                rsaCSP.FromXmlString(strPrivateBlob);
                RSAParameters rsaPrivateParams = default(RSAParameters);
                //stores private key
                rsaPrivateParams = rsaCSP.ExportParameters(true);
                rsaCSP.ImportParameters(rsaPrivateParams);

                byte[] userData = Encoding.UTF8.GetBytes(strLic);

                AsymmetricSignatureFormatter asf = new RSAPKCS1SignatureFormatter(rsaCSP);
                HashAlgorithm algorithm          = new SHA1Managed();
                asf.SetHashAlgorithm(algorithm.ToString());
                byte[] myhashedData = null;
                // a byte array to store hash value
                string myhashedDataString = null;
                myhashedData       = algorithm.ComputeHash(userData);
                myhashedDataString = BitConverter.ToString(myhashedData).Replace("-", string.Empty);
                byte[] mysignature = null;
                // holds signatures
                mysignature = asf.CreateSignature(algorithm);
                string mySignatureBlock = null;
                mySignatureBlock = Convert.ToBase64String(mysignature);
                Lic.LicenseKey   = mySignatureBlock;
            }
            catch (Exception ex) {
                modActiveLock.Set_Locale(modActiveLock.regionalSymbol);
                Err().Raise(AlugenGlobals.alugenErrCodeConstants.alugenProdInvalid, modTrial.ACTIVELOCKSTRING, ex.Message);
            }
        }

        // Serialize it into a formatted string
        string strLibKey = string.Empty;

        Lic.Save(ref strLibKey);
        return(strLibKey);
    }
Example #46
0
        public static void VerifySig(XmlDocument sigDoc)
        {
            try
            {
                XmlElement envelope = sigDoc.DocumentElement;

                XmlElement securityElem = LameXpath.SelectSingleNode(sigDoc, Elem.Security);
                if (securityElem != null)
                {
                    XmlAttribute mustUndAtt = securityElem.Attributes[Attrib.mustUnderstand, Ns.soap];
                    if (mustUndAtt != null)
                    {
                        mustUndAtt.Value = "0";
                    }
                }

                XmlElement sigElem = LameXpath.SelectSingleNode(sigDoc, Elem.Signature);
                if (sigElem == null)
                {
                    return;
                }

                XmlElement sigValElem = LameXpath.SelectSingleNode(sigElem, Elem.SignatureValue);
                byte[]     baSigVal   = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(sigValElem.InnerText);

                bool comments  = false;
                bool exclusive = true;
                System.Security.Cryptography.SHA1CryptoServiceProvider shaCsp = new System.Security.Cryptography.SHA1CryptoServiceProvider();

                XmlElement sigMethElem = LameXpath.SelectSingleNode(sigElem, Elem.SignatureMethod);
                string     segMeth     = sigMethElem.Attributes["Algorithm"].Value;

                XmlElement  signedInfoElem = LameXpath.SelectSingleNode(sigElem, Elem.SignedInfo);
                XmlDocument xdSignedInfo   = new XmlDocument();
                xdSignedInfo.LoadXml(signedInfoElem.OuterXml);
                XmlCanonicalizer xc   = new XmlCanonicalizer(comments, exclusive);
                MemoryStream     ms   = (MemoryStream)xc.Canonicalize(xdSignedInfo);
                byte []          baMs = new byte[ms.Length];
                ms.Read(baMs, 0, baMs.Length);

                ArrayList  keyInfoRefElem = LameXpath.SelectChildNodes(sigElem, Elem.SecurityTokenReference, Elem.Reference);
                XmlElement keyInfoRef     = (XmlElement)keyInfoRefElem[0];
                string     secTokUri      = keyInfoRef.Attributes["URI"].Value;
                secTokUri = secTokUri.TrimStart(new char[] { '#' });
                XmlElement secTokElem = LameXpath.SelectSingleNode(secTokUri, sigDoc);

                if (secTokElem.LocalName == Elem.UsernameToken)
                {
                    XmlElement nonce   = LameXpath.SelectSingleNode(secTokElem, Elem.Nonce);
                    XmlElement created = LameXpath.SelectSingleNode(secTokElem, Elem.Created);
                    //DerivedKeyGenerator seems to be off by 1?
                    //byte [] baKey = P_SHA1.DeriveKey(ClearPassword, StrKeyLabel, nonce.InnerText, created.InnerText, NumKeyBytes);
                    byte []  baKey   = P_SHA1.DeriveKey(SigObj.ClearPassword, StrKeyLabel, nonce.InnerText, created.InnerText, NumKeyBytes);
                    HMACSHA1 hmacSha = new HMACSHA1(baKey);
                    byte []  baSig   = hmacSha.ComputeHash(baMs);
                    OpenNETCF.Security.Cryptography.Internal.Format.SameBytes(baSigVal, baSig);
                }
                else if (secTokElem.LocalName == Elem.BinarySecurityToken)
                {
                    byte[]          baCert = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(secTokElem.InnerText);
                    X509Certificate cert   = new X509Certificate(baCert);                   //pub key to verify sig.
                    byte []         exponent;
                    byte []         modulus;
                    DecodeCertKey.GetPublicRsaParams(cert, out exponent, out modulus);
                    System.Security.Cryptography.RSAParameters rsaParam = new System.Security.Cryptography.RSAParameters();
                    rsaParam.Exponent = exponent;
                    rsaParam.Modulus  = modulus;
                    System.Security.Cryptography.RSACryptoServiceProvider rsaCsp = new System.Security.Cryptography.RSACryptoServiceProvider();
                    rsaCsp.ImportParameters(rsaParam);

                    byte [] baUnsigHash = shaCsp.ComputeHash(baMs);
                    bool    valid       = rsaCsp.VerifyHash(baUnsigHash, "SHA", baSigVal);
                    if (valid == false)
                    {
                        throw new Exception("signature is not valid");
                    }
                }
                else if (secTokElem.LocalName == Elem.SecurityContextToken)
                {
                    //TODO how to validate signature?
                }
                else
                {
                    throw new Exception("only support Username, BinarySecurity, and SecurityContext Token signature");
                }

                //verify reference hashes
                string    refdName = String.Empty;
                ArrayList refNodes = LameXpath.SelectChildNodes(sigDoc, Elem.SignedInfo, Elem.Reference);
                foreach (object oXn in refNodes)
                {
                    XmlNode xn    = (XmlNode)oXn;
                    string  uriId = xn.Attributes[Attrib.URI].Value;
                    uriId = uriId.TrimStart(new char[] { '#' });
                    XmlElement digValElem = LameXpath.SelectSingleNode(xn, Elem.DigestValue);
                    byte[]     baDigest   = OpenNETCF.Security.Cryptography.Internal.Format.GetB64(digValElem.InnerText);

                    XmlElement  refdElem   = LameXpath.SelectSingleNode(uriId, sigDoc);
                    XmlDocument xdRefdElem = new XmlDocument();
                    refdName = refdElem.LocalName;                     //for debug visibility
                    xdRefdElem.LoadXml(refdElem.OuterXml);
                    //not reusable
                    xc = new XmlCanonicalizer(comments, exclusive);
                    //MemoryStream ms = (MemoryStream) xc.Canonicalize(refdElem);
                    ms   = (MemoryStream)xc.Canonicalize(xdRefdElem);
                    baMs = new byte[ms.Length];
                    ms.Read(baMs, 0, baMs.Length);
                    byte [] baHash = shaCsp.ComputeHash(baMs);
                    try
                    {
                        OpenNETCF.Security.Cryptography.Internal.Format.SameBytes(baDigest, baHash);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(refdName + ":" + ex.Message, ex);
                    }
                }
            }
            finally
            {
                //ClearPassword = null;
                SigObj = null;
            }
        }
Example #47
0
 private static System.Security.Cryptography.RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey)
 {
     System.IO.MemoryStream input        = new System.IO.MemoryStream(privkey);
     System.IO.BinaryReader binaryReader = new System.IO.BinaryReader(input);
     System.Security.Cryptography.RSACryptoServiceProvider result;
     try
     {
         ushort num = binaryReader.ReadUInt16();
         if (num == 33072)
         {
             binaryReader.ReadByte();
         }
         else
         {
             if (num != 33328)
             {
                 result = null;
                 return(result);
             }
             binaryReader.ReadInt16();
         }
         num = binaryReader.ReadUInt16();
         if (num != 258)
         {
             result = null;
         }
         else
         {
             byte b = binaryReader.ReadByte();
             if (b != 0)
             {
                 result = null;
             }
             else
             {
                 int    integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] modulus     = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] exponent = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] d = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] p = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] q = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] dP = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] dQ = binaryReader.ReadBytes(integerSize);
                 integerSize = RSAFromPkcs8.GetIntegerSize(binaryReader);
                 byte[] inverseQ = binaryReader.ReadBytes(integerSize);
                 System.Security.Cryptography.RSACryptoServiceProvider rSACryptoServiceProvider = new System.Security.Cryptography.RSACryptoServiceProvider();
                 rSACryptoServiceProvider.ImportParameters(new System.Security.Cryptography.RSAParameters
                 {
                     Modulus  = modulus,
                     Exponent = exponent,
                     D        = d,
                     P        = p,
                     Q        = q,
                     DP       = dP,
                     DQ       = dQ,
                     InverseQ = inverseQ
                 });
                 result = rSACryptoServiceProvider;
             }
         }
     }
     catch (System.Exception)
     {
         result = null;
     }
     finally
     {
         binaryReader.Close();
     }
     return(result);
 }
Example #48
0
        public async Task ValidLocallySignedAccessToken_FromX509Certificate()
        {
#if NETSTANDARD
            const string sPfx = @"
MIIGMQIBAzCCBfcGCSqGSIb3DQEHAaCCBegEggXkMIIF4DCCAt8GCSqGSIb3DQEHBqCCAtAwggLM
AgEAMIICxQYJKoZIhvcNAQcBMBwGCiqGSIb3DQEMAQYwDgQImgNbotR3pnACAggAgIICmMHYqn7R
91hqe5gpwTGxNHaDmrvaLWfBq17xyVIdboPxzSAX4MoNasJplZgCzlN4vMwsY9CG3aY/AV5b4qF3
GRlkR5Ou3xJ84WJUkKkjVcql7hXZ8Zl8hyMKfQgW7SYpmJK/I4qYPqz5wg2ivZ4YbH4KA+VL9eaX
XR5KKdePWt+P9T3oFD1GYAjdPRTL/phSflvv01v2vkmx6In5hS10w2LjxyOJQtiHocOyEe7XAtor
bjsPi9jzMQmW5OESh9c+LDgEHCQQrccc0kG9j+GYJ65b7qORGq9OzBarVgiK+QGrC6aZhGgXZjMD
2K/efd4igVN/QqbpMHB+BDkZKQDRiEc4ezDqZ1VRP8T6VrYP/C+vhvPjZLgIacsxzxZ3f497OkOQ
pnrdpvBC6vPUxzsBpSTMcYlUGObWu+PNuwbOsQabps55c/jb67g/POKmkAqnJMFPXY45tT0/FrHX
hVK3rsSXQBwxy9/qzzPN+nBF7VlgvSoVzrF384t5Slf2ehwYTw3sgJoUudZ4c12kyE+uLdrOVl3Q
BHKDLfy1hRgxMQS/c3uNKkSgXAH3lk9SqMZ9dBzUoY2hZ45YogsP0dQDvzs3AQEdhGW0ZoGEQjC/
QcTTvp7lg/M9gRoBUp/DegGjf2p0N1OlPhj4m63Q2XEm65AvOkA5xxs5RTZKgcU28BJjkgEUpVNt
1rnp0sBsMABmtZ4FXP1YNcKCBdNkIYw67DOO5MRfAGqaDqosT3CL9EOGna61KLQEmtOS33NAx49y
ZtCeh/N91jnC+AMjjhhqwzRtrXJ6g/MLxEmmIFvNYcEipeYHfPynhuVywVVH/tj0SqmnDP4cQd4t
HvFQL5frBq963Wl0ToPVAC+koMvsplAr0dvJLVfNceIwggL5BgkqhkiG9w0BBwGgggLqBIIC5jCC
AuIwggLeBgsqhkiG9w0BDAoBAqCCAqYwggKiMBwGCiqGSIb3DQEMAQMwDgQINLkrmjjeasQCAggA
BIICgIc2PtM3mraGPkm8MqvJOEj64fTocAnAHzGVJ8BhwBXkQI++2d9eAGlSB7pO0JioT7uMBwCL
i3zVQ6bvDw2tbgVD3Pmc/qY0TpIySptODk6X1Y9fI1Bwrvgi+6cx7PIdFUrypnL/djNTtVIkIfFk
TO48YTlT6Gsn+z2Pe6asI0PSDoLgmw2yPauN7Xz1KkAg0KHDT+vMlSLaAYWF8k3+/jFNgPVUpaMM
t/DzuJti0R5+eVnpAPkMTJhncumvMdBYzg2Wx0URHzU4+24hSXE8/xMBN3pVsj11T7Eu5jPazIKR
qB5a5dn/ICVx/JHzz5dFonHilIvyiMfNE7VKTTerisEhCSdUgqq+sIhlPAlLTBCoyUgcGiCi7dKW
GAT47PJ4rvJsGHSUcaNORF71W1GqQQ5iTsJK5rPmGpMUmGwjsemmWmgp00BeMtmqO19B1yRrjDZO
atDYISR3UkmeI0A9VlXAspZ2ngmbuWvW0M8nrzwvDLIfgJ8rsFwexIVecFO58j2YSKBmVEykUvSd
x+PH3gr8IWAd/Ct0VNLF1Jk2ktOXx1pnM9GWUl8rbvTvM5lNevArHpWp+7vY6JlkM+trdaSE66Lr
cvvI+faKAnj4QtkmkbKPF0qLFsDssFv7AI0l7/65PhRZwJ12WpZEOKsqkUyAUbQI16Cva6cuY38y
XZ++x67rU4ldumq0YKOJPdPbAtptwMdCn7lepDaxT8mwv4SIZSd37hAP8UNvmRdRWL4dYx3m8Y+l
4hnClZt+GbKmMgXu/o4ua37kOlCV1T0VqmuRzpOwnct8HBvtVS6TuScExeiEkNBA4KwSIY04ZSm+
Sell3vQywF3jry7v/FMgPhoxJTAjBgkqhkiG9w0BCRUxFgQU+7ZMLd/K3gq6I9wxj3LcCb2tf5Uw
MTAhMAkGBSsOAwIaBQAEFOM/amdwLHU0WBmyCw96Za0+5Z+PBAgvp7LF+Qwu+AICCAA=";

            var x509Cert = new X509Certificate2(Convert.FromBase64String(sPfx));
#else
            const string sPrivateKey = @"
-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALQoMIfUT93VMvb5
4U5dsJLXD1D6z4o/VuVlNUaf5xH01qAv8Egpxe6f5frLB/p1eNyDjNIZ3QitD6aN
9Vfh4ifg6txBuBJtIMfSDvRJITNZ2SjKJREbflZuBk0HINKYQk2H+3TIzUbE/pN4
Cu6Mids5L/oVOnRWIe3bEC+PHR7ZAgMBAAECgYBI1qrwb+2ukeFeK59lcMnQRLVD
l3RLv9ohOy80E7h38RbJgzhR5NnK5ck1AduC7vXjqihIVf6g4F+ghmq4knI94KPQ
2fOyQGVV6jVeRVqMusx7tP9V1H26yABiK6TPklcCsWwADFmexfOxfIgbBGSmlbAd
N2/ad1Xog1xDebrbEQJBAO+2qSIDX1ahfxUyvvcMaix6Mrh/OYKb5aH1Y/7MfAav
lpbQavQHNvak2147aPNxy0ZvWdJ2HVA7hUMkgysYWSUCQQDAZalkZMSrve+Onh55
U+w5xjLklhh8PhYxx8plT8ae9VG75dGvWSz/W81B3ILg2lrNU6o08NKBJdZsJYmc
BeKlAkBtJh3zF9gEaTqlW1rqwKNjpyyLJ5r3JqczzLmAXnmmzbLi7vmULejP+5bL
XH/YQZtOcgtTMmb8jm2Kegijyc1lAkANGt+e5v4+dIGMxVhuCzlb9hQhXdftHo2E
dodivzxYN32Jvu25c+mMu0QP6GVBy53Dvp8pW/36rgkc9LGa3wvBAkEA7dGAl95T
UeNFVfuzkYNtQppcSgrx1oTcpTHoNgcvk8AgBf4yDdJJyo0IUONmgJCVffc1aTWn
nf/8cW9YC+0icQ==
-----END PRIVATE KEY-----";
            const string sCert       = @"
MIICNDCCAZ2gAwIBAgIJAKl3qU1+NsuuMA0GCSqGSIb3DQEBCwUAMDMxCzAJBgNV
BAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMQ8wDQYDVQQKDAZHb29nbGUwHhcN
MTYwODEwMTQwOTQ2WhcNNDMxMjI3MTQwOTQ2WjAzMQswCQYDVQQGEwJHQjETMBEG
A1UECAwKU29tZS1TdGF0ZTEPMA0GA1UECgwGR29vZ2xlMIGfMA0GCSqGSIb3DQEB
AQUAA4GNADCBiQKBgQC0KDCH1E/d1TL2+eFOXbCS1w9Q+s+KP1blZTVGn+cR9Nag
L/BIKcXun+X6ywf6dXjcg4zSGd0IrQ+mjfVX4eIn4OrcQbgSbSDH0g70SSEzWdko
yiURG35WbgZNByDSmEJNh/t0yM1GxP6TeArujInbOS/6FTp0ViHt2xAvjx0e2QID
AQABo1AwTjAdBgNVHQ4EFgQUMqzJi099PA8ML5CV1OSiHgiTGoUwHwYDVR0jBBgw
FoAUMqzJi099PA8ML5CV1OSiHgiTGoUwDAYDVR0TBAUwAwEB/zANBgkqhkiG9w0B
AQsFAAOBgQBQ9cMInb2rEcg8TTYq8MjDEegHWLUI9Dq/IvP/FHyKDczza4eX8m+G
3buutN74pX2/GHRgqvqEvvUUuAQUnZ36k6KjTNxfzNLiSXDPNeYmy6PWsUZy4Rye
/Van/ePiXdipTKMiUyl7V6dTjkE5p/e372wNVXUpcxOMmYdWmzSMvg==";

            var           x509Cert      = new X509Certificate2(Convert.FromBase64String(sCert));
            RSAParameters rsaParameters = Pkcs8.DecodeRsaParameters(sPrivateKey);
            var           privateKey    = new System.Security.Cryptography.RSACryptoServiceProvider();
            privateKey.ImportParameters(rsaParameters);
            x509Cert.PrivateKey = privateKey;
#endif
            Assert.That(x509Cert.HasPrivateKey);

            var initializer = new ServiceAccountCredential.Initializer("some-id")
            {
                Clock = new MockClock {
                    UtcNow = new DateTime(2016, 1, 1, 0, 0, 0, DateTimeKind.Utc)
                }
            };
            var cred = new ServiceAccountCredential(initializer.FromCertificate(x509Cert));

            Assert.That(cred.Scopes?.Any(), Is.False); // HasScopes must be false for the type of access token we want to test.

            string accessToken = await cred.GetAccessTokenForRequestAsync("http://authurl/");

            string expectedToken =
                "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzb21lLWlkIiwic3ViIjoi" +
                "c29tZS1pZCIsImF1ZCI6Imh0dHA6Ly9hdXRodXJsLyIsImV4cCI6MTQ1MTYxMDAwMCwia" +
                "WF0IjoxNDUxNjA2NDAwfQ.GfpDHgrFi4ZlGC5LuJEarLU4_eTrT5PVa-S40YtkdB2E1f3" +
                "4naYG2ItcfBEFg7Gbdkr1cIAyipuhEd2yLfPmWGwhOwVcBRNyK_J5w8RodS44mxNJwau0" +
                "jKy4x1K20ybLqcnNgzE0wag6fi5GHwdNIB0URdHDTiC88CRYdl1CIdk";
            Assert.That(accessToken, Is.EqualTo(expectedToken));
        }
Example #49
0
            /// <summary>
            /// RSAPkcs8Util
            /// </summary>
            /// <param name="dataEncoding"></param>
            /// <param name="publicKey"></param>
            /// <param name="privateKey"></param>
            /// <param name="keySize"></param>
            public RsaPkcs8Util(Encoding dataEncoding, string publicKey, string privateKey = null, int keySize = 2048)
            {
                if (string.IsNullOrEmpty(privateKey) && string.IsNullOrEmpty(publicKey))
                {
                    throw new Exception("Public and private keys must not be empty at the same time");
                }

                if (!string.IsNullOrEmpty(privateKey))
                {
#if NET451 || NET452
                    PrivateRsa = new MsRSA {
                        KeySize = keySize
                    };
#else
                    PrivateRsa         = MsRSA.Create();
                    PrivateRsa.KeySize = keySize;
#endif
                    PrivateRsa.TouchFromPrivateKeyInPkcs8(privateKey, out var priRsap);

#if NET451 || NET452
                    PrivateRsaKeyParameter = GetPrivateKeyParameter(privateKey);
#endif

                    if (string.IsNullOrEmpty(publicKey))
                    {
#if NET451 || NET452
                        PublicRsa = new MsRSA {
                            KeySize = keySize
                        };
#else
                        PublicRsa         = MsRSA.Create();
                        PublicRsa.KeySize = keySize;
#endif
                        var pubRsap = new RSAParameters
                        {
                            Modulus  = priRsap.Modulus,
                            Exponent = priRsap.Exponent
                        };
                        PublicRsa.ImportParameters(pubRsap);

#if NET451 || NET452
                        PublicRsaKeyParameter = GetPublicKeyParameter(publicKey);
#endif
                    }
                }

                if (!string.IsNullOrEmpty(publicKey))
                {
#if NET451 || NET452
                    PublicRsa = new MsRSA {
                        KeySize = keySize
                    };
#else
                    PublicRsa         = MsRSA.Create();
                    PublicRsa.KeySize = keySize;
#endif
                    PublicRsa.TouchFromPublicKeyInPkcs8(publicKey, out _);

#if NET451 || NET452
                    PublicRsaKeyParameter = GetPublicKeyParameter(publicKey);
#endif
                }

                DataEncoding = dataEncoding.SafeEncodingValue();
            }