日期:2014-05-17 浏览次数:21468 次
using System;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using Snail.Common.Extensions;
namespace Snail.Common.Security
{
public class EncryptionService:IEncryptionService
{
public byte[] Decode(byte[] encodedData)
{
using (var symmetricAlgorithm = CreateSymmetricAlgorithm())
{
using (var hashAlgorithm = CreateHashAlgorithm())
{
var iv = new byte[symmetricAlgorithm.BlockSize / 8];
var signature = new byte[hashAlgorithm.HashSize / 8];
var data = new byte[encodedData.Length - iv.Length - signature.Length];
Array.Copy(encodedData, 0, iv, 0, iv.Length);
Array.Copy(encodedData, iv.Length, data, 0, data.Length);
Array.Copy(encodedData, iv.Length + data.Length, signature, 0, signature.Length);
// validate the signature
var mac = hashAlgorithm.ComputeHash(iv.Concat(data).ToArray());
if (!mac.SequenceEqual(signature))
{
// message has been tampered
throw new ArgumentException();
}
symmetricAlgorithm.IV = iv;
using (var ms = new M