/// <summary> /// <para> /// Upserts the cache entry with an expiration time defined by <see cref="Cache.DurationSeconds"/>. /// After this period, it's no longer possible to reconnect a Blazor session back to the server, /// so we remove the entry from the cache. /// </para> /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <param name="cache">The Cache.</param> /// <param name="cipher">The AES Cipher used to encrypt/decrypt cookies.</param> /// <param name="cacheOptions">The Cache options.</param> /// <param name="logger">The <see cref="INeonLogger"/></param> /// <returns></returns> public async Task InvokeAsync( HttpContext context, Service service, IDistributedCache cache, AesCipher cipher, DistributedCacheEntryOptions cacheOptions, INeonLogger logger) { await SyncContext.Clear; await _next(context); if (service.CurrentConnections.Contains(context.Connection.Id)) { var cookie = context.Request.Cookies.Where(c => c.Key == Service.SessionCookieName).First(); var sessionId = cipher.DecryptStringFrom(cookie.Value); var session = NeonHelper.JsonDeserialize <Session>(await cache.GetAsync(sessionId)); if (session.ConnectionId == context.Connection.Id) { await cache.SetAsync(session.Id, NeonHelper.JsonSerializeToBytes(session), cacheOptions); WebsocketMetrics.CurrentConnections.Dec(); service.CurrentConnections.Remove(context.Connection.Id); } } }
public void UniqueOutput() { // Verify that we generate and use a unique IV for // every encryption run such that encrypting the same // data will return different results. This is an // important security best practice. const int iterations = 1000; var decrypted = "We hold these truths to be self-evident, that all men are created equal."; var encryptions = new HashSet <string>(); using (var cipher = new AesCipher()) { for (int i = 0; i < iterations; i++) { var encrypted = cipher.EncryptToBase64(decrypted); Assert.DoesNotContain(encrypted, encryptions); Assert.Equal(decrypted, cipher.DecryptStringFrom(encrypted)); encryptions.Add(encrypted); } } }
public void UniqueKeys() { const int iterations = 1000; // Generate a number of keys of each valid size and ensure that each key is unique. foreach (var size in sizes) { var keys = new HashSet <string>(); for (int i = 0; i < iterations; i++) { var key = AesCipher.GenerateKey(size); Assert.NotNull(key); var keyBytes = Convert.FromBase64String(key); Assert.Equal(size, keyBytes.Length * 8); Assert.DoesNotContain(key, keys); keys.Add(key); } } }
public void AesCipher_Encryption_Test() { var encryption = AesCipher.AESEncrypt("VeyselMUTLU"); var descryption = AesCipher.AESDecrypt(encryption); Assert.AreEqual("VeyselMUTLU", descryption); }
static void Main(string[] args) { var userkey = new byte[] //europe maplestory key { 0x13, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0xB4, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x0F, 0x00, 0x00, 0x00, 0x33, 0x00, 0x00, 0x00, 0x52, 0x00, 0x00, 0x00 }; var aes = new AesCipher(userkey); var info = new ServerInfo() { Version = 97, Subversion = "1", Locale = 9 }; using (var acceptor = new Acceptor(info, aes, 8484)) { acceptor.OnClientAccepted += OnClientAccepted; acceptor.Start(); Console.ReadLine(); } }
static VaultSecureContainer ConfigureContainer() { var vault = new FileSystemVault(".", "store.vault"); var cipher = new AesCipher(); return(new VaultSecureContainer(vault, cipher)); }
public void TamperDetection() { // Tamper with an encrypted payload and verify that this // is detected via the HMAC signature. using (var cipher = new AesCipher()) { var decrypted = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; var encrypted = cipher.EncryptToBytes(decrypted); Assert.Equal(decrypted, cipher.DecryptBytesFrom(encrypted)); // Modify the last byte and ensure that decryption fails. var tampered = Clone(encrypted); tampered[encrypted.Length - 1] = (byte)(~tampered[encrypted.Length - 1]); Assert.Throws <CryptographicException>(() => cipher.DecryptBytesFrom(tampered)); // Remove the last byte and ensure that decryption fails. tampered = new byte[encrypted.Length - 1]; for (int i = 0; i < tampered.Length; i++) { tampered[i] = encrypted[i]; } Assert.Throws <CryptographicException>(() => cipher.DecryptBytesFrom(tampered)); } }
/* TODO ERROR: Skipped EndRegionDirectiveTrivia */ /* TODO ERROR: Skipped RegionDirectiveTrivia */ public environmentVarsCore load() { state.secretKey = state.SettingsSecretKey; var encryption = new AesCipher(state); var settingsFile = new FileInfo(Path.Combine(state.libraryPath, "ScrewDriver.eon")); settingsFile.Refresh(); if (settingsFile.Exists) { try { var bytes = File.ReadAllBytes(Path.Combine(state.libraryPath, "ScrewDriver.eon")); string encrypted = Convert.ToBase64String(bytes, 0, bytes.Length); string decrypted = encryption.decrypt(encrypted); var data = JsonConvert.DeserializeObject <Dictionary <string, object> >(decrypted); state.country = data["country"].ToString(); state.currentLang = data["language"].ToString(); state.ServerBaseAddr = data["serverAddress"].ToString(); state.ApiServerAddrPath = data["ApiServerAddrPath"].ToString(); state.secretKey = data["ApiEncryptionKey"].ToString(); state.SendDiagnosticData = Convert.ToBoolean(data["sendDiags"]); state.SendCrashData = Convert.ToBoolean(data["sendCrash"]); return(state); } catch (Exception ex) { hasError = true; errorMessage = ex.ToString(); return(default);
/// <summary> /// Encrypts packet data /// </summary> public Span <byte> Encrypt(ReadOnlySpan <byte> data, bool toClient) { if (!Handshaken || MapleIv == null) { return(null); } var newData = new byte[data.Length + 4].AsSpan(); var header = newData.Slice(0, 4); var content = newData.Slice(4, data.Length); data.CopyTo(content); if (toClient) { WriteHeaderToClient(header, data.Length); } else { WriteHeaderToServer(header, data.Length); } EncryptShanda(content); AesCipher?.AesTransform(content, MapleIv.Bytes); MapleIv.Shuffle(); return(newData); }
public static byte[] GenerateRandomKey(int?keyLength = null, CipherMode?mode = null) { if (keyLength.HasValue) { ValidateKeyLength(keyLength.Value); } return(AesCipher.GenerateKey(mode, keyLength)); }
public void DefaultKeySize() { // Verify that the default key size is 256 bits. var key = AesCipher.GenerateKey(); Assert.NotNull(key); Assert.Equal(256, Convert.FromBase64String(key).Length * 8); }
public void AesCipherConstructorTest() { byte[] key = null; // TODO: Initialize to an appropriate value CipherMode mode = null; // TODO: Initialize to an appropriate value CipherPadding padding = null; // TODO: Initialize to an appropriate value AesCipher target = new AesCipher(key, mode, padding); Assert.Inconclusive("TODO: Implement code to verify target"); }
static void Main() { cipher = new AesCipher(userKey); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); client = new Client(IPAddress.Parse(loginIP), loginPort, cipher); gui = new MainForm(); Application.Run(gui); }
/// <summary> /// Constructor. /// </summary> /// <param name="cache"></param> /// <param name="logger"></param> /// <param name="logger"></param> public SessionTransformer( IDistributedCache cache, INeonLogger logger, DistributedCacheEntryOptions cacheOptions, AesCipher cipher) { this.cache = cache; this.logger = logger; this.cacheOptions = cacheOptions; this.cipher = cipher; }
public void Encrypt_Input_128_CBC() { var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 }; var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 }; var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 }; var expected = new byte[] { 0x19, 0x7f, 0x80, 0xd8, 0xc9, 0x89, 0xc4, 0xa7, 0xc6, 0xc6, 0x3f, 0x9f, 0x1e, 0x00, 0x1f, 0x72, 0xa7, 0x5e, 0xde, 0x40, 0x88, 0xa2, 0x72, 0xf2, 0xed, 0x3f, 0x81, 0x45, 0xb6, 0xbd, 0x45, 0x87, 0x15, 0xa5, 0x10, 0x92, 0x4a, 0x37, 0x9e, 0xa9, 0x80, 0x1c, 0x14, 0x83, 0xa3, 0x39, 0x45, 0x28 }; var testCipher = new AesCipher(key, new CbcCipherMode(iv), null); var actual = testCipher.Encrypt(input); Assert.IsTrue(actual.IsEqualTo(expected)); }
public void Decrypt_AES_128_CTR() { var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0xb0, 0x74, 0x21, 0x87, 0x16, 0xb9, 0x69, 0x48, 0x33, 0xce, 0xb3, 0xe7, 0xdc, 0x3f, 0x50, 0xdc, 0xcc, 0xd5, 0x27, 0xb7, 0xfe, 0x7a, 0x78, 0x22, 0xae, 0xc8 }; var key = new byte[] { 0x17, 0x78, 0x56, 0xe1, 0x3e, 0xbd, 0x3e, 0x50, 0x1d, 0x79, 0x3f, 0x0f, 0x55, 0x37, 0x45, 0x54 }; var iv = new byte[] { 0xe6, 0x65, 0x36, 0x0d, 0xdd, 0xd7, 0x50, 0xc3, 0x48, 0xdb, 0x48, 0x07, 0xa1, 0x30, 0xd2, 0x38 }; var output = new byte[] { 0xca, 0xfb, 0x1c, 0x49, 0xbf, 0x82, 0x2a, 0xbb, 0x1c, 0x52, 0xc7, 0x86, 0x22, 0x8a, 0xe5, 0xa4, 0xf3, 0xda, 0x4e, 0x1c, 0x3a, 0x87, 0x41, 0x1c, 0xd2, 0x6e, 0x76, 0xdc, 0xc2, 0xe9, 0xc2, 0x0e, 0xf5, 0xc7, 0xbd, 0x12, 0x85, 0xfa, 0x0e, 0xda, 0xee, 0x50, 0xd7, 0xfd, 0x81, 0x34, 0x25, 0x6d }; var testCipher = new AesCipher(key, new CtrCipherMode(iv), null); var actual = testCipher.Decrypt(output); Assert.IsTrue(input.IsEqualTo(actual)); }
static void Test(AesProvider aesProvider) { var text = Guid.NewGuid().ToString(); var cipher = aesProvider.Encrypt(text.Bytes()); var bytes = cipher.ToBytes(); var _cipher = new AesCipher().FromBytes(bytes); var source = aesProvider.Decrypt(_cipher).String(); Assert.Equal(text, source); }
public void Streams() { // Verify that we can encrypt and decrypt streams. var decryptedBytes = new byte[32 * 1024]; var encryptedBytes = (byte[])null; var key = string.Empty; // Encrypt some bytes. for (int i = 0; i < decryptedBytes.Length; i++) { decryptedBytes[i] = (byte)i; } using (var decryptedStream = new MemoryStream(decryptedBytes)) { using (var encryptedStream = new MemoryStream()) { using (var cipher = new AesCipher()) { cipher.EncryptStream(decryptedStream, encryptedStream); // Save the key and encrypted data so we can test decryption below. encryptedBytes = encryptedStream.ToArray(); key = cipher.Key; } // Verify that the two streams haven't been dispoed. decryptedStream.Position = 0; encryptedStream.Position = 0; } } // Decrypt the encypted data and verify. using (var encryptedStream = new MemoryStream(encryptedBytes)) { using (var decryptedStream = new MemoryStream()) { using (var cipher = new AesCipher(key)) { cipher.DecryptStream(encryptedStream, decryptedStream); } // Verify that the decrypted data matches the original. Assert.Equal(decryptedBytes, decryptedStream.ToArray()); } } }
public bool Decrypt(EncryptedMessage encryptedMessage, int senderId, out string messageText) { if (encryptedMessage == null) { throw new ArgumentException("Encrypted message cannot be null"); } if (encryptedMessage.Body == null || encryptedMessage.DigitalSignature == null || encryptedMessage.SymmetricKey == null || encryptedMessage.Iv == null) { throw new ArgumentException("Not all encrypted message fields are initialized"); } IContactModel senderContact = _storageService.GetContacts().FirstOrDefault(c => c.Id == senderId); if (senderContact == null) { throw new ArgumentException("Contact with id of senderId does not exist"); } string receiverKeyPair = _storageService.GetUser().KeyPair; string senderPublicKey = senderContact.PublicKey; try { // decrypt symmetric key with receivers private key RsaCipher rsa = new RsaCipher(receiverKeyPair); byte[] encryptedSymmetricKeyBytes = FormatConverter.String64ToBytes(encryptedMessage.SymmetricKey); byte[] decryptedSymmetricKeyBytes = rsa.Decrypt(encryptedSymmetricKeyBytes); // decrypt message text with jsut decrypted symmetric key byte[] ivBytes = FormatConverter.String64ToBytes(encryptedMessage.Iv); AesCipher aes = new AesCipher(decryptedSymmetricKeyBytes, ivBytes); byte[] encryptedMessageBytes = FormatConverter.String64ToBytes(encryptedMessage.Body); byte[] decryptedMessageBytes = aes.Decrypt(encryptedMessageBytes); // set message text out parameter messageText = FormatConverter.BytesToString(decryptedMessageBytes); // verify digital signature rsa = new RsaCipher(senderPublicKey); byte[] digitalSignatureBytes = FormatConverter.String64ToBytes(encryptedMessage.DigitalSignature); bool signatureOk = rsa.VerifyDigitalSignature(decryptedMessageBytes, digitalSignatureBytes); return(signatureOk); } catch (Exception ex) { messageText = null; return(false); } }
internal Session(Socket socket, SessionType type, AesCipher aesCipher) { this.socket = socket; SessionType = type; Encrypted = type != SessionType.CLIENT; this.aesCipher = aesCipher; Connected = true; sendLock = new object(); packetBuffer = new byte[RECEIVE_SIZE]; recvBuffer = new byte[RECEIVE_SIZE]; cursor = 0; }
public void Test_Cipher_AES_128_CBC() { var input = new byte[] { 0x00, 0x00, 0x00, 0x2c, 0x1a, 0x05, 0x00, 0x00, 0x00, 0x0c, 0x73, 0x73, 0x68, 0x2d, 0x75, 0x73, 0x65, 0x72, 0x61, 0x75, 0x74, 0x68, 0x30, 0x9e, 0xe0, 0x9c, 0x12, 0xee, 0x3a, 0x30, 0x03, 0x52, 0x1c, 0x1a, 0xe7, 0x3e, 0x0b, 0x9a, 0xcf, 0x9a, 0x57, 0x42, 0x0b, 0x4f, 0x4a, 0x15, 0xa0, 0xf5 }; var key = new byte[] { 0xe4, 0x94, 0xf9, 0xb1, 0x00, 0x4f, 0x16, 0x2a, 0x80, 0x11, 0xea, 0x73, 0x0d, 0xb9, 0xbf, 0x64 }; var iv = new byte[] { 0x74, 0x8b, 0x4f, 0xe6, 0xc1, 0x29, 0xb3, 0x54, 0xec, 0x77, 0x92, 0xf3, 0x15, 0xa0, 0x41, 0xa8 }; var output = new byte[] { 0x19, 0x7f, 0x80, 0xd8, 0xc9, 0x89, 0xc4, 0xa7, 0xc6, 0xc6, 0x3f, 0x9f, 0x1e, 0x00, 0x1f, 0x72, 0xa7, 0x5e, 0xde, 0x40, 0x88, 0xa2, 0x72, 0xf2, 0xed, 0x3f, 0x81, 0x45, 0xb6, 0xbd, 0x45, 0x87, 0x15, 0xa5, 0x10, 0x92, 0x4a, 0x37, 0x9e, 0xa9, 0x80, 0x1c, 0x14, 0x83, 0xa3, 0x39, 0x45, 0x28 }; var testCipher = new AesCipher(key, new CbcCipherMode(iv), null); var r = testCipher.Encrypt(input); if (!r.SequenceEqual(output)) { Assert.Fail("Invalid encryption"); } }
protected void SerializeToFile(string filePath, object obj, ConfigurationFileInfo info) { Directory.CreateDirectory(Path.GetDirectoryName(filePath)); StringWriter stringWriter = new StringWriter(); JsonWriter jsonWriter = new JsonWriter(stringWriter); jsonWriter.Validate = false; jsonWriter.PrettyPrint = true; JsonMapper.ToJson(obj, jsonWriter); string text = stringWriter.ToString(); string contents = (info.IsEncrypted ? AesCipher.Encrypt(text, info.EncryptionKey) : text); File.WriteAllText(filePath, contents); }
/// <summary> /// Constructor. /// </summary> /// <param name="cache"></param> /// <param name="aesCipher"></param> /// <param name="dexClient"></param> /// <param name="logger"></param> public SessionTransformer( IDistributedCache cache, AesCipher aesCipher, DexClient dexClient, INeonLogger logger, DistributedCacheEntryOptions cacheOptions) { this.cache = cache; this.cipher = aesCipher; this.dexClient = dexClient; this.dexHost = dexClient.BaseAddress.Host; this.logger = logger; this.cacheOptions = cacheOptions; }
/// <inheritdoc/> protected async override Task <int> OnRunAsync() { await SetStatusAsync(NeonServiceStatus.Starting); Config = await ProxyConfig.FromFileAsync(GetConfigFilePath(ConfigFile)); DnsClient = new LookupClient(new LookupClientOptions() { UseCache = Config.Dns.UseCache, MaximumCacheTimeout = TimeSpan.FromSeconds(Config.Dns.MaximumCacheTimeoutSeconds), MinimumCacheTimeout = TimeSpan.FromSeconds(Config.Dns.MinimumCacheTimeoutSeconds), CacheFailedResults = Config.Dns.CacheFailedResults }); AesCipher = new AesCipher(GetEnvironmentVariable("COOKIE_CIPHER", AesCipher.GenerateKey(), redacted: !Log.IsLogDebugEnabled)); CurrentConnections = new HashSet <string>(); // Start the web service. webHost = new WebHostBuilder() .ConfigureAppConfiguration( (hostingcontext, config) => { config.Sources.Clear(); }) .UseStartup <Startup>() .UseKestrel(options => options.Listen(IPAddress.Any, Config.Port)) .ConfigureServices(services => services.AddSingleton(typeof(Service), this)) .UseStaticWebAssets() .Build(); _ = webHost.RunAsync(); Log.LogInfo($"Listening on {IPAddress.Any}:{Config.Port}"); // Indicate that the service is ready for business. await SetStatusAsync(NeonServiceStatus.Running); // Handle termination gracefully. await Terminator.StopEvent.WaitAsync(); Terminator.ReadyToExit(); return(0); }
/// <summary> /// Decrypts a maple packet contained in <paramref name="data"/> /// </summary> /// <param name="data">Data to decrypt</param> public Span <byte> Decrypt(Span <byte> data) { if (!Handshaken || MapleIv == null) { return(data); } var header = data.Slice(0, 4); var length = GetPacketLength(header); var content = data.Slice(4, length); AesCipher?.AesTransform(content, MapleIv.Bytes); MapleIv.Shuffle(); DecryptShanda(content); return(content); }
public OutputStreamEncryption(Stream outc, byte[] key, int off, int len, int revision) { Outc = outc; _aes = revision == Aes128; if (_aes) { byte[] iv = IvGenerator.GetIv(); byte[] nkey = new byte[len]; Array.Copy(key, off, nkey, 0, len); Cipher = new AesCipher(true, nkey, iv); Write(iv, 0, iv.Length); } else { Arcfour = new ArcfourEncryption(); Arcfour.PrepareArcfourKey(key, off, len); } }
/// <summary> /// Constructor. /// </summary> /// <param name="blazorProxyService">The <see cref="Service"/></param> /// <param name="config">The <see cref="ProxyConfig"/></param> /// <param name="httpClient">HttpClient for forwarding requests.</param> /// <param name="forwarder">The YARP forwarder.</param> /// <param name="cache">The cache used for storing session information.</param> /// <param name="aesCipher">The <see cref="AesCipher"/> used for cookie encryption.</param> /// <param name="dnsClient">The <see cref="LookupClient"/> for service discovery.</param> /// <param name="sessionTransformer">The <see cref="SessionTransformer"/>.</param> public BlazorController( Service blazorProxyService, ProxyConfig config, HttpMessageInvoker httpClient, IHttpForwarder forwarder, IDistributedCache cache, AesCipher aesCipher, LookupClient dnsClient, SessionTransformer sessionTransformer) { this.blazorProxyService = blazorProxyService; this.config = config; this.httpClient = httpClient; this.forwarder = forwarder; this.cache = cache; this.cipher = aesCipher; this.transformer = sessionTransformer; this.dnsClient = dnsClient; }
public void EncryptBlockTest() { byte[] key = null; // TODO: Initialize to an appropriate value CipherMode mode = null; // TODO: Initialize to an appropriate value CipherPadding padding = null; // TODO: Initialize to an appropriate value AesCipher target = new AesCipher(key, mode, padding); // TODO: Initialize to an appropriate value byte[] inputBuffer = null; // TODO: Initialize to an appropriate value int inputOffset = 0; // TODO: Initialize to an appropriate value int inputCount = 0; // TODO: Initialize to an appropriate value byte[] outputBuffer = null; // TODO: Initialize to an appropriate value int outputOffset = 0; // TODO: Initialize to an appropriate value int expected = 0; // TODO: Initialize to an appropriate value int actual; actual = target.EncryptBlock(inputBuffer, inputOffset, inputCount, outputBuffer, outputOffset); Assert.AreEqual(expected, actual); Assert.Inconclusive("Verify the correctness of this test method."); }
/// <summary> /// Constructor. /// </summary> /// <param name="NeonSsoSessionProxyService"></param> /// <param name="httpClient"></param> /// <param name="forwarder"></param> /// <param name="cache"></param> /// <param name="aesCipher"></param> /// <param name="dexClient"></param> public AuthController( Service NeonSsoSessionProxyService, HttpMessageInvoker httpClient, IHttpForwarder forwarder, IDistributedCache cache, AesCipher aesCipher, DexClient dexClient, SessionTransformer sessionTransformer, DistributedCacheEntryOptions cacheOptions ) { this.NeonSsoSessionProxyService = NeonSsoSessionProxyService; this.httpClient = httpClient; this.forwarder = forwarder; this.cache = cache; this.cipher = aesCipher; this.transformer = sessionTransformer; this.dexClient = dexClient; this.cacheOptions = cacheOptions; }
public EncryptedMessage Encrypt(string messageText, int recieverId) { if (messageText == null) { throw new ArgumentException("Message text cannot be null"); } IContactModel receiverContact = _storageService.GetContacts().FirstOrDefault(c => c.Id == recieverId); if (receiverContact == null) { throw new ArgumentException("Contact with id of receiverId does not exist"); } EncryptedMessage encMsg = new EncryptedMessage(); AesCipher aes = new AesCipher(); // set initiazlization vector encMsg.Iv = FormatConverter.BytesToString64(aes.IV); // enccrypt message text symmetrically byte[] messageBytes = FormatConverter.StringToBytes(messageText); byte[] encryptedMessageBytes = aes.Encrypt(messageBytes); encMsg.Body = FormatConverter.BytesToString64(encryptedMessageBytes); // encrypt symmetric key with receivers public key string receiverPublicKey = receiverContact.PublicKey; RsaCipher rsa = new RsaCipher(receiverPublicKey); byte[] encryptedSymmetricKeyBytes = rsa.Encrypt(aes.Key); encMsg.SymmetricKey = FormatConverter.BytesToString64(encryptedSymmetricKeyBytes); // create digital signature of message text (using senders private key) string senderKeyPair = _storageService.GetUser().KeyPair; rsa = new RsaCipher(senderKeyPair); byte[] digitalSignatureBytes = rsa.CreateDigitalSignature(messageBytes); encMsg.DigitalSignature = FormatConverter.BytesToString64(digitalSignatureBytes); return(encMsg); }