public void AssignNewRSAKey(bool storeKeysInDB = false) { // here we are saying we want to use a 2048 bit key using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048)) { RSA.PersistKeyInCsp = false; _publicKey = RSA.ExportParameters(false); _privateKey = RSA.ExportParameters(true); if (storeKeysInDB) { RSAKeys rsaKeys = new RSAKeys(); rsaKeys.RsaPrivateKey = RSA.ToXmlString(true); // true gets the private key rsaKeys.RsaPublicKey = RSA.ToXmlString(false); // false gets the public key _jsonDataBaseInstance = new JSONDataBase(); _jsonDataBaseInstance.AddRSAKey(rsaKeys); } } }
public byte[] EncryptDataUsingRSA(byte[] dataToEncrypt, bool getKeyFromDataBase = false) { byte[] cipherBytes; using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048)) { RSA.PersistKeyInCsp = false; if (getKeyFromDataBase) { RSAKeys rsaKeys = _jsonDataBaseInstance.GetRSAKeys(); RSA.FromXmlString(rsaKeys.RsaPublicKey); } else { RSA.ImportParameters(_publicKey); } cipherBytes = RSA.Encrypt(dataToEncrypt, true); } return(cipherBytes); }
public byte[] DecryptDataUsingRSA(byte[] dataToEncrypt, bool getKeyFromDataBase = false) { byte[] dataToSendBack; // using a 2048 bit key using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048)) { RSA.PersistKeyInCsp = false; // is set to false because we are not using the key container if (getKeyFromDataBase) { RSAKeys rsaKeys = _jsonDataBaseInstance.GetRSAKeys(); RSA.FromXmlString(rsaKeys.RsaPrivateKey); } else { RSA.ImportParameters(_privateKey); } dataToSendBack = RSA.Decrypt(dataToEncrypt, true); // setting true here adds a padding scheme as an extra protection for our data } return(dataToSendBack); }