Generate SSH RSA Private/Public Key pair with Golang
Generate
gistfile1.txt
// This shows an example of how to generate a SSH RSA Private/Public key pair and save it locally
package main
import (
'crypto/rand'
'crypto/rsa'
'crypto/x509'
'encoding/pem'
'golang.org/x/crypto/ssh'
'io/ioutil'
'log'
)
func main() {
savePrivateFileTo := './id_rsa_test'
savePublicFileTo := './id_rsa_test.pub'
bitSize := 4096
privateKey, err := generatePrivateKey(bitSize)
if err != nil {
log.Fatal(err.Error())
}
publicKeyBytes, err := generatePublicKey(&privateKey.PublicKey)
if err != nil {
log.Fatal(err.Error())
}
privateKeyBytes := encodePrivateKeyToPEM(privateKey)
err = writeKeyToFile(privateKeyBytes, savePrivateFileTo)
if err != nil {
log.Fatal(err.Error())
}
err = writeKeyToFile([]byte(publicKeyBytes), savePublicFileTo)
if err != nil {
log.Fatal(err.Error())
}
}
// generatePrivateKey creates a RSA Private Key of specified byte size
func generatePrivateKey(bitSize int) (*rsa.PrivateKey, error) {
// Private Key generation
privateKey, err := rsa.GenerateKey(rand.Reader, bitSize)
if err != nil {
return nil, err
}
// Validate Private Key
err = privateKey.Validate()
if err != nil {
return nil, err
}
log.Println('Private Key generated')
return privateKey, nil
}
// encodePrivateKeyToPEM encodes Private Key from RSA to PEM format
func encodePrivateKeyToPEM(privateKey *rsa.PrivateKey) []byte {
// Get ASN.1 DER format
privDER := x509.MarshalPKCS1PrivateKey(privateKey)
// pem.Block
privBlock := pem.Block{
Type: 'RSA PRIVATE KEY',
Headers: nil,
Bytes: privDER,
}
// Private key in PEM format
privatePEM := pem.EncodeToMemory(&privBlock)
return privatePEM
}
// generatePublicKey take a rsa.PublicKey and return bytes suitable for writing to .pub file
// returns in the format 'ssh-rsa ...'
func generatePublicKey(privatekey *rsa.PublicKey) ([]byte, error) {
publicRsaKey, err := ssh.NewPublicKey(privatekey)
if err != nil {
return nil, err
}
pubKeyBytes := ssh.MarshalAuthorizedKey(publicRsaKey)
log.Println('Public key generated')
return pubKeyBytes, nil
}
// writePemToFile writes keys to a file
func writeKeyToFile(keyBytes []byte, saveFileTo string) error {
err := ioutil.WriteFile(saveFileTo, keyBytes, 0600)
if err != nil {
return err
}
log.Printf('Key saved to: %s', saveFileTo)
return nil
}
Sign up for freeto join this conversation on GitHub. Already have an account? Sign in to comment
Permalink

Join GitHub today

GitHub is home to over 40 million developers working together to host and review code, manage projects, and build software together.

To use the RSA key pair generator to generate a 4096 bits RSA key and save that key in PEM format in private.key, use./genkey type=rsa rsakeysize=4096 filename=private.key format=pem The larger the requested keysize, the longer it will take to generate the key itself. You also need to take into account the performance of the system.

Key
  1. Go is an open source programming language that makes it easy to build simple, reliable, and efficient software.
  2. //fmt.Printf('CRTValues: Exp%s Coeff%s R%s ', CRTVal2.Exp.String, CRTVal2.Coeff.String, CRTVal2.R.String).
  3. (Go) Generate Key and Certificate Signing Request (CSR) Demonstrates how to generate a new RSA key and a Certificate Signing Request (CSR).
Sign up
Branch:master
Find file Copy path
2 contributors
package main
import (
'crypto'
'crypto/rand'
'crypto/rsa'
'crypto/sha256'
'fmt'
'os'
)
funcmain() {
// Generate RSA Keys
miryanPrivateKey, err:=rsa.GenerateKey(rand.Reader, 2048)
iferr!=nil {
fmt.Println(err.Error)
os.Exit(1)
}
miryanPublicKey:=&miryanPrivateKey.PublicKey
raulPrivateKey, err:=rsa.GenerateKey(rand.Reader, 2048)
iferr!=nil {
fmt.Println(err.Error)
os.Exit(1)
}
raulPublicKey:=&raulPrivateKey.PublicKey
fmt.Println('Private Key : ', miryanPrivateKey)
fmt.Println('Public key ', miryanPublicKey)
fmt.Println('Private Key : ', raulPrivateKey)
fmt.Println('Public key ', raulPublicKey)
//Encrypt Miryan Message
message:= []byte('the code must be like a piece of music')
label:= []byte(')
hash:=sha256.New()
ciphertext, err:=rsa.EncryptOAEP(hash, rand.Reader, raulPublicKey, message, label)
iferr!=nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf('OAEP encrypted [%s] to n[%x]n', string(message), ciphertext)
fmt.Println()
// Message - Signature
varopts rsa.PSSOptions
opts.SaltLength=rsa.PSSSaltLengthAuto// for simple example
PSSmessage:=message
newhash:=crypto.SHA256
pssh:=newhash.New()
pssh.Write(PSSmessage)
hashed:=pssh.Sum(nil)
signature, err:=rsa.SignPSS(rand.Reader, miryanPrivateKey, newhash, hashed, &opts)
iferr!=nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf('PSS Signature : %xn', signature)
// Decrypt Message
plainText, err:=rsa.DecryptOAEP(hash, rand.Reader, raulPrivateKey, ciphertext, label)
iferr!=nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf('OAEP decrypted [%x] to n[%s]n', ciphertext, plainText)
//Verify Signature
err=rsa.VerifyPSS(miryanPublicKey, newhash, hashed, signature, &opts)
iferr!=nil {
fmt.Println('Who are U? Verify Signature failed')
os.Exit(1)
} else {
fmt.Println('Verify Signature successful')
}
}

Golang Rsa Encrypt

  • Copy lines
  • Copy permalink
Coments are closed
Scroll to top