Exemplo n.º 1
0
 /// <summary>
 /// Encrypt using Given Public Key
 /// </summary>
 /// <param name="StringToEncrypt">w to Encrypt</param>
 /// <param name="PublicKey"></param>
 /// <returns></returns>
 public static string Encrypt(string StrToEncrypt, string PublicKey, string EncodingMode)
 {
     try
     {
         /// First we get the RSA Public Key
         string RSAPublicKey = PublicKey;
         /// rsa object
         Chilkat.Rsa rsa = new Chilkat.Rsa();
         /// bool for success
         bool success;
         /// unlock component
         success = rsa.UnlockComponent("VIENTORSA_TbpfVVr01Or6");
         /// rsa encoding mode as base64, hex
         rsa.EncodingMode = EncodingMode;
         /// import the public key to the API
         rsa.ImportPublicKey(RSAPublicKey);
         /// decrypted string
         string encryptedStr;
         ///we now decript the string
         encryptedStr = rsa.EncryptStringENC(StrToEncrypt, false);
         /// return the string
         return encryptedStr;
     }
     catch
     {
         return null;
     }
     finally
     {
         GC.Collect();
     }
 }
Exemplo n.º 2
0
        static void testencrypt()
        {
            string Token = String.Format("{0:yyyy-MM-dd HH:mm:ss}", new DateTime(2010, 02, 02, 21, 15, 0));

            //ENCRYPT
            Chilkat.Cert cert3   = new Chilkat.Cert();
            bool         success = cert3.LoadFromBase64(mycert);

            Chilkat.PublicKey pubKey3 = null;
            pubKey3 = cert3.ExportPublicKey();
            Chilkat.Rsa rsa3 = new Chilkat.Rsa();
            success           = rsa3.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");
            rsa3.EncodingMode = "base64";
            rsa3.Charset      = "ANSI";
            rsa3.LittleEndian = true;
            rsa3.OaepPadding  = false;
            rsa3.ImportPublicKey(pubKey3.GetXml());
            bool usePrivateKey = false;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] TokenArr = encoding.GetBytes(Token);
            //array('B', [50, 48, 49, 48, 45, 48, 50, 45, 48, 50, 32, 50, 49, 58, 49, 53, 58, 48, 48])
            //byte[] encryptedArr = rsa3.EncryptBytes(TokenArr, usePrivateKey);
            string encryptedStr = rsa3.EncryptBytesENC(TokenArr, usePrivateKey);
        }
Exemplo n.º 3
0
        public string GetSymmetricKeyForUser(string userReference)
        {
            var userKeys = GetUserKeyPair(userReference);

            var rsaDecryptor = new Chilkat.Rsa {
                EncodingMode = EncodingMode
            };

            rsaDecryptor.ImportPublicKey(userKeys.PublicKey);
            var symmetricKey = rsaDecryptor.DecryptStringENC(userKeys.EncryptedSymetricKey, false);

            return(symmetricKey);
        }
Exemplo n.º 4
0
        public byte[] EncryptWithPublic(CryptoRequest cryptoRequest)
        {
            var bytes64   = cryptoRequest.Data64;
            var publicKey = cryptoRequest.Password;

            byte[] bytes = Convert.FromBase64String(bytes64);

            Chilkat.Rsa rsaEncryptor = new Chilkat.Rsa
            {
                EncodingMode = "hex"
            };

            rsaEncryptor.ImportPublicKey(publicKey);

            return(rsaEncryptor.EncryptBytes(bytes, usePrivateKey: false));
        }
Exemplo n.º 5
0
        public void EncryptApplicationKeyFromCryptoServiceCert()
        {
            RegisterChilKat();
            X509Certificate2 theCert = null;

            var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            store.Open(OpenFlags.ReadOnly);

            foreach (var certificate in store.Certificates)
            {
                //TODO's
                Console.WriteLine(certificate.FriendlyName);

                if (certificate.FriendlyName == "CryptoServiceCert")
                {
                    theCert = certificate;
                }
            }

            var privateKey = theCert?.PrivateKey?.ToXmlString(true);
            var publicKey  = theCert?.PrivateKey?.ToXmlString(true);

            var sampleText = "+oPDU29Bv2hfUZ8fZozMGAVYUZjp1wdwDs42JY213tA=";

            var rsaEncryptor = new Chilkat.Rsa {
                EncodingMode = "hex"
            };

            rsaEncryptor.ImportPublicKey(publicKey);
            var encryptedText = rsaEncryptor.EncryptStringENC(sampleText, false);

            Console.WriteLine($"Encrypted Value: [{encryptedText}]");

            var rsaDecryptor = new Chilkat.Rsa {
                EncodingMode = "hex"
            };

            rsaDecryptor.ImportPrivateKey(privateKey);

            var decryptedText = rsaDecryptor.DecryptStringENC(encryptedText, true);
        }
Exemplo n.º 6
0
        public VerificationResult <string> VerifySignature(DigitalSignature <string> signature)
        {
            var verificationResults = new VerificationResult <string>();
            var hashManager         = new HashManager();

            var envelope = DecryptSignedContent <string>(signature.SignedContent, signature.SignatoryReference);

            if (envelope == null)
            {
                verificationResults.SignatoryMatchedToSignature = false;
                return(verificationResults);
            }

            var hashCurrentBody = hashManager.HashContent(envelope.Body);
            var publicKey       = KeyStoreAdapter.GetPublicKeyForUser(signature.SignatoryReference);

            // Decrypt hash with public key to ensure there is no tampering and content is still the same
            var rsaDecryptor = new Chilkat.Rsa {
                EncodingMode = EncodingMode
            };

            rsaDecryptor.ImportPublicKey(publicKey);
            var decryptedoriginalHash = rsaDecryptor.DecryptStringENC(envelope.Header.EncryptedBodyHashSignature, false);

            var signitureMatch = hashCurrentBody == decryptedoriginalHash;

            verificationResults.IpAddress                       = envelope.Body?.IpAddress;
            verificationResults.SignatoryEmailAddress           = envelope.Body?.EmailAddress;
            verificationResults.SignatoryMatchedToSignature     = true;
            verificationResults.SignedContentMatchesToSignature = signitureMatch;

            verificationResults.ExpectedContent = signature.OriginalContent;
            verificationResults.SignedContent   = envelope?.Body?.Content;

            return(verificationResults);
        }
Exemplo n.º 7
0
        static string HttpGet(string url)
        {
            bool           success = false;
            HttpWebRequest req     = WebRequest.Create(url) as HttpWebRequest;

            string Token = String.Format("{0:yyyy-MM-dd HH:mm:ss}", new DateTime(2010, 02, 02, 21, 15, 0));

            //SIGN
            Chilkat.PrivateKey privkey1 = new Chilkat.PrivateKey();
            privkey1.LoadPem(mykey);
            Chilkat.Rsa rsa1 = new Chilkat.Rsa();
            success           = rsa1.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");
            success           = rsa1.ImportPrivateKey(privkey1.GetXml());
            rsa1.EncodingMode = "base64";
            rsa1.Charset      = "ANSI";
            rsa1.LittleEndian = false;
            rsa1.OaepPadding  = false;
            string hexSig = rsa1.SignStringENC(Token, "sha-1");


            //VERIFY
            Chilkat.Cert cert2 = new Chilkat.Cert();
            success = cert2.LoadFromBase64(mycert);
            Chilkat.PublicKey pubKey2 = null;
            pubKey2 = cert2.ExportPublicKey();
            Chilkat.Rsa rsa2 = new Chilkat.Rsa();
            success           = rsa2.ImportPublicKey(pubKey2.GetXml());
            rsa2.EncodingMode = "base64";
            rsa2.Charset      = "ANSI";
            rsa2.LittleEndian = false;
            rsa2.OaepPadding  = false;
            success           = rsa2.VerifyStringENC(Token, "sha-1", hexSig);

            req.Headers.Add("Token", Token);
            req.Headers.Add("Signature", hexSig);

            //ENCRYPT
            Chilkat.Cert cert3 = new Chilkat.Cert();
            success = cert3.LoadFromBase64(mycert);
            Chilkat.PublicKey pubKey3 = null;
            pubKey3 = cert3.ExportPublicKey();
            Chilkat.Rsa rsa3 = new Chilkat.Rsa();
            success           = rsa3.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");
            rsa3.EncodingMode = "base64";
            rsa3.Charset      = "ANSI";
            rsa3.LittleEndian = true;
            rsa3.OaepPadding  = false;
            rsa3.ImportPublicKey(pubKey3.GetXml());
            bool usePrivateKey = false;

            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
            byte[] TokenArr = encoding.GetBytes(Token);
            //byte[] encryptedArr = rsa3.EncryptBytes(TokenArr, usePrivateKey);
            string encryptedstr = rsa3.EncryptBytesENC(TokenArr, usePrivateKey);

            //DECRYPT
            Chilkat.Rsa rsa4 = new Chilkat.Rsa();
            rsa4.EncodingMode = "base64";
            rsa4.Charset      = "ANSI";
            rsa4.LittleEndian = true;
            rsa4.OaepPadding  = false;
            rsa4.ImportPrivateKey(privkey1.GetXml());
            usePrivateKey = true;
            //encryptedStr = "XJ65xTR/xvD2N9xBKyKPqPijqTAyJuVtOlbaFUIboJaEPHH9pv+Lhrd5o6MSwKF6TeXs6hVsKnj8jVeYFYoEDgJS95GqaaUomWBhEZYchOp/6dn3ZxCeQoljAWLt6m4C829R9b5JYatYar9YV0d+QV+jVWE4U0rlNrkTqtA02Qw4ztN4/oehgCISrBnc81N1MYNwG9vrTHSVM6tSUWjWxMRubpOBvqKqOxyA9fpJNHgUyzio2X1cp12K++1GEUWNWyYVhTiBr/QM3mUN67mHcn0vvWZvmPhYlIaVn9DqIvVdMbHRbLwrCczFgY4PdHrhcH9yDTlkkAbKUatgDQiI4w==";
            //encryptedStr = "6KQbxh+x5SGIzD89zEwj+/IVVCBocemCXWl1mr+mk9wxRMydCfmMSUHDOafnqiJ6GAJapKbLTHOc9d1OyWTwsp5BQBT5VM20hb9r+AkDrHwkgL06ifizP0gTEO17cyO95jwlRXOfkQKb3cERLBEtOAnRep4bKMSsPLyxRRBX5VT4d19yxRor2V9js0CEFONinxl7qRxjckwvQk53+qpxeQ8jOx+pmrQukX7nWkMajWi+ZFndyfLL3LfRBYZKN2R0vdrnSMKdkxUEUUJybsv4QCMWshNpQznPSantq2dKNe07eB5mX4fRufy4mY4qjqBlf8+XFKdD+J37C6r3THL6pw==";
            //string decryptedStr = rsa4.DecryptStringENC(encryptedStr, usePrivateKey);



            Chilkat.Crypt2 crypt = new Chilkat.Crypt2();
            success              = crypt.UnlockComponent("HAFSJOCrypt_0xo09cJWVQAw");
            crypt.EncodingMode   = "base64";
            crypt.CryptAlgorithm = "none";
            req.Headers.Add("authorization", "Basic " + crypt.EncryptStringENC("Mogens:Hafsjold"));

            string result = null;

            using (HttpWebResponse resp = req.GetResponse() as HttpWebResponse)
            {
                StreamReader reader = new StreamReader(resp.GetResponseStream());
                result = reader.ReadToEnd();
            }
            return(result);
        }
Exemplo n.º 8
0
        public static void performRSA(string text)
        {
            Chilkat.Rsa rsa = new Chilkat.Rsa();

            bool success = rsa.UnlockComponent("Anything for 30-day trial");

            if (success != true)
            {
                Console.WriteLine("RSA component unlock failed");
                return;
            }

//  This example also generates the public and private
//  keys to be used in the RSA encryption.
//  Normally, you would generate a key pair once,
//  and distribute the public key to your partner.
//  Anything encrypted with the public key can be
//  decrypted with the private key.  The reverse is
//  also true: anything encrypted using the private
//  key can be decrypted using the public key.

//  Generate a 1024-bit key.  Chilkat RSA supports
//  key sizes ranging from 512 bits to 4096 bits.
            success = rsa.GenerateKey(1024);
            if (success != true)
            {
                Console.WriteLine(rsa.LastErrorText);
                return;
            }

//  Keys are exported in XML format:
            string publicKey  = rsa.ExportPublicKey();
            string privateKey = rsa.ExportPrivateKey();

            string plainText = "Encrypting and decrypting should be easy!";

            plainText = text;
//  Start with a new RSA object to demonstrate that all we
//  need are the keys previously exported:
            Chilkat.Rsa rsaEncryptor = new Chilkat.Rsa();

//  Encrypted output is always binary.  In this case, we want
//  to encode the encrypted bytes in a printable string.
//  Our choices are "hex", "base64", "url", "quoted-printable".
            rsaEncryptor.EncodingMode = "hex";

//  We'll encrypt with the public key and decrypt with the private
//  key.  It's also possible to do the reverse.
            success = rsaEncryptor.ImportPublicKey(publicKey);

            bool   usePrivateKey = false;
            string encryptedStr  = rsaEncryptor.EncryptStringENC(plainText, usePrivateKey);

//Console.WriteLine(encryptedStr);

//  Now decrypt:
            Chilkat.Rsa rsaDecryptor = new Chilkat.Rsa();

            rsaDecryptor.EncodingMode = "hex";
            success = rsaDecryptor.ImportPrivateKey(privateKey);

            usePrivateKey = true;
            string decryptedStr = rsaDecryptor.DecryptStringENC(encryptedStr, usePrivateKey);

//Console.WriteLine(decryptedStr);
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseCors(builder => builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials()
                        ); //for CORS

            app.Use(async(context, next) => {
                //var token = context.Request.Headers["Authorization"];
                // var token = context.Request.Cookies["UserLoginAPItoken"];

                //switch(context.Request.Path.ToString())
                Console.WriteLine(context.Request.Path.ToString());
                //switch(context.Request.Path.ToString())
                if (context.Request.Path.Value.StartsWith("/auth") || context.Request.Path.Value.StartsWith("/gameplay") || context.Request.Path.Value.StartsWith("/favicon") ||
                    context.Request.Path.Value.StartsWith("/questiongenerator") || context.Request.Path.Value.StartsWith("/quizmaster"))
                {
                    Console.WriteLine("Calling next middleware");
                    await next();
                }
                else
                {
                    Microsoft.AspNetCore.Http.IRequestCookieCollection cookies = context.Request.Cookies;
                    var token           = cookies["UserLoginAPItoken"];
                    Chilkat.Global glob = new Chilkat.Global();
                    glob.UnlockBundle("Anything for 30-day trial");

                    using (var client = new ConsulClient())
                    {
                        Console.WriteLine("---------entered consul----------------");
                        client.Config.Address = new Uri("http://consul:8500");
                        var getpair2          = client.KV.Get("secretkey");
                        Console.WriteLine(getpair2);
                        Console.WriteLine("------got the getpair2------");
                        Console.WriteLine("-------key-----" + getpair2.Result.Response.Key);
                        Console.WriteLine("------Value-----" + getpair2.Result.Response.Value);
                        //var getresult = getpair2.Result.Response.Value
                        // if(getpair2.Result.Response.Value != null)
                        // {
                        Console.WriteLine("---------Entered the function");
                        string secret = System.Text.Encoding.UTF8.GetString(getpair2.Result.Response.Value);
                        Console.WriteLine("------------Secret Key------------" + secret);
                        Chilkat.Rsa rsaExportedPublicKey = new Chilkat.Rsa();
                        rsaExportedPublicKey.ImportPublicKey(secret);
                        var publickey = rsaExportedPublicKey.ExportPublicKeyObj();
                        Console.WriteLine("--------publickey--------" + publickey);
                        Console.WriteLine("-----token-----" + token);
                        var jwt = new Chilkat.Jwt();
                        if (jwt.VerifyJwtPk(token, publickey))
                        {
                            Console.WriteLine("--inside verify");
                            await next();
                        }
                        else
                        {
                            context.Response.StatusCode = 403;
                            await context.Response.WriteAsync("UnAuthorized");
                        }
                    }
                }
            });

            app.UseWebSockets();
            app.UseOcelot().Wait();
        }