安装: npm install crypto-js --save
在utils文件夹中新建secret.js文件,内容:
message: 需要加解密的文本
key: 加解密的秘钥
iv: 偏移量,最短8位数,ecb模式不需要此参数
在vue页面引入secret.js文件
vb.net code注意随机密码按钮在没用,调试时你自己输入密码,一定为8位,我是将文件存在D盘,你自己在修改一下,那个就很简单
Imports System.IO
Imports System.Security.Cryptography
Imports System.Text
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sSecretKey As String = Me.TextBox2.Text
EncryptFile(Me.TextBox1.Text, "D:\JMtest.txt", sSecretKey)
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim sSecretKey As String = Me.TextBox2.Text
DecryptFile("D:\JMtest.txt", "D:\Decrypted.txt", sSecretKey)
End Sub
Sub EncryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
Dim DES As New DESCryptoServiceProvider
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim desencrypt As ICryptoTransform = DES.CreateEncryptor()
Dim cryptostream As New CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write)
Dim byteArrayInput(fsInput.Length - 1) As Byte
fsInput.Read(byteArrayInput, 0, byteArrayInput.Length)
cryptostream.Write(byteArrayInput, 0, byteArrayInput.Length)
cryptostream.Close()
End Sub
Sub DecryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal sKey As String)
Dim DES As New DESCryptoServiceProvider
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
Dim fsread As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim desdecrypt As ICryptoTransform = DES.CreateDecryptor
Dim cryptostreamDecr As New CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read)
Dim fsDecrypted As New StreamWriter(sOutputFilename)
fsDecrypted.Write(New StreamReader(cryptostreamDecr, System.Text.ASCIIEncoding.Default).ReadToEnd)
fsDecrypted.Flush()
fsDecrypted.Close()
End Sub
Private Sub BtnChoose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnChoose.Click
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "txt files (*.txt)|*.txt"
OpenFileDialog1.ShowDialog()
If OpenFileDialog1.FileName "" Then
Me.TextBox1.Text = OpenFileDialog1.FileName
End If
End Sub
End Class
1)DES加密程序中,保存key和iv有两种做法
【Ⅰ】将key和iv“写死”在在程序中,一旦程序编译发布后,key和iv就无法改变
【Ⅱ】将保存key和iv保存在配置文件中,程序发布后,可以随时改变配置文件中的key和iv
为了增加安全性,在第二种方法中,配置文件中保存的不是key和iv的明文,而是用md5加密后的key和iv。这样,即使你的程序发布出去,别人也无法知道程序中真正使用的key和iv是什么,增加了安全性。
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)的作用是从配置文件取出加密的key和iv,然后用md5将解密,从而得到真正的key和iv
2)明白了1)后,第二个问题就容易理解了。