using Falcon.SugarApi.Encryption;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Text;
namespace Falcon.SugarApi.Test.Encryption
{
///
/// RSA测试类
///
[TestClass]
public class EncryptionTest
{
///
/// 测试公钥、秘钥生成,加密解密
///
[TestMethod("DES测试")]
public void DESTest() {
var config = new DESConfig() { };
IDESEncryption r = new DESProvider(config);
var k = r.GenerateKey();
//var bs = Encoding.UTF8.GetBytes(mingw);
//var a1 = Convert.ToBase64String(bs);
//var a2 = Convert.FromBase64String(a1);
//Assert.AreEqual(bs.Length, a2.Length);
for (int i = 0; i < 1000; i++) {
var mingw = GenerateStr();
Console.WriteLine(mingw);
var p = new DESProvider(config);
var miwen = p.Encrypt(k, mingw);
var p1 = new DESProvider(config);
var mingw1 = p1.Decrypt(k, miwen);
Assert.AreEqual(mingw, mingw1, "解密后明文不同");
}
}
///
/// 测试公钥、秘钥生成,加密解密
///
[TestMethod("AES测试")]
public void AESTest() {
var config = new AESConfig() { };
IAESEncryption r = new AESProvider(config);
var k = r.GenerateKey();
//测试字符串加密
for (int i = 0; i < 1000; i++) {
var mingw = GenerateStr();
//Console.WriteLine(mingw);
var p = new AESProvider(config);
var miwen = p.Encrypt(k, mingw);
var p1 = new AESProvider(config);
var mingw1 = p1.Decrypt(k, miwen);
Assert.AreEqual(mingw, mingw1, "解密后明文不同");
}
//测试对象加密
var obj = new TestObj { Id = 1, Name = "abc" };
var ma = r.Encrypt(k, obj);
Assert.IsNotNull(ma);
var obj2 = r.Decrypt(k, ma);
Assert.IsNotNull(obj2);
Assert.IsTrue(obj.Id == obj2.Id);
Assert.IsTrue(obj.Name == obj2.Name);
Assert.ThrowsException(() => r.Encrypt(k, null));
Assert.ThrowsException(() => r.Encrypt(null, obj));
Assert.ThrowsException(() => r.Decrypt(k, null));
Assert.ThrowsException(() => r.Decrypt(null, ma));
}
///
/// 生成随机长度,由字符表内字符组成的字符串
///
///
private string GenerateStr() {
var chars = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789,.!/*\";
var r = new Random();
var len = r.Next(100);
var sb = new StringBuilder(len);
for (int i = 0; i < len; i++) {
sb.Append(chars[r.Next(0, chars.Length)]);
}
return sb.ToString();
}
class TestObj
{
public int Id { get; set; }
public string Name { get; set; }
}
}
}