libricochet-go/utils/crypto.go

84 lines
2.6 KiB
Go

package utils
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"github.com/agl/ed25519/extra25519"
"golang.org/x/crypto/curve25519"
"golang.org/x/crypto/ed25519"
"io/ioutil"
"math"
"math/big"
)
const (
// InvalidPrivateKeyFileError is a library error, thrown when the given key file fials to load
InvalidPrivateKeyFileError = Error("InvalidPrivateKeyFileError")
// RicochetKeySize - tor onion services currently use rsa key sizes of 1024 bits
RicochetKeySize = 1024
)
// GetRandNumber is a helper function which returns a random integer, this is
// currently mostly used to generate messageids
func GetRandNumber() *big.Int {
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
}
// EDH implements diffie hellman using curve25519 keys derived from ed25519 keys
// NOTE: This uses a 3rd party library extra25519 as the key conversion is not in the core golang lib
// as such this definitely needs further review.
func EDH(privateKey ed25519.PrivateKey, remotePublicKey ed25519.PublicKey) [32]byte {
var privKeyBytes [64]byte
var remotePubKeyBytes [32]byte
copy(privKeyBytes[:], privateKey[:])
copy(remotePubKeyBytes[:], remotePublicKey[:])
var secret, curve25519priv, curve25519pub [32]byte
extra25519.PrivateKeyToCurve25519(&curve25519priv, &privKeyBytes)
extra25519.PublicKeyToCurve25519(&curve25519pub, &remotePubKeyBytes)
curve25519.ScalarMult(&secret, &curve25519priv, &curve25519pub)
return secret
}
// GeneratePrivateKeyV3 cryptographically creats a new ed25519 key pair.
func GeneratePrivateKeyV3() (ed25519.PublicKey, ed25519.PrivateKey, error) {
return ed25519.GenerateKey(rand.Reader)
}
// 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)
}
// ParsePrivateKey Convert a private key string to a usable private key
func ParsePrivateKey(pemData []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(pemData)
if block == nil || block.Type != "RSA PRIVATE KEY" {
return nil, InvalidPrivateKeyFileError
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
// 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))
}