初衷
之前根据需要开发了一款*《全局钩子——代码翻译小工具》*的文章,后续收到了一些有建议性的反馈和在使用中的一些感受,所以做了一些升级。
README!!!
因为:
使用时会因为网络问题出现卡顿;
百度翻译引擎调整政策为每月5万字;
使用时会重复翻译相同内容,照成翻译资源浪费;
所以:
使用了线程去处理翻译过程,避免卡顿;
添加了腾讯机器翻译引擎,并添加ID和Key输入窗口(并在本地做了加密处理),可使其使用自己的翻译源;
添加了一些逻辑判断,检测到相同内容的翻译后,会从本地取出,减少浪费;
使用:
使用过程和之前一样,自定义的SourceId和SourceKey可以到百度或腾讯开发者网站自己申请,(当然也可以先用我的,不过超过了免费限制后,我可不会缴费。。。
攻坚
AES加密:(需要注意的密钥向量的个数和密钥长度要一致)
// An highlighted block
public class AESLock
{
#region single
private static object syncObj = new object();
private static AESLock instance = null;
private AESLock()
{ }
public static AESLock GetInstance()
{
lock (syncObj)
{
if (instance == null)
{
instance = new AESLock();
}
}
return instance;
}
#endregion
#region body
//测试密钥向量
private readonly static byte[] MY_IV = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07
};
//测试密钥
private const string publicKey = "whttranslatelock";
#endregion
#region 成员
/// <summary>
/// AES加密算法
/// </summary>
/// <param name="plainText">明文字符串</param>
/// <returns>返回加密后的密文字节数组</returns>
public string Encrypt(string text)
{
byte[] bytes = Encoding.UTF8.GetBytes(text);
bytes = Encrypt(bytes);
string res = Convert.ToBase64String(bytes);
return res;
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="cipherText">密文字节数组</param>
/// <returns>返回解密后的字符串</returns>
public string Decrypt(string text)
{
byte[] bytes = Convert.FromBase64String(text);
bytes = Decrypt(bytes);
string res = Encoding.UTF8.GetString(bytes);
//去除尾部自动填充的无效字符
res = res.TrimEnd('\0');
return res;
}
#endregion
#region 成员
public byte[] Encrypt(byte[] data)
{
//分组加密算法
SymmetricAlgorithm des = Rijndael.Create();
//设置密钥及密钥向量
des.Key = Encoding.UTF8.GetBytes(publicKey);
des.IV = MY_IV;
byte[] cipherBytes;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(data, 0, data.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();//得到加密后的字节数组
//cs.Close();
}
//ms.Close();
}
return cipherBytes;
}
public byte[] Decrypt(byte[] data)
{
//分组加密算法
SymmetricAlgorithm des = Rijndael.Create();
//设置密钥及密钥向量
des.Key = Encoding.UTF8.GetBytes(publicKey);
des.IV = MY_IV;
byte[] decryptBytes = new byte[data.Length];
using (MemoryStream ms = new MemoryStream(data))
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, 0, decryptBytes.Length);
//cs.Close();
}
//ms.Close();
}
return decryptBytes;
}
#endregion
}
总结
源码地址:https://github.com/Dream9898123/Translate.git
开盖及食:链接: https://pan.baidu.com/s/1dYPbMZWr4lAUqyBmjGhJZw 提取码: a355