public void EnhancedMemoryStream_Int32() { var es = new EnhancedMemoryStream(); es.WriteInt32(0); es.WriteInt32(65121); es.WriteInt32(0x12345678); es.Seek(0, SeekOrigin.Begin); Assert.AreEqual(0, es.ReadInt32()); Assert.AreEqual(65121, es.ReadInt32()); Assert.AreEqual(0x12345678, es.ReadInt32()); }
/// <summary> /// Encrypts the keys using the symmetric key passed. /// </summary> /// <returns>The encrypted key chain.</returns> public byte[] Encrypt(SymmetricKey key) { using (var ms = new EnhancedMemoryStream()) { ms.WriteInt32(Magic); ms.WriteInt32(keys.Count); foreach (string privateKey in keys.Values) { ms.WriteString16(privateKey); } ms.WriteBytesNoLen(Crypto.GetSalt8()); return(Crypto.Encrypt(ms.ToArray(), key)); } }
/// <summary> /// Called when the server receives an unserialized request. /// </summary> /// <param name="requestBytes">The serialized request.</param> private void OnRequest(byte[] requestBytes) { try { using (var input = new EnhancedMemoryStream(requestBytes)) { int typeCode = input.ReadInt32(); SharedMemMessage request; SharedMemMessage response; if (typeCode < 0) { request = new SharedMemErrorMessage(); } else { request = messageFactory.Create(typeCode); } request.InternalReadFrom(input); request.ReadFrom(input); try { response = requestHandler(request); if (response == null) { throw new NullReferenceException("Server request handler returned a NULL response message."); } } catch (Exception e) { response = new SharedMemErrorMessage(); response.InternalError = string.Format("{0}: {1}", e.GetType().FullName, e.Message); } response.InternalRequestId = request.InternalRequestId; response.InternalClientInbox = request.InternalClientInbox; using (var output = new EnhancedMemoryStream(response.SerializedCapacityHint)) { output.WriteInt32(response.TypeCode); response.InternalWriteTo(output); response.WriteTo(output); // This call is synchronous but should execute very quickly (microseconds). outbox.Send(response.InternalClientInbox, output.ToArray()); } } } catch (Exception e) { SysLog.LogException(e); } }
/// <summary> /// Casually encrypts the old and new password to be used to during /// a change password operation. /// </summary> /// <param name="originalPassword">The original password.</param> /// <param name="newPassword">The new password.</param> /// <returns>The encrypted password change parameters.</returns> /// <remarks> /// <note> /// This method is designed to provide a low level of security during development /// and testing, when the overhead of configuring SSL certificates is not worth /// the trouble. Do not rely on this method as your only mechanism for securing /// credentials during transmission in production environments. /// </note> /// </remarks> public static byte[] EncryptPasswordChange(string originalPassword, string newPassword) { using (var ms = new EnhancedMemoryStream(256)) { ms.WriteInt32(CredentialMagic); ms.WriteString16(originalPassword); ms.WriteString16(newPassword); return(EncryptWithSalt8(ms.ToArray(), credentialsKey)); } }
/// <summary> /// Generates a request signature using a shared <see cref="SymmetricKey" /> /// for request arguments as well as the current time. /// </summary> /// <param name="sharedKey">The shared <see cref="SymmetricKey" />.</param> /// <param name="args">The request argument collection.</param> /// <returns>The base-64 encoded signature.</returns> public static string Generate(SymmetricKey sharedKey, ArgCollection args) { using (var ms = new EnhancedMemoryStream(512)) { ms.WriteBytesNoLen(Crypto.GetSalt8()); ms.WriteInt32(Magic); ms.WriteInt64(DateTime.UtcNow.Ticks); ms.WriteBytesNoLen(ComputeHash(args, null)); return(Convert.ToBase64String(Crypto.Encrypt(ms.ToArray(), sharedKey))); } }
/// <summary> /// Casually encrypts authentication <see cref="Credentials" /> into a byte /// array using using the <see cref="CredentialsKey" />. /// </summary> /// <param name="credentials">The <see cref="Credentials" />.</param> /// <returns>The encrypted credentials.</returns> /// <remarks> /// <note> /// This method is designed to provide a low level of security during development /// and testing, when the overhead of configuring SSL certificates is not worth /// the trouble. Do not rely on this method as your only mechanism for securing /// credentials during transmission in production environments. /// </note> /// </remarks> public static byte[] EncryptCredentials(Credentials credentials) { using (var ms = new EnhancedMemoryStream(256)) { ms.WriteInt32(CredentialMagic); ms.WriteString16(credentials.Realm); ms.WriteString16(credentials.Account); ms.WriteString16(credentials.Password); return(EncryptWithSalt8(ms.ToArray(), credentialsKey)); } }
/// <summary> /// Performs a secure symmetric encryption including cryptographic salt, padding, and /// data validation. /// </summary> /// <param name="symmetricKey">The symmetric algorithm arguments.</param> /// <param name="plainText">The unencrypted data.</param> /// <param name="paddedSize">Specifies the minimum padded size of the encrypted content.</param> /// <returns>The encrypted result.</returns> public static byte[] Encrypt(SymmetricKey symmetricKey, byte[] plainText, int paddedSize) { EnhancedMemoryStream output = new EnhancedMemoryStream(Math.Max(plainText.Length, paddedSize) + 512); EnhancedMemoryStream ms = new EnhancedMemoryStream(512); BlockEncryptor encryptor = new BlockEncryptor(symmetricKey); try { // Write header fields output.WriteInt32(Magic); output.WriteInt32(0); // Write encrypted contents ms.WriteInt32(Magic); ms.WriteBytesNoLen(Crypto.GetSalt8()); ms.WriteBytes32(plainText); for (int i = plainText.Length; i < paddedSize; i++) { ms.WriteByte((byte)i); // Padding bytes } output.WriteBytes32(encryptor.Encrypt(ms.ToArray())); // That's it, we're done. return(output.ToArray()); } finally { if (encryptor != null) { encryptor.Dispose(); } output.Close(); ms.Close(); } }
/// <summary> /// Asynchronously submits a <see cref="SharedMemMessage"/> request message to the server /// and waits for and returns the response <see cref="SharedMemMessage"/>. /// </summary> /// <param name="request">The request message.</param> /// <param name="timeout">The optional timeout to override the <see cref="Timeout"/> property. /// </param> /// <returns>The response <see cref="SharedMemMessage"/>.</returns> public Task <SharedMemMessage> CallAsync(SharedMemMessage request, TimeSpan?timeout = null) { if (request == null) { throw new ArgumentNullException("request"); } if (request.InternalRequestId != Guid.Empty) { throw new InvalidOperationException("Cannot reuse a [SharedMemMessage] request instance previously submitted for a call operation."); } request.InternalRequestId = Guid.NewGuid(); request.InternalClientInbox = this.ClientName; if (!timeout.HasValue) { timeout = this.Timeout; } var operation = new PendingOperation(request, new TaskCompletionSource <SharedMemMessage>(), stopwatch.Elapsed + timeout.Value); lock (syncLock) { pendingOperations.Add(request.InternalRequestId, operation); } try { using (var output = new EnhancedMemoryStream(request.SerializedCapacityHint)) { output.WriteInt32(request.TypeCode); request.InternalWriteTo(output); request.WriteTo(output); // This call is synchronous but should execute very quickly (microseconds). outbox.Send(ServerName, output.ToArray()); } } catch (Exception e) { lock (syncLock) { pendingOperations.Remove(operation.RequestMessage.InternalRequestId); } operation.Tcs.TrySetException(e); } return(operation.Tcs.Task); }
/// <summary> /// Encrypts authentication <see cref="Credentials" /> into a byte /// array using the specified public asymmetric public key and /// algorithm. /// </summary> /// <param name="credentials">The <see cref="Credentials" />.</param> /// <param name="algorithm">The encryption algorithm.</param> /// <param name="key">The public key.</param> /// <returns>The encrypted credentials.</returns> /// <remarks> /// The current implementation supports only the "RSA" provider. /// </remarks> public static byte[] EncryptCredentials(Credentials credentials, string algorithm, string key) { using (var ms = new EnhancedMemoryStream(256)) { ms.WriteInt32(Crypto.CredentialMagic); ms.WriteString16(credentials.Realm); ms.WriteString16(credentials.Account); ms.WriteString16(credentials.Password); ms.WriteBytesNoLen(Crypto.GetSalt4()); return(Encrypt(algorithm, key, ms.ToArray())); } }
public void EnhancedMemoryStream_VerifyBufLength() { var es = new EnhancedMemoryStream(); es.WriteInt16(5000); es.Seek(0, SeekOrigin.Begin); try { es.ReadBytes16(); Assert.Fail(); } catch { } es.Seek(0, SeekOrigin.Begin); try { es.ReadString16(); Assert.Fail(); } catch { } es.Seek(0, SeekOrigin.Begin); es.WriteInt32(500000); try { es.ReadBytes32(); Assert.Fail(); } catch { } es.Seek(0, SeekOrigin.Begin); try { es.ReadString32(); Assert.Fail(); } catch { } }
/// <summary> /// Encrypts a byte array using a combination of an asymmetric RSA key and the /// specified symmetric encryption algorithm and a one-time key generated by /// the method. /// </summary> /// <param name="rsaKey">The encrypting RSA key as XML or as a secure key container name.</param> /// <param name="plainText">The data to be encrypted.</param> /// <param name="algorithm">The symmetric encryption algorithm name.</param> /// <param name="keySize">The one-time symmetric key size to generate in bits.</param> /// <param name="paddedSize">Specifies the minimum padded size of the encrypted content.</param> /// <param name="symmetricKey">Returns as the symmetric encryption algorithm arguments.</param> /// <returns>The encrypted result.</returns> /// <remarks> /// <para> /// Note that applications should take some care to ensure that the <paramref name="symmetricKey" /> /// value return is disposed so that the symmetric encryption key will be cleared. /// </para> /// <para> /// The current supported cross platform encryption algorithms /// are: "DES", "RC2", "TripleDES", and "AES" (Rijndael). /// </para> /// </remarks> /// <exception cref="ArgumentException">Thrown if the requested encryption algorithm is unknown.</exception> public static byte[] Encrypt(string rsaKey, byte[] plainText, string algorithm, int keySize, int paddedSize, out SymmetricKey symmetricKey) { EnhancedMemoryStream output = new EnhancedMemoryStream(Math.Max(plainText.Length, paddedSize) + 512); EnhancedMemoryStream ms = new EnhancedMemoryStream(512); BlockEncryptor encryptor = null; byte[] symKey; byte[] symIV; Crypto.GenerateSymmetricKey(algorithm, keySize, out symKey, out symIV); encryptor = new BlockEncryptor(algorithm, symKey, symIV); symmetricKey = new SymmetricKey(algorithm, (byte[])symKey.Clone(), (byte[])symIV.Clone()); try { // Write header fields output.WriteInt32(Magic); output.WriteInt32(0); // Write encryption Info ms.WriteString16(algorithm); ms.WriteBytes16(symKey); ms.WriteBytes16(symIV); ms.WriteBytesNoLen(Crypto.GetSalt8()); output.WriteBytes16(AsymmetricCrypto.Encrypt(CryptoAlgorithm.RSA, rsaKey, ms.ToArray())); // Write encrypted contents ms.SetLength(0); ms.WriteInt32(Magic); ms.WriteBytesNoLen(Crypto.GetSalt8()); ms.WriteBytes32(plainText); for (int i = plainText.Length; i < paddedSize; i++) { ms.WriteByte((byte)i); // Padding bytes } output.WriteBytes32(encryptor.Encrypt(ms.ToArray())); // That's it, we're done. return(output.ToArray()); } finally { if (symKey != null) { Array.Clear(symKey, 0, symKey.Length); } if (symIV != null) { Array.Clear(symIV, 0, symIV.Length); } if (encryptor != null) { encryptor.Dispose(); } output.Close(); ms.Close(); } }