How to Generate Unique Public and Private Key via RSA

后端 未结 3 1679
旧巷少年郎
旧巷少年郎 2020-11-29 15:37

I am building a custom shopping cart where CC numbers and Exp date will be stored in a database until processing (then deleted). I need to encrypt this data (obviously).

3条回答
  •  爱一瞬间的悲伤
    2020-11-29 15:59

    The RSACryptoServiceProvider(CspParameters) constructor creates a keypair which is stored in the keystore on the local machine. If you already have a keypair with the specified name, it uses the existing keypair.

    It sounds as if you are not interested in having the key stored on the machine.

    So use the RSACryptoServiceProvider(Int32) constructor:

    public static void AssignNewKey(){
        RSA rsa = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key
    
        string publicPrivateKeyXML = rsa.ToXmlString(true);
        string publicOnlyKeyXML = rsa.ToXmlString(false);
        // do stuff with keys...
    }
    

    EDIT:

    Alternatively try setting the PersistKeyInCsp to false:

    public static void AssignNewKey(){
        const int PROVIDER_RSA_FULL = 1;
        const string CONTAINER_NAME = "KeyContainer";
        CspParameters cspParams;
        cspParams = new CspParameters(PROVIDER_RSA_FULL);
        cspParams.KeyContainerName = CONTAINER_NAME;
        cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
        cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
        rsa = new RSACryptoServiceProvider(cspParams);
    
        rsa.PersistKeyInCsp = false;
    
        string publicPrivateKeyXML = rsa.ToXmlString(true);
        string publicOnlyKeyXML = rsa.ToXmlString(false);
        // do stuff with keys...
    }
    

提交回复
热议问题