openssl

package module
v0.0.0-...-f4dbb0b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 25, 2023 License: GPL-3.0 Imports: 9 Imported by: 0

README

openssl

This is golang binding for openssl, use swig generated interface.

support SSL client, SSL server, digest(md5, sha1, sha256) and cipher(AES).

Usage example

SSL/TLS Client example

package main

import (
    "bufio"
    "log"
    "net/http"
    "os"

    "github.com/fangdingjun/openssl"
)

func main() {
    conn, err := openssl.Dial("tcp", "httpbin.org:443", &openssl.Config{
        ServerName:         "httpbin.org",
        InsecureSkipVerify: false,
    })
    if err != nil {
        log.Fatalf("connect failed %s", err)
    }
    defer conn.Close()

    req, _ := http.NewRequest("GET", "https://httpbin.org/get?key1=value1&key2=value2", nil)
    req.Header.Add("x-cusom-header1", "hello")
    req.Header.Add("connection", "close")

    req.Write(os.Stdout)
    req.Write(conn)

    bufio := bufio.NewReader(conn)
    resp, err := http.ReadResponse(bufio, req)
    if err != nil {
        log.Fatalf("read response failed %#v", err)
    }
    resp.Write(os.Stdout)
}

SSL/TLS Server example

package main

import (
    "bufio"
    "fmt"
    "io"
    "log"
    "net"
    "net/http"
    "os"
    "strings"

    "github.com/fangdingjun/openssl"
)

func handleConn(conn net.Conn) {
    defer conn.Close()

    reader := bufio.NewReader(conn)
    req, err := http.ReadRequest(reader)
    if err != nil {
        log.Println(err)
        return
    }

    // dump request to console
    req.Write(os.Stdout)

    // custom a http response
    res := &http.Response{}

    res.Header = make(http.Header)
    res.Header.Add("x-custom-header", "aaa")
    res.Header.Add("server", "openssl_server/1.0")

    responseText := "hello, world\n"

    res.Header.Add("content-type", "text/plain")
    res.Header.Add("content-length", fmt.Sprintf("%d", len(responseText)))

    res.StatusCode = 200
    res.ProtoMajor = 1
    res.ProtoMinor = 1

    body := strings.NewReader(responseText)
    res.Body = io.NopCloser(body)

    res.Write(conn)
}

func main() {
    key, err := openssl.LoadPrivateKey("../certs/server.key")
    if err != nil {
        log.Fatal(err)
    }
    cert, err := openssl.LoadCertificate("../certs/server.cert")
    if err != nil {
        log.Fatal(err)
    }
    ln, err := openssl.Listen("tcp", ":7777", &openssl.Config{
        Certificate: cert,
        PrivateKey:  key,
    })
    if err != nil {
        log.Fatal(err)
    }
    defer ln.Close()

    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Println(err)
            break
        }
        go handleConn(conn)
    }
}

Crypto example

func md5example() {
    h := openssl.NewMD5()
    defer h.Close()

    h.Write([]byte("hello"))
    h.Flush()
    result := make([]byte, 32)
    n, err := h.Read(result)
    if err != nil {
        log.Println(err)
        return
    }
    fmt.Printf("md5 result %x\n", result[:n])
}

func sha256example() {
    h := openssl.NewSha256()
    defer h.Close()

    h.Write([]byte("hello"))
    h.Flush()
    result := make([]byte, 32)
    n, err := h.Read(result)
    if err != nil {
        log.Println(err)
        return
    }
    fmt.Printf("sha256 result %x\n", result[:n])
}

func aesExample() {
    data := []byte("hello")

    // use random key and iv
    key := make([]byte, 16)
    iv := make([]byte, 12)
    rand.Reader.Read(key)
    rand.Reader.Read(iv)

    encCipher := openssl.NewCipherEncrypt(libssl.EVP_aes_128_gcm(), key, iv)
    defer encCipher.Close()

    encCipher.Write(data)
    encCipher.Flush() // no more data to encrypt

    result := make([]byte, 20)
    n, _ := encCipher.Read(result)
    fmt.Printf("aes encrypt result %x\n", result[:n])

    decCipher := openssl.NewCipherDecrypt(libssl.EVP_aes_128_gcm(), key, iv)
    defer decCipher.Close()

    decCipher.Write(result[:n])
    decCipher.Flush() // no more data to decrypt

    result2 := make([]byte, 32)
    n, _ = decCipher.Read(result2)

    fmt.Printf("aes decrypted result: %s\n", result2[:n])
}

WARNING: this code is not full tested, use it at your own risk!

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetCertificateIssuer

func GetCertificateIssuer(cert libssl.X509) string

GetCertificateIssuer get the issuer subject from x509 certificate

func GetCertificateSubject

func GetCertificateSubject(cert libssl.X509) string

GetCertificateSubject get the subject from x509 certificate

func GetSslError

func GetSslError() string

GetSslError get the current ssl error

func Listen

func Listen(network, laddr string, config *Config) (net.Listener, error)

Listen create a listener, when accept, auto create a tls context for the new connection

func LoadCertificate

func LoadCertificate(filename string) (libssl.X509, error)

func LoadPrivateKey

func LoadPrivateKey(filename string) (libssl.EVP_PKEY, error)

func NewListener

func NewListener(inner net.Listener, config *Config) net.Listener

NewListener create listener with exists listener and config

Types

type Cipher

type Cipher interface {
	io.ReadWriteCloser
	Flush() error
}

func NewCipherDecrypt

func NewCipherDecrypt(md libssl.EVP_CIPHER, key, iv []byte) Cipher

NewCipherDecrypt create a decrypt cipher with cipher md with key and iv, key and iv size must match the cipher md.

Write() write the ciphertext to cipher.

Read() get the plaintext.

Flush() signal no more data to cipher.

Close() free the resource.

func NewCipherEncrypt

func NewCipherEncrypt(md libssl.EVP_CIPHER, key, iv []byte) Cipher

NewCipherEncrypt create a encrypt cipher with cipher md with key and iv, key and iv size must match the cipher md.

use Write() write the plaintext to cipher.

Read() get the ciphertext.

Flush() signal no more data to cipher.

Close() free the resource.

type Config

type Config struct {
	// ServerName server sni name
	ServerName string

	// private key to use
	PrivateKey libssl.EVP_PKEY

	// ALPN names
	NextProtos []string

	// certificate to use
	Certificate libssl.X509

	// psk identity used in psk mode
	Identity string

	// the pre-shared key used in psk mode, this field set will enable psk mode
	Psk []byte

	// skip verify server certificate
	InsecureSkipVerify bool

	// additional root ca to use
	RootCA libssl.X509

	ClientCA libssl.X509

	// verify client or not
	ClientAuth int
}

Config tls config

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn a tls connection

func Client

func Client(conn net.Conn, config *Config) *Conn

Client initail a tls client use exists connection conn and config

func Dial

func Dial(network, addr string, config *Config) (*Conn, error)

Dial create a connection to addr and intial the tls context

func Server

func Server(conn net.Conn, config *Config) *Conn

Server create tls context for server use exists connection conn

func (*Conn) Close

func (c *Conn) Close() error

Close close the tls connection

func (*Conn) ConnectionState

func (c *Conn) ConnectionState() ConnectionState

ConnectionState get connection state

func (*Conn) Handshake

func (c *Conn) Handshake() error

Handshake perform the tls handshake

func (*Conn) LocalAddr

func (c *Conn) LocalAddr() net.Addr

LocalAddr get local addr

func (*Conn) Read

func (c *Conn) Read(buf []byte) (int, error)

Read read data from tls conn

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() net.Addr

RemoteAddr get the remote addr

func (*Conn) SetDeadline

func (c *Conn) SetDeadline(t time.Time) error

SetDeadline set the dead line

func (*Conn) SetReadDeadline

func (c *Conn) SetReadDeadline(t time.Time) error

SetReadDeadline set the read dead line

func (*Conn) SetWriteDeadline

func (c *Conn) SetWriteDeadline(t time.Time) error

SetWriteDeadline set the write dead line

func (*Conn) Write

func (c *Conn) Write(buf []byte) (int, error)

Write write data through tls conn

type ConnectionState

type ConnectionState struct {
	NegotiatedProtocol string
	HandshakeComplete  bool
	PeerCertificate    libssl.X509
}

ConnectionState connection state

type HASH

type HASH interface {
	io.ReadWriteCloser
	Flush() error
}

func NewMD5

func NewMD5() HASH

NewMD5 create a md5 hash instance

func NewSha1

func NewSha1() HASH

NewSha1 create a sha1 hash instance

func NewSha256

func NewSha256() HASH

NewSha256 create a sha256 hash instance

func NewSha512

func NewSha512() HASH

NewSha512 create a sha512 hash instance

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL