Ejemplo n.º 1
0
        public static string SignDataWithPrivateKey(string strData,
                                                    string keyPrivate,
                                                    string hashAlgorithm,
                                                    out string error)
        {
            try
            {
                Chilkat.Rsa rsa = new Chilkat.Rsa();

                rsa.ImportPrivateKey(keyPrivate);

                // sign a string, and receive the signature in a hex-encoded string.
                // Therefore, set the encoding mode to "hex":
                rsa.EncodingMode = "hex";

                // It is important to match the byte-ordering.
                // The LittleEndian property may be set to true for little-endian byte ordering,
                // or false  for big-endian byte ordering.
                // Microsoft apps typically use little-endian, while
                // OpenSSL and other services (such as Amazon CloudFront) use big-endian.
                rsa.LittleEndian = false;

                // Sign the string using the  md5 hash algorithm.
                // Other valid choices are "md2", "sha256", "sha384",
                // "sha512", and "sha-1".
                string hexSignature = rsa.SignStringENC(strData, hashAlgorithm);
                error = string.Empty;
                return(hexSignature);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(null);
            }
        }
Ejemplo n.º 2
0
        static void testdecrypt()
        {
            //byte[] encryptedArr = {145, 110, 51, 179, 147, 38, 228, 145, 55, 179, 143, 45, 179, 239, 28, 251, 127, 202, 47, 73, 49, 31, 36, 232, 81, 219, 2, 180, 16, 104, 203, 148, 207, 36, 110, 184, 225, 133, 190, 185, 22, 75, 49, 69, 129, 101, 161, 215, 102, 66, 218, 127, 193, 201, 222, 181, 187, 251, 221, 205, 103, 188, 5, 77, 94, 236, 43, 121, 182, 233, 109, 123, 64, 93, 61, 61, 204, 157, 23, 17, 220, 187, 150, 187, 29, 230, 91, 89, 241, 27, 34, 18, 21, 195, 220, 231, 237, 47, 123, 247, 128, 107, 169, 115, 84, 103, 129, 126, 99, 231, 2, 23, 152, 183, 136, 70, 64, 116, 125, 198, 240, 128, 129, 133, 5, 144, 179, 255, 10, 14, 148, 216, 164, 78, 253, 190, 231, 153, 157, 64, 212, 78, 212, 191, 230, 120, 58, 223, 147, 241, 222, 191, 22, 99, 80, 126, 212, 172, 14, 43, 135, 43, 117, 47, 172, 161, 38, 67, 125, 205, 186, 91, 35, 89, 110, 243, 184, 200, 158, 220, 161, 222, 172, 53, 211, 90, 55, 126, 190, 183, 71, 101, 215, 218, 90, 68, 122, 226, 237, 119, 139, 176, 51, 129, 7, 71, 154, 196, 52, 16, 136, 104, 4, 108, 136, 112, 25, 45, 88, 232, 94, 159, 199, 221, 152, 88, 156, 73, 183, 158, 241, 10, 102, 50, 166, 183, 86, 252, 102, 4, 190, 144, 149, 136, 255, 115, 163, 177, 88, 67, 88, 85, 247, 0, 30, 159};

            string encryptedStr = "";

            encryptedStr = "YrOiK4Efq2oM4Ny0YW7VFnOtkWHpcFg1zHHfxpdEX1k/wbjbMHyBYn6Uo1qB6fcRNmokO1L48fQGfpeyErgWSt/D1pBlffV+QkGNLtApXIShPdOj8uqElP0T8skNTZCUNqsaB5MPwFsUDiuynimqikM6tBNdLss+z81LbxARUlao/yN112GoxQQ4wpnaDk/eOA51J+5aZb2jMssHwAFx3M3K8AJmUv4qBN8lOAnahd3QnDgaxk7gNydjKyVi1eRGHYxwQVNwMsV1we7EFDMBICG97i4GmWrP2BkrXs8J09osP2O++TIVZrxYpEGwwrRmtno1bBCfySWLNuxd33jwcg==";
            encryptedStr = "SnGp1BBb0fU7poFpM5Z0oD0YtfYZizU97GxUF9pn58yGEhpTdJ2vWy/NrhYMPflf4yym77zUyNVhDaOZ+1Q2H4imkiXa5q9DsBRN+dl5dVvosEse3OSyOTEbxn4AcrreWGhKTJ+/3mEhRotUE/rUuWskXKzSA+WQ0nSGUxSG/Rw0yaCeWsa1MU3UM0ugxxxd2gExY+K39+4nXUzNMv+H4XniTvmmUI7k8TEGAsZujwDsU9Oh+MbMtH8nlTu+yvfS++/dDTX9bFmpbkkH7FgbVvKcoICXsI5UfTATfRL4LkzdipO8VJNiPKT8TkgZyIJC/m1daLGAmIs+fM98rWm9yg==";
            //DECRYPT
            Chilkat.PrivateKey privkey1 = new Chilkat.PrivateKey();
            bool success = privkey1.LoadPem(mykey);

            Chilkat.Rsa rsa4 = new Chilkat.Rsa();
            success = rsa4.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");

            rsa4.EncodingMode = "base64";
            rsa4.Charset      = "ANSI";
            rsa4.LittleEndian = true;
            rsa4.OaepPadding  = false;
            success           = rsa4.ImportPrivateKey(privkey1.GetXml());
            bool usePrivateKey = true;

            //byte[] decryptedArr = rsa4.DecryptBytes(encryptedArr, usePrivateKey);
            string decryptedStr = rsa4.DecryptStringENC(encryptedStr, usePrivateKey);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 4
0
        public static bool VerifyData(string data,
                                      string hashAlgorithm,
                                      string hexSignature,
                                      out string error)
        {
            try
            {
                Chilkat.Rsa rsa = new Chilkat.Rsa();

                var success = rsa.VerifyStringENC(data, hashAlgorithm, hexSignature);
                if (success)
                {
                    error = string.Empty;
                    return(true);
                }
                else
                {
                    error = rsa.LastErrorText;
                    return(false);
                }
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(false);
            }
        }
Ejemplo n.º 5
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();
     }
 }
Ejemplo n.º 6
0
        public static Tuple <string, string> GenerateRsaKeyPairStandalone(out string error)
        {
            Tuple <string, string> keyPair;

            try
            {
                Chilkat.Rsa rsa = new Chilkat.Rsa();

                // Generate a 1024-bit RSA key pair.
                if (!rsa.GenerateKey(1024))
                {
                    throw new Exception(rsa.LastErrorText);
                }

                keyPair = new Tuple <string, string>(item1: rsa.ExportPrivateKey(), item2: rsa.ExportPublicKey());

                error = null;
                return(keyPair);
            }
            catch (Exception ex)
            {
                error = ex.Message;
                return(new Tuple <string, string>(null, null));
            }
        }
Ejemplo n.º 7
0
        private UserKeys GenerateNewKeyPair()
        {
            var rsa = new Chilkat.Rsa();

            rsa.GenerateKey(RsaKeySize);

            var publicKey  = rsa.ExportPublicKey();
            var privateKey = rsa.ExportPrivateKey();

            var symetricKey = EncryptionManager.GenerateSymmetricKey();

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

            rsaEncryptor.ImportPrivateKey(privateKey);

            // Encrypted with private so that public key can get access to symmetric key
            var encryptedSymetricKey = rsaEncryptor.EncryptStringENC(symetricKey, true);

            // Encrypted with application key so that the application can manage access to private keys
            var encryptedPrivateKey = EncryptionManager.Encrypt(privateKey, string.Empty);

            return(UserKeys.Create(encryptedPrivateKey, publicKey, encryptedSymetricKey));
        }
Ejemplo n.º 8
0
        public SigningOutput SignContent(string serializedRequest)
        {
            var hashManager = new HashManager();
            var privateKey  = KeyStoreAdapter.GetPrivateKeyForUser(SignatoryReference);

            var envolope = SigningEnvelope <string> .Create(serializedRequest, SignatoryReference, SignatoryEmail, SignatoryIpAddress);

            var hashSigningContent = hashManager.HashContent(envolope.Body);

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

            rsaEncryptor.ImportPrivateKey(privateKey);

            var encryptedSignContentHash = rsaEncryptor.EncryptStringENC(hashSigningContent, true);

            envolope.AddEncryptedHashForBody(encryptedSignContentHash);

            var symmetricKey = KeyStoreAdapter.GetSymmetricKeyForUser(SignatoryReference);

            var serializedSignedContent = JsonConvert.SerializeObject(envolope);
            var encryptedSignedString   = Encrypt(serializedSignedContent, symmetricKey);

            return(SigningOutput.Create(encryptedSignedString, SignatoryReference));
        }
Ejemplo n.º 9
0
        public void SignRequest(ref HttpWebRequest Request)
        {
            TimeSpan diff      = DateTime.UtcNow - (new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc));
            uint     timestamp = (uint)Math.Floor(diff.TotalSeconds); // Seconds since 1970
            string   data      = timestamp.ToString();

            Chilkat.PrivateKey privkey1 = new Chilkat.PrivateKey();
            privkey1.LoadPem(mykey);
            Chilkat.Rsa rsa1    = new Chilkat.Rsa();
            bool        success = rsa1.UnlockComponent("HAFSJORSA_K36nxU3n1Yui");

            success           = rsa1.ImportPrivateKey(privkey1.GetXml());
            rsa1.EncodingMode = "base64";
            rsa1.Charset      = "ANSI";
            rsa1.LittleEndian = false;
            rsa1.OaepPadding  = false;

            string s_mysecre = data + mysecret;

            char[] c_mysecre = s_mysecre.ToCharArray();
            byte[] b_mysecre = System.Text.Encoding.GetEncoding("windows-1252").GetBytes(c_mysecre);
            string hexSig    = rsa1.SignBytesENC(b_mysecre, "sha-1");

            Request.Headers.Add("timestamp", data);
            Request.Headers.Add("signed", hexSig);
        }
Ejemplo n.º 10
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="StrToDecrypt"></param>
 /// <param name="EncodingMode"></param>
 /// <returns></returns>
 public override string Decrypt(string StrToDecrypt, string EncodingMode, string RSAPrivateKey)
 {
     try
     {
         //  Now decrypt:
         Chilkat.Rsa rsaDecryptor = new Chilkat.Rsa();
         /// bool for success
         bool success;
         /// unlock component
         success = rsaDecryptor.UnlockComponent("VIENTORSA_TbpfVVr01Or6");
         /// we encode in 64 base bits
         rsaDecryptor.EncodingMode = EncodingMode;
         ///rsa import private
         rsaDecryptor.ImportPrivateKey(RSAPrivateKey);
         /// decrypted string
         string decryptedStr;
         ///we now decript the string
         decryptedStr = rsaDecryptor.DecryptStringENC(StrToDecrypt, true);
         /// return the string
         return decryptedStr;
     }
     catch
     {
         return null;
     }
     finally
     {
         GC.Collect();
     }
 }
        private string DecryptWithApplicationCertPrivateKey(string encryptedkey)
        {
            var rsaDecryptor = new Chilkat.Rsa {
                EncodingMode = "hex"
            };

            rsaDecryptor.ImportPrivateKey(CertificatePrivateKey);

            var applicationKey = rsaDecryptor.DecryptStringENC(encryptedkey, true);

            return(applicationKey);
        }
Ejemplo n.º 12
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);
        }
Ejemplo n.º 13
0
        public static String CreateSignature(String fileContent)
        {
            signatureRsa = new Chilkat.Rsa();

            signatureRsa.UnlockComponent("30-day trial");

            signatureRsa.GenerateKey(1024);


            signatureRsa.EncodingMode = "hex";
            signatureRsa.LittleEndian = false;

            return(signatureRsa.SignStringENC(fileContent, "sha-256"));
        }
Ejemplo n.º 14
0
        static void RSAChilat(string Data)
        {
            Chilkat.PrivateKey l_key = new Chilkat.PrivateKey();
            bool   l_res             = l_key.LoadPemFile(@"D:\Work\Other\ForexStars\_incomming\project1074.ppk");
            string l_pr_key_xml      = l_key.GetXml();


            Chilkat.Rsa rsa = new Chilkat.Rsa();
            rsa.ImportPrivateKey(l_pr_key_xml);
            //rsa.UnlockComponent("30-day trial");
            rsa.UnlockComponent("RSA$TEAM$BEAN_495C86FD5RkU");
            rsa.EncodingMode = "hex";
            rsa.LittleEndian = false;
            string l_sign = rsa.SignStringENC(Data, "sha-1");
        }
Ejemplo n.º 15
0
        public PublicPrivateKey GetKeys()
        {
            Chilkat.Rsa rsa = new Chilkat.Rsa();
            rsa.GenerateKey(1024);

            string publicKey  = rsa.ExportPublicKey();
            string privateKey = rsa.ExportPrivateKey();

            var data = new PublicPrivateKey()
            {
                PrivateKey = privateKey,
                PublicKey  = publicKey
            };

            return(data);
        }
Ejemplo n.º 16
0
        public byte[] DecryptWithPrivate(CryptoRequest cryptoRequest)
        {
            var bytes64    = cryptoRequest.Data64;
            var privateKey = cryptoRequest.Password;

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

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

            rsaEncryptor.ImportPrivateKey(privateKey);

            return(rsaEncryptor.DecryptBytes(bytes, usePrivateKey: true));
        }
Ejemplo n.º 17
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);
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Decrypt using a Given Private Key
 /// </summary>
 /// <param name="StringToDecrypt">w to Decrypt</param>
 /// <param name="PrivateKey"></param>
 /// <param name="EncodingMode">base64, hex</param>
 /// <returns></returns>
 public static string Decrypt(string StrToDecrypt, string PrivateKey, string EncodingMode)
 {
     try
     {
         /// First we get the RSA Public Key
         string RSAPrivateKey = PrivateKey;
         /// rsa object
         Chilkat.Rsa rsa = new Chilkat.Rsa();
         /// bool for success
         bool success;
         /// unlock component
         success = rsa.UnlockComponent("VIENTORSA_TbpfVVr01Or6");
         /// private key
         string privateKey;
         ///we now export the private key
         privateKey = rsa.ExportPrivateKey();
         //  Now decrypt:
         Chilkat.Rsa rsaDecryptor = new Chilkat.Rsa();
         /// we encode in 64 base bits
         rsaDecryptor.EncodingMode = EncodingMode;
         ///rsa import private
         rsaDecryptor.ImportPrivateKey(RSAPrivateKey);
         /// decrypted string
         string decryptedStr;
         ///we now decript the string
         decryptedStr = rsaDecryptor.DecryptStringENC(StrToDecrypt, true);
         /// return the string
         return decryptedStr;
     }
     catch
     {
         return null;
     }
     finally
     {
         GC.Collect();
     }
 }
Ejemplo n.º 19
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);
        }
Ejemplo n.º 20
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();
        }
Ejemplo n.º 21
0
 /// <summary>
 /// Method to Generate new keys according Possition
 /// { "keys" :
 /// { "0" : private key,
 ///   "1" : public key }
 /// }
 /// </summary>
 /// <returns></returns>
 public static List<string> GenerateNewRSAKeyPair()
 {
     /// rsa object from library
     Chilkat.Rsa rsa = new Chilkat.Rsa();
     /// unlock component
     bool success = rsa.UnlockComponent("VIENTORSA_TbpfVVr01Or6");
     /// we generate the amount key from amount of bits
     success = rsa.GenerateKey(2048);
     /// this is the public key
     string publicKey = rsa.ExportPublicKey();
     /// this is the private key
     string privateKey = rsa.ExportPrivateKey();
     /// we return the new elements
     return new List<string>() { privateKey, publicKey };
 }
Ejemplo n.º 22
0
        private void BtnAdd_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TbLastName.Text) ||
                string.IsNullOrWhiteSpace(TbFirstName.Text) ||
                string.IsNullOrWhiteSpace(TbLogin.Text) ||
                string.IsNullOrWhiteSpace(TbPassword.Text) ||
                string.IsNullOrWhiteSpace(TbPhone.Text) ||
                string.IsNullOrWhiteSpace(TbEmail.Text))
            {
                MessageBox.Show("Пустые поля!", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }
            DeliveryPoint point = CmbPoints.SelectedItem as DeliveryPoint;

            if (i == 0)
            {
                Person person = new Person()
                {
                    Email      = TbEmail.Text,
                    LastName   = TbLastName.Text,
                    FirstName  = TbFirstName.Text,
                    Login      = TbLogin.Text,
                    Password   = TbPassword.Text,
                    MiddleName = TbMiddleName.Text,
                    Phone      = TbPhone.Text,
                };
                Helper.context.People.Add(person);
                Helper.context.SaveChanges();
                Chilkat.Rsa rsa = new Chilkat.Rsa();
                rsa.GenerateKey(1024);
                string publicKey  = rsa.ExportPublicKey();
                string privateKey = rsa.ExportPrivateKey();
                Client client     = new Client()
                {
                    PersonId   = person.Id,
                    Wallet     = Convert.ToDecimal(TbWallet.Text),
                    PublicKey  = publicKey,
                    PrivateKey = privateKey,
                };
                Helper.context.Clients.Add(client);
                Helper.context.SaveChanges();
                ClientPoint clientPoint = new ClientPoint()
                {
                    ClientId        = client.Id,
                    DeliveryPointId = point.Id,
                };
                Helper.context.ClientPoints.Add(clientPoint);
                Helper.context.SaveChanges();
                var message = MessageBox.Show("Добавить еще одну точку забора, данному клиенту?", "Точка забора", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (message == MessageBoxResult.Yes)
                {
                    i++;
                }
                else
                {
                    i = 0;
                    Close();
                }
            }
            else if (i > 0)
            {
                var         lastClient  = Helper.context.Clients.OrderByDescending(x => x.Id).FirstOrDefault();
                ClientPoint clientPoint = new ClientPoint()
                {
                    ClientId        = lastClient.Id,
                    DeliveryPointId = point.Id,
                };
                Helper.context.ClientPoints.Add(clientPoint);
                Helper.context.SaveChanges();
                var message = MessageBox.Show("Добавить еще одну точку забора, данному клиенту?", "Точка забора", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (message == MessageBoxResult.Yes)
                {
                    i++;
                }
                else
                {
                    i = 0;
                    Close();
                }
            }
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
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);
        }