go语言安全编程

安全编程

哈希函数

package main
import(
    "fmt"
    "crypto/sha1"
    "crypto/md5"
)
func main(){
    TestString:="Hi,pandaman!"
    Md5Inst:=md5.New()
    Md5Inst.Write([]byte(TestString))
    Result:=Md5Inst.Sum([]byte(""))
    fmt.Printf("%x\n\n",Result)
    Sha1Inst:=sha1.New()
    Sha1Inst.Write([]byte(TestString))
    Result=Sha1Inst.Sum([]byte(""))
    fmt.Printf("%x\n\n",Result)
}

这个程序的执行结果为:

$ go run hash1.go
b08dad36bde5f406bdcfb32bfcadbb6b
00aa75c24404f4c81583b99b50534879adc3985d

对文件内容计算SHA1:

package main
import (
    "io"
    "fmt"
    "os"
    "crypto/md5"
    "crypto/sha1"
)
func main() {
    TestFile := "123.txt"
    infile, inerr := os.Open(TestFile)
    if inerr == nil {
        md5h := md5.New()
        io.Copy(md5h, infile)
        fmt.Printf("%x %s\n",md5h.Sum([]byte("")), TestFile)
        sha1h := sha1.New()
        io.Copy(sha1h, infile)
        fmt.Printf("%x %s\n",sha1h.Sum([]byte("")), TestFile)
    } else {
        fmt.Println(inerr)
        os.Exit(1)
    }
}

加密通信

支持HTTPS的Web服务器

package main
import (
    "fmt"
    "net/http"
)
const SERVER_PORT = 8080
const SERVER_DOMAIN = "localhost"
const RESPONSE_TEMPLATE = "hello"
func rootHandler(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/html")
    w.Header().Set("Content-Length", fmt.Sprint(len(RESPONSE_TEMPLATE)))
    w.Write([]byte(RESPONSE_TEMPLATE))
}
func main() {
    http.HandleFunc(fmt.Sprintf("%s:%d/", SERVER_DOMAIN, SERVER_PORT), rootHandler)
    http.ListenAndServeTLS(fmt.Sprintf(":%d", SERVER_PORT), "rui.crt", "rui.key", nil)
}

支持HTTPS的文件服务器:

package main
import (
    "net/http"
)
func main(){
    h := http.FileServer(http.Dir("."))
    http.ListenAndServeTLS(":8001", "rui.crt", "rui.key", h)
}

SSL/TLS协议只能运行于TCP之上,不能在UDP上工作,且SSL/TLS位于TCP与应用层协议之间,因此所有基于TCP的应用层协议都可以透明地使用SSL/TLS为自己提供安全保障。

你可能感兴趣的:(go)