程式碼如下
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 WindowsFormsApplication7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Random r = new Random();
int[] ramdon3=new int[3];
//確保TextBox1的長度符合要求
while (textBox1.Text.Length < 13)
{
textBox1.Text+=" ";
}
//產生3組不同長度亂數
ramdon3[0] = r.Next(0, 9);
ramdon3[1]=r.Next(10,99);
ramdon3[2] = r.Next(1000, 9999);
string newString = ramdon3[0] + textBox1.Text.Substring(0, 3)+ramdon3[1]+textBox1.Text.Substring(3,5)+ramdon3[2] +textBox1.Text.Substring(8,5);
byte[] b=encrypt(newString,"abcd1234");
string encryptStr = Convert.ToBase64String(b);
label1.Text = encryptStr;
label2.Text = String.Empty;
}
//加密函式
private byte[] encrypt(string string_secretContent, string string_pwd)
{
//密碼轉譯一定都是用byte[] 所以把string都換成byte[]
byte[] byte_secretContent = Encoding.UTF8.GetBytes(string_secretContent);
byte[] byte_pwd = Encoding.UTF8.GetBytes(string_pwd);
//加解密函數的key通常都會有固定的長度 而使用者輸入的key長度不定 因此用hash過後的值當做key
MD5CryptoServiceProvider provider_MD5 = new MD5CryptoServiceProvider();
byte[] byte_pwdMD5 = provider_MD5.ComputeHash(byte_pwd);
//產生加密實體 如果要用其他不同的加解密演算法就改這裡(ex:AES)
RijndaelManaged provider_AES = new RijndaelManaged();
ICryptoTransform encrypt_AES = provider_AES.CreateEncryptor(byte_pwdMD5, byte_pwdMD5);
//output就是加密過後的結果
byte[] output = encrypt_AES.TransformFinalBlock(byte_secretContent, 0, byte_secretContent.Length);
return output;
}
//解密函式
private string decrypt(byte[] byte_ciphertext, string string_pwd)
{
//密碼轉譯一定都是用byte[] 所以把string都換成byte[]
byte[] byte_pwd = Encoding.UTF8.GetBytes(string_pwd);
//加解密函數的key通常都會有固定的長度 而使用者輸入的key長度不定 因此用hash過後的值當做key
MD5CryptoServiceProvider provider_MD5 = new MD5CryptoServiceProvider();
byte[] byte_pwdMD5 = provider_MD5.ComputeHash(byte_pwd);
//產生解密實體
RijndaelManaged provider_AES = new RijndaelManaged();
ICryptoTransform decrypt_AES = provider_AES.CreateDecryptor(byte_pwdMD5, byte_pwdMD5);
//string_secretContent就是解密後的明文
byte[] byte_secretContent = decrypt_AES.TransformFinalBlock(byte_ciphertext, 0, byte_ciphertext.Length);
string string_secretContent = Encoding.UTF8.GetString(byte_secretContent);
return string_secretContent;
}
private void button2_Click(object sender, EventArgs e)
{
//防呆
if (label1.Text == String.Empty)
return;
//解密
byte[] b = Convert.FromBase64String(label1.Text);
string newString = decrypt(b, "abcd1234");
//拆掉亂數
label2.Text = newString.Substring(1, 3) + newString.Substring(6, 5) + newString.Substring(15, 5);
}
}
}
執行畫面如下
第一次執行加密
執行解密
第2次執行加密
執行解密
AES加解密函式程式碼來源
http://blog.wahahajk.com/2008/08/c-demo-aes-3des.html
沒有留言:
張貼留言