Merge pull request #26 from dballard/crypto-utils

Add more crypto/utils and extend SetupOnion to support unix sockets
This commit is contained in:
Sarah Jamie Lewis 2017-08-15 11:34:26 -07:00 committed by GitHub
commit d2dceef028
2 changed files with 33 additions and 3 deletions

View File

@ -6,8 +6,10 @@ import (
"net" "net"
) )
func SetupOnion(proxyServer string, authentication string, pk *rsa.PrivateKey, onionport uint16) (net.Listener, error) { // "127.0.0.1:9051" "tcp4"
c, err := bulb.Dial("tcp4", proxyServer) // "/var/run/tor/control" "unix"
func SetupOnion(torControlAddress string, torControlSocketType string, authentication string, pk *rsa.PrivateKey, onionport uint16) (net.Listener, error) {
c, err := bulb.Dial(torControlSocketType, torControlAddress)
if err != nil { if err != nil {
return nil, err return nil, err
} }

View File

@ -5,20 +5,37 @@ import (
"crypto/x509" "crypto/x509"
"encoding/pem" "encoding/pem"
"io/ioutil" "io/ioutil"
"errors"
"crypto/rand"
) )
const ( const (
InvalidPrivateKeyFileError = Error("InvalidPrivateKeyFileError") InvalidPrivateKeyFileError = Error("InvalidPrivateKeyFileError")
RICOCHET_KEY_SIZE = 1024
) )
// Generate a private key for use
func GeneratePrivateKey() (*rsa.PrivateKey, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, RICOCHET_KEY_SIZE)
if err != nil {
return nil, errors.New("Could not generate key: " + err.Error())
}
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
return x509.ParsePKCS1PrivateKey(privateKeyDer)
}
// LoadPrivateKeyFromFile loads a private key from a file... // LoadPrivateKeyFromFile loads a private key from a file...
func LoadPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) { func LoadPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) {
pemData, err := ioutil.ReadFile(filename) pemData, err := ioutil.ReadFile(filename)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return ParsePrivateKey(pemData)
}
// Convert a private key string to a usable private key
func ParsePrivateKey(pemData []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(pemData) block, _ := pem.Decode(pemData)
if block == nil || block.Type != "RSA PRIVATE KEY" { if block == nil || block.Type != "RSA PRIVATE KEY" {
return nil, InvalidPrivateKeyFileError return nil, InvalidPrivateKeyFileError
@ -26,3 +43,14 @@ func LoadPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) {
return x509.ParsePKCS1PrivateKey(block.Bytes) return x509.ParsePKCS1PrivateKey(block.Bytes)
} }
// turn a private key into storable string
func PrivateKeyToString(privateKey *rsa.PrivateKey) string {
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
return string(pem.EncodeToMemory(&privateKeyBlock))
}