Example #1
0
        public static bool VerifyData(string originalMessage, string signedMessage, string publicKey)
        {
            bool success = false;

            using (RSA rsa = RSA.Create(RSAKeySize))
            {
                byte[] bytesToVerify = Encoding.Unicode.GetBytes(originalMessage);
                byte[] signedBytes   = Convert.FromBase64String(signedMessage);
                try
                {
                    rsa.ImportParameters(ToRSAParameters(publicKey));

                    success = rsa.VerifyData(bytesToVerify, signedBytes, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    rsa.Clear();
                }
            }
            return(success);
        }
Example #2
0
        public static string SignData(string message, string privateKey)
        {
            byte[] signedBytes;
            using (RSA rsa = RSA.Create(RSAKeySize))
            {
                byte[] originalData = Encoding.Unicode.GetBytes(message);

                try
                {
                    rsa.ImportParameters(ToRSAParameters(privateKey));

                    signedBytes = rsa.SignData(originalData, HashAlgorithmName.SHA512, RSASignaturePadding.Pkcs1);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return(null);
                }
                finally
                {
                    rsa.Clear();
                }
            }
            return(Convert.ToBase64String(signedBytes));
        }
Example #3
0
        public static byte[] Encrypt(string publicKey, string data)
        {
            using (RSA rsa = RSA.Create(RSAKeySize))
            {
                try
                {
                    rsa.ImportParameters(ToRSAParameters(publicKey));

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

                    byte[] encryptedBytes = rsa.Encrypt(plainBytes, RSAEncryptionPadding.OaepSHA512);

                    return(encryptedBytes);
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return(null);
                }
                finally
                {
                    rsa.Clear();
                }
            }
        }
Example #4
0
        //------   Since we are using an RSA with nonpersisted keycontainer, must pass it in to ensure it isn't colledted  -----
        private static byte[] GetPkcs12(RSA rsa, String keycontainer, String cspprovider, uint KEYSPEC, uint cspflags)
        {
            byte[] pfxblob    = null;
            IntPtr hCertCntxt = IntPtr.Zero;

            String DN = "CN=Opensslkey Unsigned Certificate";

            hCertCntxt = CreateUnsignedCertCntxt(keycontainer, cspprovider, KEYSPEC, cspflags, DN);
            if (hCertCntxt == IntPtr.Zero)
            {
                Console.WriteLine("Couldn't create an unsigned-cert\n");
                return(null);
            }
            try
            {
                X509Certificate cert = new X509Certificate(hCertCntxt); //create certificate object from cert context.
                SecureString    pswd = GetSecPswd("Set PFX ==>");
                pfxblob = cert.Export(X509ContentType.Pkcs12, pswd);
            }

            catch (Exception exc)
            {
                Console.WriteLine("BAD RESULT" + exc.Message);
                pfxblob = null;
            }

            rsa.Clear();
            if (hCertCntxt != IntPtr.Zero)
            {
                Win32.CertFreeCertificateContext(hCertCntxt);
            }
            return(pfxblob);
        }
Example #5
0
    static void Main(string[] args)
    {
        // Create an XmlDocument object.
        XmlDocument xmlDoc = new XmlDocument();

        // Load an XML file into the XmlDocument object.
        try
        {
            xmlDoc.PreserveWhitespace = true;
            xmlDoc.Load("test.xml");
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        // Create a new RSA key.  This key will encrypt a symmetric key,
        // which will then be imbedded in the XML document.
        RSA rsaKey = RSA.Create();

        try
        {
            // Encrypt the "creditcard" element.
            Encrypt(xmlDoc, "creditcard", "EncryptedElement1", rsaKey, "rsaKey");

            // Encrypt the "creditcard2" element.
            Encrypt(xmlDoc, "creditcard2", "EncryptedElement2", rsaKey, "rsaKey");

            // Display the encrypted XML to the console.
            Console.WriteLine("Encrypted XML:");
            Console.WriteLine();
            Console.WriteLine(xmlDoc.OuterXml);

            // Decrypt the "creditcard" element.
            Decrypt(xmlDoc, rsaKey, "rsaKey");

            // Display the encrypted XML to the console.
            Console.WriteLine();
            Console.WriteLine("Decrypted XML:");
            Console.WriteLine();
            Console.WriteLine(xmlDoc.OuterXml);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear the RSA key.
            rsaKey.Clear();
        }

        Console.ReadLine();
    }
Example #6
0
        /// <summary>
        /// Zapis kluczy do pliku xml
        /// </summary>
        /// <param name="rsaPriv">klucz prywatny</param>
        /// <param name="rsaPub">klucz publiczny</param>
        public static void ToFileRsa(RSAParameters rsaPriv, RSAParameters rsaPub)
        {
            //stream to save the keys
            FileStream   fs = null;
            StreamWriter sw = null;

            //create RSA provider
            using (RSA rsa = RSA.Create())
            {
                rsa.ImportParameters(rsaPriv);
                try
                {
                    //save private key
                    fs = new FileStream("privateKeyPath.xml", FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs);
                    sw.Write(rsa.ToXmlString(true));
                    sw.Flush();
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }

                rsa.ImportParameters(rsaPub);
                try
                {
                    //save public key
                    fs = new FileStream("publicKeyPath.xml", FileMode.Create, FileAccess.Write);
                    sw = new StreamWriter(fs);
                    sw.Write(rsa.ToXmlString(false));
                    sw.Flush();
                }
                finally
                {
                    if (sw != null)
                    {
                        sw.Close();
                    }
                    if (fs != null)
                    {
                        fs.Close();
                    }
                }
                rsa.Clear();
            }
        }
Example #7
0
        /// <summary>秘密鍵と公開鍵を取得する。</summary>
        /// <param name="publicKey">公開鍵</param>
        /// <param name="privateKey">秘密鍵</param>
        public static void GetKeys(out string publicKey, out string privateKey)
        {
            // RSACryptoServiceProviderオブジェクトの作成
            RSA rsa = RSACryptoServiceProvider.Create(); // devps(1703)

            // 公開鍵をXML形式で取得
            publicKey = rsa.ToXmlString(false);
            // 秘密鍵をXML形式で取得
            privateKey = rsa.ToXmlString(true);

            rsa.Clear(); // devps(1725)
        }
Example #8
0
        private void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    PublicKey  = null;
                    PrivateKey = null;
                }

                _rsa?.Clear();
                _disposed = true;
            }
        }
Example #9
0
    public static void Main(String[] args)
    {
        // Generate a signing key.
        RSA Key = RSA.Create();

        string xsl = @"
    <xs:transform xmlns:xs='http://www.w3.org/1999/XSL/Transform' version='1.0'>
        <xs:template match='/'>
            <xs:apply-templates/>
        </xs:template>
        <xs:template match='ElementToTransform'>
            <transformedElement/>
        </xs:template>
    </xs:transform>";

        try
        {
            // Create an XML file to sign.
            CreateSomeXml("Example.xml");
            Console.WriteLine("New XML file created.");

            // Sign the XML that was just created and save it in a
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key, xsl);
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \
            // the console.
            if (result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Key.Clear();
        }
    }
Example #10
0
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                #if NETSTANDARD2_0
                Public?.Dispose();
                Private?.Dispose();
                #endif

                #if NETFX
                Public?.Clear();
                Private?.Clear();
                #endif

                Public  = null;
                Private = null;
            }
        }
Example #11
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposed)
            {
                return;
            }

            if (disposing)
            {
                if (rsa != null)
                {
                    rsa.Clear();
                }
                rsa = null;
            }

            disposed = true;
        }
Example #12
0
    public static void Main(String[] args)
    {
        // Generate a signing key.
        RSA Key = RSA.Create();

        try
        {
            // Specify an element to sign.
            string[] elements = { "#tag1" };

            // Sign an XML file and save the signature to a
            // new file.
            SignXmlFile("Test.xml", "SignedExample.xml", Key, elements);
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");

            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to
            // the console.
            if (result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear resources associated with the
            // RSA instance.
            Key.Clear();
        }
    }
Example #13
0
        private string Sign(string data, X509Certificate2 pkcs12)
        {
            string signature = string.Empty;
            RSA    rsa       = null;

            try
            {
                rsa = pkcs12.GetRSAPrivateKey();
                byte[] signed = rsa.SignData(
                    Encoding.UTF8.GetBytes(data),
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);
                signature = Convert.ToBase64String(signed);
            }
            finally
            {
                rsa?.Clear();
            }

            return(signature);
        }
Example #14
0
        private bool Verify(string data, string base64Signature, X509Certificate2 keystore)
        {
            bool result;
            RSA  rsa = null;

            try
            {
                rsa    = keystore.GetRSAPublicKey();
                result = rsa.VerifyData(
                    Encoding.UTF8.GetBytes(data),
                    Convert.FromBase64String(base64Signature),
                    HashAlgorithmName.SHA256,
                    RSASignaturePadding.Pkcs1);
            }
            finally
            {
                rsa?.Clear();
            }

            return(result);
        }
Example #15
0
    public static void Main(String[] args)
    {
        // Generate a signing key.
        RSA Key = RSA.Create();

        try
        {
            // Create an XML file to sign.
            CreateSomeXml("Example.xml");
            Console.WriteLine("New XML file created.");

            // Sign the XML that was just created and save it in a
            // new file.
            SignXmlFile("Example.xml", "SignedExample.xml", Key, "ancestor-or-self::TempElement");
            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");
            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \
            // the console.
            if (result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            Key.Clear();
        }
    }
Example #16
0
    static void Main(string[] args)
    {
        Console.WriteLine("This example shows how to use the public and private key from a certificate to encrypt and decrypt data.\r\n");
        byte[] data = Encoding.ASCII.GetBytes("Hello World!");
        // load the certificate from a file
        Certificate cert = Certificate.CreateFromCerFile(@"client.cer");

        // get an RSA instance that represents the public key of the certificate
        RSA public_key = cert.PublicKey;
        // create a PKCS#1 key exchange formatter instance with the public key
        RSAPKCS1KeyExchangeFormatter kef = new RSAPKCS1KeyExchangeFormatter(public_key);

        // encrypt the data, using the public key from the certificate
        byte[] encrypted = kef.CreateKeyExchange(data);

        // associate the certificate with its private key
        // we set exportable to true because decryption will fail on Windows 98
        // if this flag is not set. If you do not use Windows 98, you should set
        // the exportable flag to false for increased security.
        cert.AssociateWithPrivateKey(@"client.pvk", "test", true);
        // get an RSA instance that represents the private key
        RSA private_key = cert.PrivateKey;
        // create a PKCS#1 key exchange deformatter instance with the private key
        RSAPKCS1KeyExchangeDeformatter ked = new RSAPKCS1KeyExchangeDeformatter(private_key);

        // decrypt the data, using the private key from the certificate
        byte[] decrypted = ked.DecryptKeyExchange(encrypted);

        // print the results in the console
        Console.WriteLine("Input data: " + Encoding.ASCII.GetString(data) + "\r\n");
        Console.WriteLine("Encrypted data:\r\n" + BytesToHex(encrypted) + "\r\n");
        Console.WriteLine("Decrypted data: " + Encoding.ASCII.GetString(decrypted));
        Console.WriteLine("\r\nPress ENTER to continue...");
        Console.ReadLine();

        // clean up
        public_key.Clear();
        private_key.Clear();
    }
Example #17
0
    public static void Main(String[] args)
    {
        // Generate a signing key.
        RSA Key = RSA.Create();

        try
        {
            // Sign the detached resource and save the signature in an XML file.
            SignDetachedResource("http://www.microsoft.com", "SignedExample.xml", Key);

            Console.WriteLine("XML file signed.");

            // Verify the signature of the signed XML.
            Console.WriteLine("Verifying signature...");

            bool result = VerifyXmlFile("SignedExample.xml");

            // Display the results of the signature verification to \
            // the console.
            if (result)
            {
                Console.WriteLine("The XML signature is valid.");
            }
            else
            {
                Console.WriteLine("The XML signature is not valid.");
            }
        }
        catch (CryptographicException e)
        {
            Console.WriteLine(e.Message);
        }
        finally
        {
            // Clear resources associated with the
            // RSA instance.
            Key.Clear();
        }
    }
Example #18
0
        public static string Decrypt(string privateKey, byte[] encryptedBytes)
        {
            using (RSA rsa = RSA.Create(RSAKeySize))
            {
                try
                {
                    rsa.ImportParameters(ToRSAParameters(privateKey));

                    byte[] plainBytes = rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA512);

                    return(Encoding.UTF8.GetString(plainBytes, 0, plainBytes.Length));
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
                    return(null);
                }
                finally
                {
                    rsa.Clear();
                }
            }
        }
Example #19
0
        private static byte[] GetPkcs12(
            RSA rsa,
            string keycontainer,
            string cspprovider,
            uint KEYSPEC,
            uint cspflags)
        {
            IntPtr zero = IntPtr.Zero;
            string DN   = "CN=Opensslkey Unsigned Certificate";
            IntPtr unsignedCertCntxt = opensslkey.CreateUnsignedCertCntxt(keycontainer, cspprovider, KEYSPEC, cspflags, DN);

            if (unsignedCertCntxt == IntPtr.Zero)
            {
                Console.WriteLine("Couldn't create an unsigned-cert\n");
                return((byte[])null);
            }
            byte[] numArray;
            try
            {
                X509Certificate certificate = new X509Certificate(unsignedCertCntxt);
                X509Certificate2UI.DisplayCertificate(new X509Certificate2(certificate));
                SecureString secPswd = opensslkey.GetSecPswd("Set PFX Password ==>");
                numArray = certificate.Export(X509ContentType.Pfx, secPswd);
            }
            catch (Exception ex)
            {
                Console.WriteLine("BAD RESULT" + ex.Message);
                numArray = (byte[])null;
            }
            rsa.Clear();
            if (unsignedCertCntxt != IntPtr.Zero)
            {
                Win32.CertFreeCertificateContext(unsignedCertCntxt);
            }
            return(numArray);
        }