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为自己提供安全保障。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值