Exemplo n.º 1
0
        public static EncryptedDiaryRecord EncryptRecord(DiaryRecord record, RSACryptoServiceProvider rsa)
        {
            var rij = Rijndael.Create();

            rij.KeySize = 256;
            rij.GenerateKey();
            rij.GenerateIV();

            var encryptedRecord = new EncryptedDiaryRecord();

            var header = new MemoryStream();

            header.Write(rij.Key, 0, rij.Key.Length);
            header.Write(rij.IV, 0, rij.IV.Length);

            encryptedRecord.Header = rsa.Encrypt(header.ToArray(), false);

            var encryptedBodyStream = new MemoryStream();

            using (var body = new CryptoStream(encryptedBodyStream, rij.CreateEncryptor(), CryptoStreamMode.Write))
            {
                Serializer.Serialize(body, record);
            }

            encryptedRecord.Body = encryptedBodyStream.ToArray();

            return(encryptedRecord);
        }
Exemplo n.º 2
0
        public DiaryRecord ReadPrevious()
        {
            var reader = new BinaryReader(_fileStream);

            _fileStream.Seek(-4, SeekOrigin.Current);
            var messageLength = reader.ReadInt32();

            _fileStream.Seek(-(messageLength + 4), SeekOrigin.Current);
            var recordBytes = reader.ReadBytes(messageLength);

            if (recordBytes.Length != messageLength)
            {
                throw new InvalidDataException("The record could not be read");
            }

            var encryptedDiaryRecord = new EncryptedDiaryRecord();

            var headerLength = _rsa.KeySize / 8;

            encryptedDiaryRecord.Header = new byte[headerLength];
            encryptedDiaryRecord.Body   = new byte[recordBytes.Length - headerLength];

            Buffer.BlockCopy(recordBytes, 0, encryptedDiaryRecord.Header, 0, headerLength);
            Buffer.BlockCopy(recordBytes, headerLength, encryptedDiaryRecord.Body, 0, encryptedDiaryRecord.Body.Length);

            var record = EncryptionHelper.DecryptEntry(encryptedDiaryRecord, _rsa);

            _fileStream.Seek(-(messageLength + 4), SeekOrigin.Current);

            return(record);
        }
Exemplo n.º 3
0
        public static DiaryRecord DecryptEntry(EncryptedDiaryRecord record, RSACryptoServiceProvider rsa)
        {
            var decryptedChunk = rsa.Decrypt(record.Header, false);

            var key = new byte[32];
            var iv  = new byte[16];

            var rij = Rijndael.Create();

            Buffer.BlockCopy(decryptedChunk, 0, key, 0, 32);
            Buffer.BlockCopy(decryptedChunk, 32, iv, 0, 16);

            using (var cs = new CryptoStream(new MemoryStream(record.Body), rij.CreateDecryptor(key, iv), CryptoStreamMode.Read))
            {
                return(Serializer.Deserialize <DiaryRecord>(cs));
            }
        }