Ad

FromXmlString In CSharp And Javascript

- 1 answer

Can anyone tell me what the below piece of code is doing. I want to implement this using Nodejs. I'm totally new to CSharp

Does this method FromXmlString really mandatory for encryption here. Please help

public void FromXmlString(RSACryptoServiceProvider rsa, string xmlString)
    {
        RSAParameters parameters = new RSAParameters();

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xmlString);

        if (xmlDoc.DocumentElement.Name.Equals("RSAKeyValue"))
        {
            foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes)
            {
                switch (node.Name)
                {
                    case "Modulus": parameters.Modulus = Convert.FromBase64String(node.InnerText); break;
                    case "Exponent": parameters.Exponent = Convert.FromBase64String(node.InnerText); break;
                    case "P": parameters.P = Convert.FromBase64String(node.InnerText); break;
                    case "Q": parameters.Q = Convert.FromBase64String(node.InnerText); break;
                    case "DP": parameters.DP = Convert.FromBase64String(node.InnerText); break;
                    case "DQ": parameters.DQ = Convert.FromBase64String(node.InnerText); break;
                    case "InverseQ": parameters.InverseQ = Convert.FromBase64String(node.InnerText); break;
                    case "D": parameters.D = Convert.FromBase64String(node.InnerText); break;
                }
            }
        }
        rsa.ImportParameters(parameters);
    }

 public string EncryptAsymmetric(string encryptText, string publicKey)
    {
        bool isOAEP = false;
        byte[] byteEncrypt = Encoding.UTF8.GetBytes(encryptText);
        byte[] encryptedData;

        var RSA = new RSACryptoServiceProvider();


        FromXmlString(RSA, publicKey);

        encryptedData = RSA.Encrypt(byteEncrypt, isOAEP);

        return Convert.ToBase64String(encryptedData);
    }
Ad

Answer

In a nutshell, it's RSA encrypting a string (encryptText), using parameters specified as an XML formatted string (publicKey) and returning the result as a Base64 encoded string.

FromXmlString is necessary as it is being used to load the encryption parameters from the XML formatted publicKey.

Ad
source: stackoverflow.com
Ad