Skip to content

Commit

Permalink
refactor: rsa generate file
Browse files Browse the repository at this point in the history
  • Loading branch information
710leo committed Oct 12, 2023
1 parent c3b8146 commit 68732d6
Showing 1 changed file with 12 additions and 8 deletions.
20 changes: 12 additions & 8 deletions pkg/secu/rsa.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,20 +63,24 @@ func GenerateKeyWithPassword(privateFilePath, publicFilePath, password string) e
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
}
encryptedBlock, err := x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(password), x509.PEMCipherAES256)
if err != nil {
return fmt.Errorf("failed to EncryptPEMBlock: %v", err)

var encryptedBlock *pem.Block
if password != "" {
encryptedBlock, err = x509.EncryptPEMBlock(rand.Reader, block.Type, block.Bytes, []byte(password), x509.PEMCipherAES256)
if err != nil {
return fmt.Errorf("failed to EncryptPEMBlock: %v", err)
}
} else {
encryptedBlock = block
}

privateKeyFile, err := os.Create(privateFilePath)
if err != nil {
return fmt.Errorf("failed to create private key file: %v", err)
}
defer privateKeyFile.Close()
if password == "" {
err = pem.Encode(privateKeyFile, block)
} else {
err = pem.Encode(privateKeyFile, encryptedBlock)
}

err = pem.Encode(privateKeyFile, encryptedBlock)
if err != nil {
return fmt.Errorf("failed to pem.Encode: %v", err)
}
Expand Down

0 comments on commit 68732d6

Please sign in to comment.