I'm trying to use rsa
package for encrypt
and decrypt
with public
and private
keys.
func main() {
flag.Parse()
text := "my super secret"
glog.Infof("Original text: %s
", text)
glog.Infoln("Loading public key..")
pubKey, err := loadPublicKey("id_rsa.pub")
if err == nil {
glog.Infoln("SUCCESS!")
} else {
glog.Errorln("LOOSE =(")
}
etext, err := encrypt([]byte(text), pubKey)
if err != nil {
glog.Errorf("Can't encrypt text: %+v
", err)
}
glog.Infof("Encrypted text: %s
", etext)
glog.Infoln("Loading private key..")
privKey, err := loadPrivateKey("id_rsa")
if err == nil {
glog.Infoln("SUCCESS!")
} else {
glog.Errorln("LOOSE =(")
}
dtext, err := decrypt(etext, privKey)
if err != nil {
glog.Errorf("Can't decrypt text: %+v
", err)
}
glog.Infof("Decrypted text: %s
", dtext)
glog.Flush()
}
func loadPublicKey(path string) (*rsa.PublicKey, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("no key found
")
}
if block.Type != "PUBLIC KEY" {
return nil, fmt.Errorf("invalid key type - %s
", block.Type)
}
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("can't parse key - %+v
", err)
}
return pubKey.(*rsa.PublicKey), nil
}
func loadPrivateKey(path string) (*rsa.PrivateKey, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("no key found
")
}
if block.Type != "PRIVATE KEY" {
return nil, fmt.Errorf("invalid key type - %s
", block.Type)
}
return x509.ParsePKCS1PrivateKey(block.Bytes)
}
func encrypt(data []byte, pubKey *rsa.PublicKey) ([]byte, error) {
return rsa.EncryptPKCS1v15(rand.Reader, pubKey, data)
}
func decrypt(data []byte, privKey *rsa.PrivateKey) ([]byte, error) {
return rsa.DecryptPKCS1v15(rand.Reader, privKey, data)
}
But I have an error in rsa.EncryptPKCS1v15
:
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x5c16c]
goroutine 1 [running]:
crypto/rsa.EncryptPKCS1v15(0x11641f8, 0xc8200762a0, 0x0, 0xc82004ddc8, 0xf, 0x20, 0x0, 0x0, 0x0, 0x0, ...)
/usr/local/go/src/crypto/rsa/pkcs1v15.go:32 +0x5c
main.encrypt(0xc82004ddc8, 0xf, 0x20, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0)
/Users/cnaize/Dropbox/develop/gocode/src/test/main.go:132 +0x87
main.main()
/Users/cnaize/Dropbox/develop/gocode/src/test/main.go:67 +0x3b8
Why where is the error? How to resolve this?
EDITED:
thanks, now I understand the problem - in loadPublicKey("id_rsa.pub")
pem.Decode(data)
returns nil block
.
What is the right way to parse ssh
keys?