Skip to content

Commit

Permalink
feat: add rsa key generator command
Browse files Browse the repository at this point in the history
  • Loading branch information
mehditeymorian committed Aug 29, 2022
1 parent 76835dc commit ccf93eb
Show file tree
Hide file tree
Showing 3 changed files with 82 additions and 5 deletions.
6 changes: 5 additions & 1 deletion internal/cmd/key/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ func Key() *cobra.Command {
Example: "jwt key rsa|hmac|ecdsa",
}

c.AddCommand(
rsaCommand(),
)

return c
}

Expand All @@ -36,7 +40,7 @@ func key(_ *cobra.Command, _ []string) {

switch config.SigningMethod(selected) {
case config.RSA:

rsa(nil, nil)
case config.HMAC:

case config.ECDSA:
Expand Down
66 changes: 66 additions & 0 deletions internal/cmd/key/rsa.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package key

import (
"log"
"os"
"strconv"

"github.com/AlecAivazis/survey/v2"
keyGenerator "github.com/mehditeymorian/jwt/internal/key"
"github.com/spf13/cobra"
)

func rsaCommand() *cobra.Command {
c := &cobra.Command{
Use: "rsa",
Short: "generate rsa key",
Example: "jwt key rsa",
Run: rsa,
}

return c
}

func rsa(_ *cobra.Command, _ []string) {

prompt := &survey.Select{
Message: "select number of bits",
Options: []string{
"512",
"1024",
"2048",
"4096",
},
}

var bitsStr string

survey.AskOne(prompt, &bitsStr)

bits, _ := strconv.ParseInt(bitsStr, 10, 64)

publicKey, privateKey := keyGenerator.GenerateRsaKeys(int(bits))

dir, _ := os.Getwd()

publicPem, err := os.Create(dir + "/public.pem")
if err != nil {
log.Fatalf("failed to create public pem file: %v\n", err)
}
defer publicPem.Close()

publicPem.WriteString(publicKey)

privatePem, err := os.Create(dir + "/private.pem")
if err != nil {
log.Fatalf("failed to create private pem file: %v\n", err)
}
defer privatePem.Close()

privatePem.WriteString(privateKey)

log.Printf(`
Publickey: %s/public.pem
PrivateKey: %s/private.pem
`, dir, dir)
}
15 changes: 11 additions & 4 deletions internal/key/rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@ package key
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
)

func GenerateRsaKeys() (*rsa.PublicKey, *rsa.PrivateKey) {
privateKey, err := rsa.GenerateKey(rand.Reader, 1024)
func GenerateRsaKeys(bits int) (string, string) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return nil, nil
return "", ""
}

return &privateKey.PublicKey, privateKey
publicKey := &privateKey.PublicKey
pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509.MarshalPKCS1PublicKey(publicKey)})

pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})

return string(pemEncodedPub), string(pemEncoded)
}

0 comments on commit ccf93eb

Please sign in to comment.