Java 生成 RSA 密钥对并将私有编码为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1709441/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 21:46:45 来源:igfitidea点击:
Generate RSA key pair and encode private as string
提问by Angela
I want to generate 512 bit RSA keypair and then encode my public key as a string. How can I achieve this?
我想生成 512 位 RSA 密钥对,然后将我的公钥编码为字符串。我怎样才能做到这一点?
采纳答案by jitter
For output as Hex-String
输出为十六进制字符串
import java.security.*;
public class Test {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
StringBuffer retString = new StringBuffer();
for (int i = 0; i < publicKey.length; ++i) {
retString.append(Integer.toHexString(0x0100 + (publicKey[i] & 0x00FF)).substring(1));
}
System.out.println(retString);
}
}
For output as byte values
输出为字节值
import java.security.*;
public class Test {
public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchProviderException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(512);
byte[] publicKey = keyGen.genKeyPair().getPublic().getEncoded();
StringBuffer retString = new StringBuffer();
retString.append("[");
for (int i = 0; i < publicKey.length; ++i) {
retString.append(publicKey[i]);
retString.append(", ");
}
retString = retString.delete(retString.length()-2,retString.length());
retString.append("]");
System.out.println(retString); //e.g. [48, 92, 48, .... , 0, 1]
}
}