-1

I have a private key in a file -----BEGIN PRIVATE KEY-----\nxxx-----END PRIVATE KEY-----\n I am trying to perform the below which is in Ruby in Go and got stuck as Go accepts only pem file. Kindly suggest.

azure_certificate_private_key = OpenSSL::PKey.read(private_key_file)
base64_signature = Base64.strict_encode64(private_key.sign(OpenSSL::Digest::SHA256.new, headerPayloadConcatenated))

I have tried as,

signBytes, err := ioutil.ReadFile(privKeyPath)
signer, err := ParsePrivateKey(signBytes)
  • no key found error
useranon
  • 29,318
  • 31
  • 98
  • 146
  • *"... as golang accepts only pem file ..."* - based on what you show as file contents you already have a PEM file. – Steffen Ullrich Aug 24 '21 at 11:49
  • @SteffenUllrich - I dont have a PEM file but instead a private_key which i got it while generating private key json from Google API – useranon Aug 24 '21 at 11:52
  • 1
    *"I dont have a PEM file"* - this contradicts what you write in your question *"I have a private key in a file ..."*. Also see https://stackoverflow.com/questions/44230634/how-to-read-an-rsa-key-from-file – Steffen Ullrich Aug 24 '21 at 12:51

1 Answers1

0
package main

import (
    "encoding/pem"
    "crypto/x509"
    "io/ioutil"
)

func main() {
    signBytes, err := ioutil.ReadFile(privKeyPath)
    if err != nil {
        panic(err) //or do whatever with err
    }

    keyRSA := parseRSAKey(signBytes)

    //keyRSA is a *rsa.PrivateKey
    //....use the key

}

func parseRSAKey(b []byte) *rsa.PrivateKey {
    block, _ := pem.Decode(b)
    if block == nil {
        panic("no PEM block")
    }

    key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
    if err != nil {
        panic(err)
    }
    return key
}

this should work to parse a RSA private key.

yebowhatsay
  • 182
  • 1
  • 7