Falcon.SugarApi/Falcon.SugarApi.Test/Encryption/EncryptionTest.cs

100 lines
3.3 KiB
C#

using Falcon.SugarApi.Encryption;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Text;
namespace Falcon.SugarApi.Test.Encryption
{
/// <summary>
/// RSA测试类
/// </summary>
[TestClass]
public class EncryptionTest
{
/// <summary>
/// 测试公钥、秘钥生成,加密解密
/// </summary>
[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, "解密后明文不同");
}
}
/// <summary>
/// 测试公钥、秘钥生成,加密解密
/// </summary>
[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<TestObj>(k, ma);
Assert.IsNotNull(obj2);
Assert.IsTrue(obj.Id == obj2.Id);
Assert.IsTrue(obj.Name == obj2.Name);
Assert.ThrowsException<ArgumentNullException>(() => r.Encrypt<TestObj>(k, null));
Assert.ThrowsException<ArgumentNullException>(() => r.Encrypt<TestObj>(null, obj));
Assert.ThrowsException<ArgumentNullException>(() => r.Decrypt<TestObj>(k, null));
Assert.ThrowsException<ArgumentNullException>(() => r.Decrypt<TestObj>(null, ma));
}
/// <summary>
/// 生成随机长度,由字符表内字符组成的字符串
/// </summary>
/// <returns></returns>
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; }
}
}
}