Converting to Type rsa.PublicKey - go

I'm trying to import my own RSA public key as opposed to generating one to encrypt a string with. Only thing is that I'm having issues changing to the correct type. Here's my current code:
func main() {
s := ""
i := new(big.Int)
i.SetString(s, 16)
encrypt(i)
}
func encrypt(i *big.Int) {
publicKey := PublicKey{N: i, E: 010001}
secretMessage := "This is super secret message!"
encryptedMessage := RSA_OAEP_Encrypt(secretMessage, publicKey)
fmt.Println("Cipher Text:", encryptedMessage)
}
Where it doesn't like publicKey's type
What I'm wondering is if there's a way that I can **convert type PublicKey** to **type rsa.PublicKey** so that I can use it for encryption.

There seem to be two types of key: one is the base interface, called just PublicKey. The type rsa.PublicKey is derived from that and should be used instead. Otherwise the key type is not set correctly and the code will fail. I presume it creates an anonymous type with the values set.

Related

Converting *crypto.PrivateKey to *rsa.PrivateKey

I am developing a method that will make a signature based in the type of private key that is passed as argument. To do that, I'm passing a *crypto.PrivateKey variable as argument. But the problem comes when I want to do a type assertion to use the argument.
func Sign(text string, privKey *crypto.PrivateKey) string{
if _, ok := (*privKey).(rsa.PrivateKey) //This is ok
if _, ok := (privKey).(*rsa.PrivateKey) //This is not ok 2
I guess I can do the first thing because if I use "*", the compiler think that it is an interface. But I don't know why I can't do the second thing, when it should be correct.
By the way, I need to use a variable of type *rsa.PrivateKey, I can do this this way:
privRsa, _ := (*privKey).(rsa.PrivateKey)
var priv *rsa.PrivateKey
priv = &privRsa
What I can not understand is why I can't directly convert the *crypto.PrivateKey into *rsa.PrivateKey, or if it exist a way to do that. I thing doing it the way I'm doing it right now would allocate new space in memory that I shouldn't if I want it to be efficient
crypto.PrivateKey is an interface. *crypto.PrivateKey is a pointer to an interface. You can use type-assertion on an interface to get the underlying value:
func Sign(text string, privKey crypto.PrivateKey) string{
if _, ok := privKey.(rsa.PrivateKey)
...
}
...
var pkey rsa.PrivateKey
Sign(text,pkey)
Here, the private key value in the interface is a copy of the rsa.PrivateKey.
If you pass the address of pkey, then, then the interface would have a pointer to the private key:
func Sign(text string, privKey crypto.PrivateKey) string{
if _, ok := privKey.(*rsa.PrivateKey)
...
}
...
var pkey rsa.PrivateKey
Sign(text,&pkey)

Bip32 Keys encryption in Golang Nacl Secretbox

I have created the Assymetric struct which generates a BIP39 and BIP32 Master public and private key. Now I want to use these keys and their derived children to encrypt files or strings depending upon the use case. Please correct me if I am wrong — the keys generated from Mnemonics BIP32 are Elliptic curve keys(secp256k1). I am trying to use the NACL Go implementation to encrypt text with these keys, but it only accepts keys which are 32 bytes but the keys that are being generated from Mnemonics are 256 Bytes. Please help. The bip32 implementation can be found here https://github.com/tyler-smith/go-bip32/blob/master/bip32.go#L59
After going through the implementation, I have found out that the resulting key is a combination of Key and chaincode, key.Key is a 32byte key that must be used for encryption. Just wanted to check if this is the right way to do it and guarantees security.
package encryption
import (
"github.com/tyler-smith/go-bip39"
"github.com/tyler-smith/go-bip32"
"crypto/ecdsa"
"crypto/elliptic"
"golang.org/x/crypto/nacl/secretbox"
"crypto/rand"
"encoding/hex"
"io"
"log"
)
type Encryption interface {
GenerateMnemonic() ( *bip32.Key, *bip32.Key)
}
type Assymetric struct{
RootPrivateKey *bip32.Key
RootPublicKeyKey *bip32.Key
RootMnemonic string
RootPassphrase string
}
func (c *Assymetric) GenerateMnemonic() (*bip32.Key, *bip32.Key){
entropy, _ := bip39.NewEntropy(256)
mnemonic, _ := bip39.NewMnemonic(entropy)
seed := bip39.NewSeed(mnemonic, c.RootPassphrase)
rootPrivateKey, _ := bip32.NewMasterKey(seed)
rootPublicKey := rootPrivateKey.PublicKey()
// Display mnemonic and keys
//c.RootMnemonic = mnemonic
c.RootPrivateKey = rootPrivateKey
c.RootPublicKeyKey = rootPublicKey
key, _ := rootPrivateKey.NewChildKey(0)
log.Printf("Private key 0 is %s", key)
log.Printf("Public key 0 is %s", key.PublicKey())
// You must use a different nonce for each message you encrypt with the
// same key. Since the nonce here is 192 bits long, a random value
// provides a sufficiently small probability of repeats.
log.Printf("This is the secret key %s", secretKey)
var nonce [24]byte
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
panic(err)
}
log.Printf("This is the nonce %s", nonce)
var a [32]byte
copy(a[:], key.Key)
log.Printf("\nlen=%d cap=%d %v\n", len(a), cap(a), a)
encrypted := secretbox.Seal(nonce[:], []byte("hello world"), &nonce, &a)
log.Println(encrypted)
return rootPrivateKey, rootPublicKey

ed25519.Public result is different

Using the package https://github.com/golang/crypto/tree/master/ed25519 i m trying to get a public key for a given private key.
Those data are from http://www.bittorrent.org/beps/bep_0044.html: test 2 (mutable with salt)
Problem is, ed25519.Public() won t return the same public key when i fed it with the given private key.
The golang implementation returns the last 32 bytes of the PVK. But in my test data this is unexpected.
The code here https://play.golang.org/p/UJNPCyuGQB
package main
import (
"encoding/hex"
"golang.org/x/crypto/ed25519"
"log"
)
func main() {
priv := "e06d3183d14159228433ed599221b80bd0a5ce8352e4bdf0262f76786ef1c74db7e7a9fea2c0eb269d61e3b38e450a22e754941ac78479d6c54e1faf6037881d"
pub := "77ff84905a91936367c01360803104f92432fcd904a43511876df5cdf3e7e548"
sig := "6834284b6b24c3204eb2fea824d82f88883a3d95e8b4a21b8c0ded553d17d17ddf9a8a7104b1258f30bed3787e6cb896fca78c58f8e03b5f18f14951a87d9a08"
// d := hex.EncodeToString([]byte(priv))
privb, _ := hex.DecodeString(priv)
pvk := ed25519.PrivateKey(privb)
buffer := []byte("4:salt6:foobar3:seqi1e1:v12:Hello World!")
sigb := ed25519.Sign(pvk, buffer)
pubb, _ := hex.DecodeString(pub)
sigb2, _ := hex.DecodeString(sig)
log.Println(ed25519.Verify(pubb, buffer, sigb))
log.Printf("%x\n", pvk.Public())
log.Printf("%x\n", sigb)
log.Printf("%x\n", sigb2)
}
How to generate the same public key than the bep using golang ?
This is due to different ed25519 private key formats. An ed25519 key starts out as a 32 byte seed. This seed is hashed with SHA512 to produce 64 bytes (a couple of bits are flipped too). The first 32 bytes of these are used to generate the public key (which is also 32 bytes), and the last 32 bytes are used in the generation of the signature.
The Golang private key format is the 32 byte seed concatenated with the 32 byte public key. The private keys in the Bittorrent document you are using are the 64 byte result of the hash (or possibly just 64 random bytes that are used the same way as the hash result).
Since it’s not possible to reverse the hash, you can’t convert the Bittorrent keys to a format that the Golang API will accept.
You can produce a version of the Golang lib based on the existing package.
The following code depends on the internal package golang.org/x/crypto/ed25519/internal/edwards25519, so if you want to use it you will need to copy that package out so that it is available to you code. It’s also very “rough and ready”, I’ve basically just copied the chunks of code needed from the existing code to get this to work.
Note that the public key and signature formats are the same, so as long as you are not sharing private keys you don’t need to use this code to get a working implementation. You will only need it if you want to check the test vectors.
First generating the public key from a private key:
// Generate the public key corresponding to the already hashed private
// key.
//
// This code is mostly copied from GenerateKey in the
// golang.org/x/crypto/ed25519 package, from after the SHA512
// calculation of the seed.
func getPublicKey(privateKey []byte) []byte {
var A edwards25519.ExtendedGroupElement
var hBytes [32]byte
copy(hBytes[:], privateKey)
edwards25519.GeScalarMultBase(&A, &hBytes)
var publicKeyBytes [32]byte
A.ToBytes(&publicKeyBytes)
return publicKeyBytes[:]
}
Next generating a signature:
// Calculate the signature from the (pre hashed) private key, public key
// and message.
//
// This code is mostly copied from the Sign function from
// golang.org/x/crypto/ed25519, from after the SHA512 calculation of the
// seed.
func sign(privateKey, publicKey, message []byte) []byte {
var privateKeyA [32]byte
copy(privateKeyA[:], privateKey) // we need this in an array later
var messageDigest, hramDigest [64]byte
h := sha512.New()
h.Write(privateKey[32:])
h.Write(message)
h.Sum(messageDigest[:0])
var messageDigestReduced [32]byte
edwards25519.ScReduce(&messageDigestReduced, &messageDigest)
var R edwards25519.ExtendedGroupElement
edwards25519.GeScalarMultBase(&R, &messageDigestReduced)
var encodedR [32]byte
R.ToBytes(&encodedR)
h.Reset()
h.Write(encodedR[:])
h.Write(publicKey)
h.Write(message)
h.Sum(hramDigest[:0])
var hramDigestReduced [32]byte
edwards25519.ScReduce(&hramDigestReduced, &hramDigest)
var s [32]byte
edwards25519.ScMulAdd(&s, &hramDigestReduced, &privateKeyA, &messageDigestReduced)
signature := make([]byte, 64)
copy(signature[:], encodedR[:])
copy(signature[32:], s[:])
return signature
}
Finally we can use these two functions to demonstrate the test vectors:
privateKeyHex := "e06d3183d14159228433ed599221b80bd0a5ce8352e4bdf0262f76786ef1c74db7e7a9fea2c0eb269d61e3b38e450a22e754941ac78479d6c54e1faf6037881d"
expectedPublicKey := "77ff84905a91936367c01360803104f92432fcd904a43511876df5cdf3e7e548"
expectedSig := "6834284b6b24c3204eb2fea824d82f88883a3d95e8b4a21b8c0ded553d17d17ddf9a8a7104b1258f30bed3787e6cb896fca78c58f8e03b5f18f14951a87d9a08"
privateKey, _ := hex.DecodeString(privateKeyHex)
publicKey := getPublicKey(privateKey)
fmt.Printf("Calculated key: %x\n", publicKey)
fmt.Printf("Expected key: %s\n", expectedPublicKey)
keyMatches := expectedPublicKey == hex.EncodeToString(publicKey)
fmt.Printf("Public key matches expected: %v\n", keyMatches)
buffer := []byte("4:salt6:foobar3:seqi1e1:v12:Hello World!")
calculatedSig := sign(privateKey, publicKey, buffer)
fmt.Printf("Calculated sig: %x\n", calculatedSig)
fmt.Printf("Expected sig: %s\n", expectedSig)
sigMatches := expectedSig == hex.EncodeToString(calculatedSig)
fmt.Printf("Signature matches expected: %v\n", sigMatches)

How to convert interface{} to string?

I'm using docopt to parse command-line arguments. This works, and it results in a map, such as
map[<host>:www.google.de <port>:80 --help:false --version:false]
Now I would like to concatenate the host and the port value to a string with a colon in-between the two values. Basically, something such as:
host := arguments["<host>"] + ":" + arguments["<port>"]
Unfortunately, this doesn't work, as I get the error message:
invalid operation: arguments[""] + ":" (mismatched types interface {} and string)
So obviously I need to convert the value that I get from the map (which is just interface{}, so it can be anything) to a string. Now my question is, how do I do that?
You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)
Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port
You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:
hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])
To expand on what Peter said:
Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.
Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.
You could also use text/template:
package main
import (
"text/template"
"strings"
)
func format(s string, v interface{}) string {
t, b := new(template.Template), new(strings.Builder)
template.Must(t.Parse(s)).Execute(b, v)
return b.String()
}
func main() {
m := map[string]interface{}{"<host>": "www.google.de", "<port>": "80"}
s := format(`{{index . "<host>"}}:{{index . "<port>"}}`, m)
println(s == "www.google.de:80")
}
https://pkg.go.dev/text/template

How to store ECDSA private key in Go

I am using the ecdsa.GenerateKey method to generate a private/public key pair in Go. I would like to store the private key in a file on the users computer, and load it whenever the program starts. There is a method elliptic.Marshal that marshals the public key, but nothing for the private key. Should I simply roll my own, or is there a recommended way to store the private key?
Here is a code sample that demonstrates encoding and decoding of keys in Go. It helps to know that you need to connect couple of steps. Crypto algorithm is the fist step, in this case ECDSA key. Then you need standard encoding, x509 is most commontly used standard. Finally you need a file format, PEM is again commonly used one. This is currently most commonly used combination, but feel free to substitute any other algoriths or encoding.
func encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string) {
x509Encoded, _ := x509.MarshalECPrivateKey(privateKey)
pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded})
x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey)
pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub})
return string(pemEncoded), string(pemEncodedPub)
}
func decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) {
block, _ := pem.Decode([]byte(pemEncoded))
x509Encoded := block.Bytes
privateKey, _ := x509.ParseECPrivateKey(x509Encoded)
blockPub, _ := pem.Decode([]byte(pemEncodedPub))
x509EncodedPub := blockPub.Bytes
genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub)
publicKey := genericPublicKey.(*ecdsa.PublicKey)
return privateKey, publicKey
}
func test() {
privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
publicKey := &privateKey.PublicKey
encPriv, encPub := encode(privateKey, publicKey)
fmt.Println(encPriv)
fmt.Println(encPub)
priv2, pub2 := decode(encPriv, encPub)
if !reflect.DeepEqual(privateKey, priv2) {
fmt.Println("Private keys do not match.")
}
if !reflect.DeepEqual(publicKey, pub2) {
fmt.Println("Public keys do not match.")
}
}
I believe the standard format for those keys is to use the X.509 ASN.1 DER representation. See http://golang.org/pkg/crypto/x509/#MarshalECPrivateKey and http://golang.org/pkg/crypto/x509/#ParseECPrivateKey.
I adapted a really quick and dirty way to do it, as suggested by one of the geth team in late '15 in my library https://github.com/DaveAppleton/ether_go
it is a far simpler solution (but puts keys in plain sight)

Resources