This repository has been archived on 2020-04-20. You can view files and clone it, but cannot push or open issues or pull requests.
libricochet-go/utils/crypto.go

83 lines
2.3 KiB
Go
Raw Normal View History

2017-05-02 23:33:51 +00:00
package utils
import (
"crypto/rand"
2017-05-02 23:33:51 +00:00
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"math"
"math/big"
"github.com/yawning/bulb/utils/pkcs1"
2017-05-02 23:33:51 +00:00
)
const (
2018-01-08 19:01:23 +00:00
// InvalidPrivateKeyFileError is a library error, thrown when the given key file fials to load
InvalidPrivateKeyFileError = Error("InvalidPrivateKeyFileError")
2018-01-08 19:01:23 +00:00
// RicochetKeySize - tor onion services currently use rsa key sizes of 1024 bits
RicochetKeySize = 1024
)
2018-01-17 18:18:46 +00:00
// GetRandNumber is a helper function which returns a random integer, this is
// currently mostly used to generate messageids
func GetRandNumber() *big.Int {
2018-01-12 18:04:20 +00:00
num, err := rand.Int(rand.Reader, big.NewInt(math.MaxUint32))
// If we can't generate random numbers then panicking is probably
// the best option.
CheckError(err)
return num
}
2018-01-08 19:01:23 +00:00
// GeneratePrivateKey generates a new private key for use
func GeneratePrivateKey() (*rsa.PrivateKey, error) {
2018-01-08 19:01:23 +00:00
privateKey, err := rsa.GenerateKey(rand.Reader, RicochetKeySize)
if err != nil {
return nil, errors.New("Could not generate key: " + err.Error())
}
privateKeyDer := x509.MarshalPKCS1PrivateKey(privateKey)
return x509.ParsePKCS1PrivateKey(privateKeyDer)
}
2017-05-02 23:33:51 +00:00
// LoadPrivateKeyFromFile loads a private key from a file...
func LoadPrivateKeyFromFile(filename string) (*rsa.PrivateKey, error) {
pemData, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
return ParsePrivateKey(pemData)
}
2018-01-08 19:01:23 +00:00
// ParsePrivateKey Convert a private key string to a usable private key
func ParsePrivateKey(pemData []byte) (*rsa.PrivateKey, error) {
2017-05-02 23:33:51 +00:00
block, _ := pem.Decode(pemData)
if block == nil || block.Type != "RSA PRIVATE KEY" {
return nil, InvalidPrivateKeyFileError
2017-05-02 23:33:51 +00:00
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
2018-01-08 19:01:23 +00:00
// PrivateKeyToString turns 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))
}
// return an onion address from a private key
func GetOnionAddress(privateKey *rsa.PrivateKey) (string, error) {
addr, err := pkcs1.OnionAddr(&privateKey.PublicKey)
if err != nil {
return "", err
} else if addr == "" {
return "", OnionAddressGenerationError
}
return addr, nil
}