英文:
Java remove public key header and footer from string
问题
Hi,我正在尝试移除一个以字符串形式存储的公钥的标题和页脚。我已经成功地找到了如何移除"begin"标题的方法,即通过删除从第一个"\n"开始的所有内容,
String s1 = pKey.substring(pKey.indexOf("\n")+1);
但是,我现在正努力删除页脚,从最后一个"\n"一直到结尾。可能有一种更简洁的方法来同时移除它们。
英文:
Hi I am trying to remove the header and footer off a public key that is being stored as a string. I have managed to work out how to remove the "begin" header by removing everything up to the first "\n",
-----BEGIN PUBLIC KEY-----\n
with this code.
String s1 = pKey.substring(pKey.indexOf("\n")+1);
I am however struggling to remove the footer from the end up to the last "\n".
\n-----END PUBLIC KEY-----
There must be a cleaner way to remove them both.
答案1
得分: 4
公钥可以是这样的 -----BEGIN PUBLIC KEY----\nkey\n-----END PUBLIC KEY-----
。
要从字符串中删除头部和尾部,您可以使用以下代码:
pKey.substring(pKey.indexOf("\n")+1, pKey.lastIndexOf("\n"));
或者另一种方式是直接将头部和尾部替换为空,因为它们不会出现在密钥中。
英文:
Public key can be Some thing like this "-----BEGIN PUBLIC KEY----\nkey\n-----END PUBLIC KEY-----"
So to remove header and footer from string you can use
pKey.substring(pKey.indexOf("\n")+1, pKey.lastIndexOf("\n"));
or other way just replace header and footer directly by empty , since it won't be present in key
答案2
得分: 4
我一直在使用以下的实用方法来解析文本中的RSA公钥:
public static RSAPublicKey parsePKCS8PublicKey(String publicKey) {
publicKey = publicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\n", "")
.trim();
byte[] bytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException(e);
}
}
请注意,代码部分没有翻译。
英文:
I've been using the following util method to parse RSA public keys from text:
public static RSAPublicKey parsePKCS8PublicKey(String publicKey) {
publicKey = publicKey
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\n", "")
.trim();
byte[] bytes = Base64.getDecoder().decode(publicKey);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
try {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (GeneralSecurityException e) {
throw new IllegalArgumentException(e);
}
}
答案3
得分: 3
你可以使用以下代码:
String s1 = pKey.replaceAll("^.*\\n|\\n-+END PUBLIC KEY-+$", "");
正则表达式详解
^.*\\n
- 字符串开头和第一行后面的换行符|
- 或者\\n-+END PUBLIC KEY-+$
- 换行符后跟1个或多个连字符,然后是END PUBLIC KEY
,然后是一个或多个连字符,直到字符串的末尾。
英文:
You may use
String s1 = pKey.replaceAll("^.*\n|\n-+END PUBLIC KEY-+$", "");
Regex details
^.*\n
- start of string and the first line with a newline|
- or\n-+END PUBLIC KEY-+$
- a newline char followed with 1+-
chars, thenEND PUBLIC KEY
and then one or more hyphens till the end of the string.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论