public string Encrypt(KeyPair encryptionKeyPair, string plainText) { //use THEIR public key to encrypt _rsaCryptoServiceProvider.FromXmlString(encryptionKeyPair.Public.Key); //Get Modulus Size and compare it to length of PlainText // If Length of PlainText > (Modulus Size - 11), then PlainText will need to be broken into segments of size (Modulus Size - 11) // Each of these segments will be encrypted separately // and will return encrypted strings equal to the Modulus Size (with at least 11 bytes of padding) // When decrypting, if the EncryptedText string > Modulus size, it will be split into segments of size equal to Modulus Size // Each of these EncryptedText segments will be decrypted individually with the resulting PlainText segments re-assembled. var blockSize = GetModulusSize() - 11; var plainStream = new MemoryStream(TextHelpers.ClearTextToClearBytes(plainText)); var cipherStream = new MemoryStream(); var buffer = new byte[blockSize]; while (plainStream.Read(buffer, 0, blockSize) > 0) { var c = _rsaCryptoServiceProvider.Encrypt(buffer, false); cipherStream.Write(c, 0, c.Length); } var cipherBytes = cipherStream.ToArray(); return(TextHelpers.CipherBytesToCipherText(cipherBytes)); }
public string Sign(KeyPair signingKeyPair, string text) { //Use PrivateKey to sign _rsaCryptoServiceProvider.FromXmlString(signingKeyPair.Private.Key); var signedData = _rsaCryptoServiceProvider.SignData(TextHelpers.ClearTextToClearBytes(text), HashAlgorithm.Create()); var signature = TextHelpers.CipherBytesToCipherText(signedData); return(string.Format("{0}<signature>{1}</signature>", text, signature)); }
public bool Authenticate(KeyPair authenticationKeyPair, string signedText) { _rsaCryptoServiceProvider.FromXmlString(authenticationKeyPair.Public.Key); string signature = CryptoHelpers.ExtractSignature(signedText); string message = CryptoHelpers.StripSignature(signedText); if (string.IsNullOrEmpty(signature)) { throw new Exception("Digital signature is missing or not formatted properly."); } var bytes = TextHelpers.ClearTextToClearBytes(message); var sigbytes = TextHelpers.CipherTextToCipherBytes(signature); return(_rsaCryptoServiceProvider.VerifyData(bytes, HashAlgorithm.Create(), sigbytes)); }