在項(xiàng)目開發(fā)中减噪,常會遇到需要加密存儲信息的時(shí)候短绸,比如密碼。密碼一般不需要解密筹裕。
對于一些保密要求較高的內(nèi)容鸠按,也要求加密存儲,在需要查看的時(shí)候饶碘,再解密查看目尖。
為了對服務(wù)器和客戶端進(jìn)行身份驗(yàn)證,也會用到加密解密或身份id的判定等情況扎运。
一般單向加密(不可解密)的方法瑟曲,常見的有md5、sha1等豪治。
加密解密雙向需求的洞拨,常用base64。
對服務(wù)端负拟、客戶端等的驗(yàn)證烦衣,常用非對稱加密rsa。
為了實(shí)踐一下這些方法掩浙,先建立一個(gè)模板頁花吟。
模板頁面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Go Cryptography SHA1 MD5 BASE64 RSA</title>
</head>
<body>
加密解密等
<hr color="#e8e8e8" size="1">
<form id="cryptoform" action="../cryptography/" method="post">
md5 --> 原文: <textarea id="sourcecontentmd5" name="sourcecontentmd5" >{{.sourcecontentmd5}}</textarea><br>
md5 --> 密文: <textarea id="cryptocontentmd5" name="cryptocontentmd5" >{{.cryptocontentmd5}}</textarea><br>
sha1 --> 原文: <textarea id="sourcecontentsha1" name="sourcecontentsha1" >{{.sourcecontentsha1}}</textarea><br>
sha1 --> 密文: <textarea id="cryptocontentsha1" name="cryptocontentsha1" >{{.cryptocontentsha1}}</textarea><br>
<br><br><br>
<input type="radio" name="sc" value="0" {{.sc0}}>加密
<input type="radio" name="sc" value="1" {{.sc1}}>解密
<br>
base64 --> 原文: <textarea id="sourcecontentbase64" name="sourcecontentbase64" >{{.sourcecontentbase64}}</textarea><br>
base64 --> 密文: <textarea id="cryptocontentbase64" name="cryptocontentbase64" >{{.cryptocontentbase64}}</textarea><br>
rsa --> 原文: <textarea id="sourcecontentrsa" name="sourcecontentrsa" >{{.sourcecontentrsa}}</textarea><br>
rsa --> 密文: <textarea id="cryptocontentrsa" name="cryptocontentrsa" >{{.cryptocontentrsa}}</textarea><br>
<br><br>
<input id="submit" type="submit" value="-=提交=-"><br>
<label id="guid" >{{.guid}}</label>
</form>
</body>
</html>
路徑
http.HandleFunc("/cryptography/", processCryptographyHandler)
首先加密的時(shí)候,避免空白內(nèi)容厨姚,也為了避免加密內(nèi)容被猜測衅澈,在需要加密的原文前后分別加上一個(gè)散列值(hashHeader、hashFooter)谬墙。
這兩個(gè)值都是常量今布,一旦使用了就不能更改了,不然修改之前的密文就無法使用了拭抬。
const (
hashHeader = "Ji.anJ.un.bo" //散列值部默,設(shè)置后,若啟用則不要再改變了
hashFooter = "201410171695" //散列值造虎,設(shè)置后傅蹂,若啟用則不要再改變了
)
md5加密
md5加密,給出需要加密的原文累奈,在原文前后分別加上hashHeader贬派、hashFooter變量急但,然后再加密。返回加密后的密文搞乏。函數(shù)寫法如下
/**md5加密波桩,無解密*/
func JoelGetingMD5String(s string) string {
h := md5.New()
h.Write([]byte(hashHeader + s + hashFooter))
return hex.EncodeToString(h.Sum(nil))
}
sha1加密
sha1加密,給出需要加密的原文请敦,在原文前后分別加上hashHeader镐躲、hashFooter變量,然后再加密侍筛。返回加密后的密文萤皂。函數(shù)寫法如下
/**SHA1加密,無解密*/
func JoelGetingSHA1String(s string) string {
t := sha1.New()
t.Write([]byte(hashHeader + s + hashFooter))
return hex.EncodeToString(t.Sum(nil))
}
base64加密解密
使用base64可以實(shí)現(xiàn)對原文的加密匣椰,和對密文的解密裆熙。
首先需要一個(gè)64編碼表。我們編寫一個(gè)64個(gè)符號的編碼表出來禽笑。放在變量代碼塊中入录。
base64Table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
這個(gè)64位編碼表的64個(gè)元素不可以重復(fù)。加密解密編碼的基礎(chǔ)佳镜。當(dāng)然僚稿,你也可以試著改變這里的元素順序,或者用其他符號替換其中的元素蟀伸。(不要使用換行符號)
加解密前聲明一個(gè)NewEncoding蚀同,在加密解密中會用到。
var joelHashCoderBase64 = base64.NewEncoding(base64Table)
然后就是加密和解密函數(shù)了
/**base64加密*/
func JoelGetingBase64Encoding(s string) string {
var src []byte = []byte(hashHeader + s + hashFooter)
return string([]byte(joelHashCoderBase64.EncodeToString(src)))
}
/**base64解密*/
func JoelGetingBase64Decoding(s string) (string, error) {
var src []byte = []byte(s)
sourcecode, err := joelHashCoderBase64.DecodeString(string(src))
var source = string(sourcecode)
//去掉頭部
source1 := strings.Replace(source, hashHeader, "", -1)
//去掉尾部
source2 := strings.Replace(source1, hashFooter, "", len(source)-len(hashFooter)-1)
return source2, err
}
利用md5和base64也能夠生成guid啊掏,這在需要隨機(jī)一個(gè)id的時(shí)候很有用蠢络。
/**返回一個(gè)Guid值*/
func JoelGetGuid() string {
b := make([]byte, 48)
if _, err := io.ReadFull(rand.Reader, b); err != nil{
return ""
}
return JoelGetingMD5String(base64.URLEncoding.EncodeToString(b))
}
這些的調(diào)用相對要簡單些。
我們使用一個(gè)模板頁提交和顯示加解密的原文與密文脖律。由于有加密和解密2種操作谢肾,所以再增加一個(gè)當(dāng)前是加密還是解密的判斷。這個(gè)就用sc來承擔(dān)了小泉。
guid只是生成一下,相對就更簡單冕杠。
//加密解密相關(guān) SHA1 BASE64 MD5 RSA
func processCryptographyHandler(writer http.ResponseWriter, request *http.Request) {
var sourcecontentmd5 = request.FormValue("sourcecontentmd5")
var cryptocontentmd5 = request.FormValue("cryptocontentmd5")
var sourcecontentsha1 = request.FormValue("sourcecontentsha1")
var cryptocontentsha1 = request.FormValue("cryptocontentsha1")
var sourcecontentbase64 = request.FormValue("sourcecontentbase64")
var cryptocontentbase64 = request.FormValue("cryptocontentbase64")
var sourcecontentrsa = request.FormValue("sourcecontentrsa")
var cryptocontentrsa = request.FormValue("cryptocontentrsa")
var sc = request.FormValue("sc")
//md5加密
cryptocontentmd5 = JoelCryptography.JoelGetingMD5String(sourcecontentmd5)
//SHA1加密
cryptocontentsha1 = JoelCryptography.JoelGetingSHA1String(sourcecontentsha1)
if sc == "0"{
//加密
//--base64加密
cryptocontentbase64 = JoelCryptography.JoelGetingBase64Encoding(sourcecontentbase64)
}else {
//解密
//--base64解密
source64, err := JoelCryptography.JoelGetingBase64Decoding(cryptocontentbase64)
if err != nil{
sourcecontentbase64 = err.Error()
}else {
sourcecontentbase64 = source64
}
}
var jcrypto = make(map[string]string)
jcrypto["sourcecontentmd5"] = sourcecontentmd5
jcrypto["cryptocontentmd5"] = cryptocontentmd5
jcrypto["sourcecontentsha1"] = sourcecontentsha1
jcrypto["cryptocontentsha1"] = cryptocontentsha1
jcrypto["sourcecontentbase64"] = sourcecontentbase64
jcrypto["cryptocontentbase64"] = cryptocontentbase64
jcrypto["sourcecontentrsa"] = sourcecontentrsa
jcrypto["cryptocontentrsa"] = cryptocontentrsa
jcrypto["guid"] = JoelCryptography.JoelGetGuid()
if sc == "0"{
jcrypto["sc0"] = "checked"
jcrypto["sc1"] = ""
}else {
jcrypto["sc0"] = ""
jcrypto["sc1"] = "checked"
}
t, _ := template.ParseFiles("./JoelTempWeb/tmplCrypto.html")
t.ExecuteTemplate(writer, "tmplCrypto.html", jcrypto)
}