简体   繁体   中英

Exporting encrypted XML file and decrypt in another application?

I am making an application in c# to encrypt the exported XML files so people cant read the files when exported. A user downloads an encrypted XML file and imports it on the local application which has to decrypt it.

Right now i can encrypt the file but how do i share the key safely with the other application to decrypt the xml files there safely?

        static CspParameters cspParams = new CspParameters();
        static RSACryptoServiceProvider rsaKey = new RSACryptoServiceProvider(cspParams);

        static void Main(string[] args)
        {
            cspParams.KeyContainerName = "XML_ENC_RSA_KEY";

            Console.WriteLine("What do you want to do?");
            Console.WriteLine("");
            Console.WriteLine("- Export");
            Console.WriteLine("- Exit");
            Console.Write("Enter: ");
            if (Console.ReadLine() == "export")
            {
                Export();
                Console.WriteLine("file Exported");
            }

You could export your private key to a .pem file and then the other application could use it.

Or if the other application you're talking about is your own application on another computer you could extend your application so that it allows to import from xml and you distribute this xml only where you want to

Small code sample included:

    byte[] toEncryptData = Encoding.ASCII.GetBytes("<mytest></mytest>");

    //Generate keys
    RSACryptoServiceProvider rsaGenKeys = new RSACryptoServiceProvider();
    string privateXml = rsaGenKeys.ToXmlString(true);
    string publicXml = rsaGenKeys.ToXmlString(false);

    //Encode with public key
    RSACryptoServiceProvider rsaPublic = new RSACryptoServiceProvider();
    rsaPublic.FromXmlString(publicXml);
    byte[] encryptedRSA = rsaPublic.Encrypt(toEncryptData, false);
    string EncryptedResult = Encoding.Default.GetString(encryptedRSA);

    File.WriteAllText("key", privateXml);
    var key = File.ReadAllText("key");

    //Decode with private key
    var rsaPrivate = new RSACryptoServiceProvider();
    rsaPrivate.FromXmlString(key);
    byte[] decryptedRSA = rsaPrivate.Decrypt(encryptedRSA, false);
    string originalResult = Encoding.Default.GetString(decryptedRSA);
    Console.WriteLine(originalResult);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM