File tree Expand file tree Collapse file tree 2 files changed +27
-10
lines changed
key-pair-loader/src/main/java/com/onixbyte/security Expand file tree Collapse file tree 2 files changed +27
-10
lines changed Original file line number Diff line number Diff line change @@ -49,4 +49,29 @@ public interface KeyLoader {
4949 */
5050 PublicKey loadPublicKey (String pemKeyText );
5151
52+ /**
53+ * Retrieves the raw content of a PEM formatted key by removing unnecessary headers, footers,
54+ * and new line characters.
55+ *
56+ * <p>
57+ * This method processes the provided PEM key text to return a cleaned string that contains
58+ * only the key content. The method strips away the
59+ * {@code "-----BEGIN (EC )?(PRIVATE|PUBLIC) KEY-----"} and
60+ * {@code "-----END (EC )?(PRIVATE|PUBLIC) KEY-----"} lines, as well as any new line characters,
61+ * resulting in a continuous string representation of the key, which can be used for further
62+ * cryptographic operations.
63+ *
64+ * @param pemKeyText the PEM formatted key as a string, which may include headers, footers and
65+ * line breaks
66+ * @return a string containing the raw key content devoid of any unnecessary formatting
67+ * or whitespace
68+ */
69+ default String getRawContent (String pemKeyText ) {
70+ // remove all unnecessary parts of the pem key text
71+ return pemKeyText
72+ .replaceAll ("-----BEGIN (EC )?(PRIVATE|PUBLIC) KEY-----" , "" )
73+ .replaceAll ("-----END (EC )?(PRIVATE|PUBLIC) KEY-----" , "" )
74+ .replaceAll ("\n " , "" );
75+ }
76+
5277}
Original file line number Diff line number Diff line change @@ -82,11 +82,7 @@ public EcKeyLoader() {
8282 @ Override
8383 public ECPrivateKey loadPrivateKey (String pemKeyText ) {
8484 try {
85- // remove all unnecessary parts of the pem key text
86- pemKeyText = pemKeyText
87- .replaceAll ("-----BEGIN (EC )?PRIVATE KEY-----" , "" )
88- .replaceAll ("-----END (EC )?PRIVATE KEY-----" , "" )
89- .replaceAll ("\n " , "" );
85+ pemKeyText = getRawContent (pemKeyText );
9086 var decodedKeyString = decoder .decode (pemKeyText );
9187 var keySpec = new PKCS8EncodedKeySpec (decodedKeyString );
9288
@@ -112,11 +108,7 @@ public ECPrivateKey loadPrivateKey(String pemKeyText) {
112108 @ Override
113109 public ECPublicKey loadPublicKey (String pemKeyText ) {
114110 try {
115- // remove all unnecessary parts of the pem key text
116- pemKeyText = pemKeyText
117- .replaceAll ("-----BEGIN (EC )?PUBLIC KEY-----" , "" )
118- .replaceAll ("-----END (EC )?PUBLIC KEY-----" , "" )
119- .replaceAll ("\n " , "" );
111+ pemKeyText = getRawContent (pemKeyText );
120112 var keyBytes = decoder .decode (pemKeyText );
121113 var spec = new X509EncodedKeySpec (keyBytes );
122114 var key = keyFactory .generatePublic (spec );
You can’t perform that action at this time.
0 commit comments