# 使用ASP密碼編譯演算法加密你的資料（二）

下面的代碼就是能夠同時實現這個功能的函數
Crypt.asp檔案
<%
Dim g_Key
Const g_CryptThis = "Now is the time for
all good men to come to the aid of their country."
Const g_KeyLocation = "c:\key.txt"

Response.Write "<p>ORIGINAL STRING: " & g_CryptThis & "<p>"
Response.Write "<p>KEY VALUE: " & g_Key & "<p>"
Response.Write "<p>ENCRYPTED CYPHERTEXT: " & EnCrypt(g_CryptThis) & "<p>"
Response.Write "<p>DECRYPTED CYPHERTEXT: " & DeCrypt(EnCrypt(g_CryptThis)) & "<p>"

Function EnCrypt(strCryptThis)
Dim strChar, iKeyChar, iStringChar, I
for I = 1 to Len(strCryptThis)
iKeyChar = Asc(mid(g_Key,I,1))
iStringChar = Asc(mid(strCryptThis,I,1))
' *** uncomment below to encrypt with addition,
' iCryptChar = iStringChar + iKeyChar
iCryptChar = iKeyChar Xor iStringChar
strEncrypted = strEncrypted & Chr(iCryptChar)
next
EnCrypt = strEncrypted
End Function

Function DeCrypt(strEncrypted)
Dim strChar, iKeyChar, iStringChar, I
for I = 1 to Len(strEncrypted)
iKeyChar = (Asc(mid(g_Key,I,1)))
iStringChar = Asc(mid(strEncrypted,I,1))
' *** uncomment below to decrypt with subtraction
' iDeCryptChar = iStringChar - iKeyChar
iDeCryptChar = iKeyChar Xor iStringChar
strDecrypted = strDecrypted & Chr(iDeCryptChar)
next
DeCrypt = strDecrypted
End Function

Dim keyFile, fso, f
set fso = Server.CreateObject("Scripting.FileSystemObject")
set f = fso.GetFile(strFileName)
set ts = f.OpenAsTextStream(1, -2)

Do While not ts.AtEndOfStream
Loop

End Function

%>
在Crypt.asp中我們首先從密鑰檔案中得到密鑰值，然後從這段密鑰中截取和我們需要加密的明文同樣長度的密鑰。然後使用一個簡單的異或操作將明文和密鑰進行運算，那麼得到的結果就是加密後的密文了。過程很簡單的。由於是使用了異或操作，所以解密將非常簡單，只要使用同樣的金鑰組密文再次進行異或操作就能夠解密了。在上面介紹的基礎上，你可以少加改動，就可以使用同樣的方法加密一個檔案。唯一需要注意的是，對於一個二進位檔案，你需要做一些完整性檢查以保證轉換回來

Vernam密碼是由Gilbert Vernam (他是AT&T的工程師)在1918年發明的。這是一種使用異或方法進行加密解密的方法。

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD