You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

109 lines
2.3 KiB
Go

6 years ago
// Package gnutls is a gnutls binding for golang.
/*
7 years ago
a limit set of api is supported.
TLS api is very similar to crypto/tls on standard library.
TLS client example:
addr := "127.0.0.1:9443"
7 years ago
c, err := gnutls.Dial("tcp", addr, &gnutls.Config{ServerName: "localhost",InsecureSkipVerify: true})
7 years ago
if err != nil {
log.Fatal("gnutls dial ", err)
7 years ago
}
defer c.Close()
data := "hello, world"
if _, err = c.Write([]byte(data)); err != nil {
log.Fatal("gnutls write ", err)
7 years ago
}
buf := make([]byte, 100)
n, err := c.Read(buf)
if err != nil {
log.Fatal("gnutls read ", err)
7 years ago
}
TLS Server example:
6 years ago
cert, err := gnutls.LoadX509KeyPair("testdata/server/crt", "testdata/server.key")
if err != nil{
// handle error
}
7 years ago
l, err := gnults.Listen("tcp", "127.0.0.1:9443", &gnutls.Config{
6 years ago
Certificates: []*gnutls.Certificate{cert}})
7 years ago
if err != nil {
6 years ago
// handle error
7 years ago
}
defer l.Close()
for {
c, err := l.Accept()
if err != nil {
log.Println("gnutls accept ", err)
break
}
log.Println("accept connection from ", c.RemoteAddr())
go func(c net.Conn) {
defer c.Close()
buf := make([]byte, 4096)
for {
n, err := c.Read(buf[0:])
if err != nil {
log.Println("gnutls read ", err)
break
}
if _, err := c.Write(buf[:n]); err != nil {
log.Println("gnutls write ", err)
break
}
}
}(c)
}
AES encrypt/decrypt example:
key := []byte("0123456789abcdef")
iv := []byte("abcdefg123456789")
c, err := gnutls.NewCipher(gnutls.GNUTLS_CIPHER_AES_128_CBC, key, iv)
if err != nil {
log.Fatal(err)
7 years ago
}
defer c.Close()
c1, err := gnutls.NewCipher(gnutls.GNUTLS_CIPHER_AES_128_CBC, key, iv)
if err != nil {
log.Fatal(err)
7 years ago
}
defer c1.Close()
data := []byte("1234012121212121")
if c == nil {
log.Fatal("new ciphoer failed")
7 years ago
}
// encrypt
6 years ago
dst := make([]byte, len(data))
err := c.Encrypt(dst, data)
7 years ago
if err != nil {
log.Fatal("encrypt failed", err)
7 years ago
}
// decrypt
6 years ago
data1 := make([]byte, len(data))
err := c1.Decrypt(data1, cdata)
7 years ago
if err != nil {
log.Fatal("decrypt failed", err)
7 years ago
}
Hash example:
7 years ago
h := gnutls.NewHash(gnutls.GNUTLS_HASH_SHA512)
7 years ago
defer h.Close()
data := []byte("1234")
h1 := h.Sum(data)
*/
package gnutls