Securing a license key with RSA key

て烟熏妆下的殇ゞ 提交于 2019-11-30 14:47:42

I used this method to sign xml documents using a private key stored in an xml file that I then embedded into the application .dll as a resource. I think you may be struggling with permissions accessing the keystore, and this would also create hassles transferring the code to other servers etc.

Here is the code to get the private key as an embedded resource and sign the document: (Sign is the name of the class this method is located in, Licensing.Private.Private.xml is a combination of the default namespace + folder + filename of the resource)

public static void SignDocument(XmlDocument xmldoc)
{
    //Get the XML content from the embedded XML privatekey.
    Stream s = null;
    string xmlkey = string.Empty;
    try
    {
        s = typeof(Sign).Assembly.GetManifestResourceStream("Licensing.Private.Private.xml");

        // Read-in the XML content.
        StreamReader reader = new StreamReader(s);
        xmlkey = reader.ReadToEnd();
        reader.Close();
    }
    catch (Exception e)
    {
        throw new Exception("Error: could not import key:",e);
    }

    // Create an RSA crypto service provider from the embedded
    // XML document resource (the private key).
    RSACryptoServiceProvider csp = new RSACryptoServiceProvider();
    csp.FromXmlString(xmlkey);
    //Creating the XML signing object.
    SignedXml sxml = new SignedXml(xmldoc);
    sxml.SigningKey = csp;

    //Set the canonicalization method for the document.
    sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl; // No comments.

    //Create an empty reference (not enveloped) for the XPath transformation.
    Reference r = new Reference("");

    //Create the XPath transform and add it to the reference list.
    r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

    //Add the reference to the SignedXml object.
    sxml.AddReference(r);

    //Compute the signature.
    sxml.ComputeSignature();

    // Get the signature XML and add it to the document element.
    XmlElement sig = sxml.GetXml();
    xmldoc.DocumentElement.AppendChild(sig);
}

Use the following code the generate the private.xml and public.xml keys. Keep the private.xml file secure, obviously.

RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
File.WriteAllText(@"C:\privateKey.xml", rsa.ToXmlString(true));  // Private Key
File.WriteAllText(@"C:\publicKey.xml", rsa.ToXmlString(false));  // Public Key

Guess, the problem is that different users don't have access to the key that is stored for the 1st user (Please note: I am not a cryptography expert).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!