(raw string)
| 55 | } |
| 56 | |
| 57 | func sanitizePrivateKey(raw string) (string, error) { |
| 58 | pk := strings.ReplaceAll(raw, "\r\n", "\n") |
| 59 | pk = strings.ReplaceAll(pk, "\r", "\n") |
| 60 | pk = stripANSIEscape(pk) |
| 61 | pk = strings.ToValidUTF8(pk, "") |
| 62 | pk = strings.TrimSpace(pk) |
| 63 | |
| 64 | normalized := pk |
| 65 | if block, _ := pem.Decode([]byte(pk)); block == nil { |
| 66 | // Attempt to reconstruct from the textual payload. |
| 67 | if reconstructed, err := rebuildPEM(pk); err == nil { |
| 68 | normalized = reconstructed |
| 69 | } else { |
| 70 | return "", fmt.Errorf("private_key is not valid pem: %w", err) |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | block, _ := pem.Decode([]byte(normalized)) |
| 75 | if block == nil { |
| 76 | return "", fmt.Errorf("private_key pem decode failed") |
| 77 | } |
| 78 | |
| 79 | rsaBlock, err := ensureRSAPrivateKey(block) |
| 80 | if err != nil { |
| 81 | return "", err |
| 82 | } |
| 83 | return string(pem.EncodeToMemory(rsaBlock)), nil |
| 84 | } |
| 85 | |
| 86 | func ensureRSAPrivateKey(block *pem.Block) (*pem.Block, error) { |
| 87 | if block == nil { |
no test coverage detected