我是C#的新手,在尝试简单地加密和解密一个简单的字符串时遇到了加密异常。对于密钥,我使用短语" Pyber"的SHA512哈希。这似乎是问题,因为密钥(Pyber)不是合适的大小。
在调试时,我得到了这个:
未处理的类型' System.Security.Cryptography.CryptographicException'发生在mscorlib.dll
附加信息:指定密钥不是此算法的有效大小。
感谢任何帮助。
编辑:现在尝试使用MD5,enryption工作得非常好,而解密仍然会引发相同的异常。using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
namespace ENC_1
{
public partial class main : Form
{
public main()
{
InitializeComponent();
}
string hash = "Pyber";
private void button1_MouseHover(object sender, EventArgs e)
{
//Don't do anything
}
private void btn_encrypt_Click(object sender, EventArgs e)
{
byte[] data = UTF8Encoding.UTF8.GetBytes(txt_input.Text);
using (SHA512CryptoServiceProvider SHA512 = new SHA512CryptoServiceProvider())
{
byte[] keys = SHA512.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider() { Key = keys, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 })
{
ICryptoTransform transform = tripDes.CreateEncryptor();
byte[] results = transform.TransformFinalBlock(data, 0, data.Length);
txt_encrypt.Text = Convert.ToBase64String(results, 0, results.Length);
}
}
}
private void btn_decrypt_Click(object sender, EventArgs e)
{
byte[] data = Convert.FromBase64String(txt_encrypt.Text);
using (SHA512CryptoServiceProvider SHA512 = new SHA512CryptoServiceProvider())
{
byte[] keys = SHA512.ComputeHash(UTF8Encoding.UTF8.GetBytes(hash));
using (TripleDESCryptoServiceProvider tripDes = new TripleDESCryptoServiceProvider() { Key = keys, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 })
{
ICryptoTransform transform = tripDes.CreateDecryptor();
byte[] results = transform.TransformFinalBlock(data, 0, data.Length);
txt_encrypt.Text = UTF8Encoding.UTF8.GetString(results);
}
}
}
}
}
答案 0 :(得分:0)
根据.Net支持文档,TripleDes接受密钥between 128 and 192 bits,即16和24个字符。
SHA512生成64个字符键;我建议你尝试将你的密钥截断为24个字符,
byte[] newKey= new byte[24];
Array.Copy(keys, newKey, newKey.Length);
答案 1 :(得分:0)
问题已解决。将散列算法恢复为MD5结果是有效的。