using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
namespace AIPractice.Shared.Labels
{
public class LabelContainer
{
private const string _encryptKey = "VINNO123";
private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
///
/// All labels included in this container.
///
public IList Labels { get; } = new List();
public static LabelContainer FromXml(string xmlContent)
{
var container = new LabelContainer();
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(xmlContent)))
{
using (var r = XmlReader.Create(ms))
{
r.Read();
while (r.NodeType == XmlNodeType.Element && r.Name == nameof(RootLabel) ||
r.ReadToDescendant(nameof(RootLabel)))
{
container.Labels.Add(RootLabel.FromXml(r.ReadOuterXml()));
}
return container;
}
}
}
public string ToXml()
{
var sb = new StringBuilder();
sb.Append($"<{nameof(LabelContainer)}>");
foreach (var label in Labels)
{
sb.Append(label.ToXml());
}
sb.Append($"{nameof(LabelContainer)}>");
return sb.ToString();
}
private static byte[] Encode(string data)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(_encryptKey.Substring(0, 8));
byte[] rgbIV = Keys;
byte[] inputByteArray = Encoding.UTF8.GetBytes(data);
DESCryptoServiceProvider dcsp = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, dcsp.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
}
}
catch
{
return new byte[0];
}
}
private static string Decode(byte[] data)
{
try
{
byte[] rgbKey = Encoding.UTF8.GetBytes(_encryptKey);
byte[] rgbIV = Keys;
byte[] inputByteArray = data;
DESCryptoServiceProvider dcsp = new DESCryptoServiceProvider();
using (MemoryStream ms = new MemoryStream())
{
using (var cs = new CryptoStream(ms, dcsp.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Encoding.UTF8.GetString(ms.ToArray());
}
}
}
catch
{
return string.Empty;
}
}
public void Save(string fileName)
{
var ext = Path.GetExtension(fileName);
if (ext.ToLower() == ".xml")
{
File.WriteAllText(fileName, ToXml());
}
else
{
var data = Encode(ToXml());
File.WriteAllBytes(fileName, data);
}
}
public static LabelContainer Open(string fileName)
{
var ext = Path.GetExtension(fileName);
if (ext.ToLower() == ".xml")
{
return FromXml(File.ReadAllText(fileName));
}
else
{
var data = File.ReadAllBytes(fileName);
var content = Decode(data);
return FromXml(content);
}
}
}
}