Skip to content

Commit 82ea62c

Browse files
(fix) Preserve Newline Characters in Multi-line PrivateKeys in Analyzer (#3988)
* replace spaces with newlines in privatekey analyzer * use detector's regex --------- Co-authored-by: Kashif Khan <[email protected]>
1 parent 6bffdd0 commit 82ea62c

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

pkg/analyzer/analyzers/privatekey/privatekey.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"errors"
77
"fmt"
88
"os"
9+
"regexp"
910
"strings"
1011
"sync"
1112
"time"
@@ -130,6 +131,9 @@ func AnalyzeAndPrintPermissions(cfg *config.Config, key string) {
130131
return
131132
}
132133

134+
// key entered through command line may have spaces instead of newlines, replace them
135+
token = replaceSpacesWithNewlines(token)
136+
133137
info, err := AnalyzePermissions(context.Background(), cfg, token)
134138
if err != nil {
135139
color.Red("[x] Error: %s", err.Error())
@@ -301,3 +305,26 @@ func analyzeGithubUser(ctx context.Context, parsedKey any) (*string, error) {
301305
func analyzeGitlabUser(ctx context.Context, parsedKey any) (*string, error) {
302306
return privatekey.VerifyGitLabUser(ctx, parsedKey)
303307
}
308+
309+
// replaceSpacesWithNewlines extracts the base64 part, replaces spaces with newlines if needed, and reconstructs the key.
310+
func replaceSpacesWithNewlines(privateKey string) string {
311+
// Regex pattern to extract the key content
312+
re := regexp.MustCompile(`(?i)(-----\s*BEGIN[ A-Z0-9_-]*PRIVATE KEY\s*-----)\s*([\s\S]*?)\s*(-----\s*END[ A-Z0-9_-]*PRIVATE KEY\s*-----)`)
313+
314+
// Find matches
315+
matches := re.FindStringSubmatch(privateKey)
316+
if len(matches) != 4 {
317+
// no need to process
318+
return privateKey
319+
}
320+
321+
header := matches[1] // BEGIN line
322+
base64Part := matches[2] // Base64 content
323+
footer := matches[3] // END line
324+
325+
// Replace spaces with newlines
326+
formattedBase64 := strings.ReplaceAll(base64Part, " ", "\n")
327+
328+
// Reconstruct the private key
329+
return fmt.Sprintf("%s\n%s\n%s", header, formattedBase64, footer)
330+
}

0 commit comments

Comments
 (0)