请问在RSA算法中,如何将已存在的公钥,私钥传入算法呢?
RT 看了好多的例子,基本都是自己生成的公钥和私钥.如何做到将已存在的公钥,私钥传入算法呢
请达人帮忙.
//p:F0963DD3
//q:F9D7FBA3
//E:100001
//N:EACD1CCCA57C3E59
//D:CB67A64EDF4B725D
如何将这样的格式(String)作为参数传入呢?
------解决方案--------------------读公钥:(密钥库是用keytool生成的,用的类都是java.security.*的)
String keyfile = "D:\\ttt\\server.jks "; //密钥库路径
String keyalias = "alice "; //密钥库别名
char[] keypassword = "password ".toCharArray(); //密钥库密码
KeyStore keystore = KeyStore.getInstance( "JKS ");
FileInputStream fis = new FileInputStream(keyfile);
keystore.load(fis, keypassword);
Key pubKey = keystore.getKey(keyalias, keypassword);
取私钥:
KeyStore keystore = KeyStore.getInstance( "JKS ");
FileInputStream fis = new FileInputStream(keyfile);
keystore.load(fis, keypassword);
KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(keyalias, new KeyStore.PasswordProtection(keypassword));
PrivateKey myPrivateKey = pkEntry.getPrivateKey();
------解决方案--------------------我程序中的rsa加密是自己实现的,很简单,就是用一下BigInteger(在java.math包中),贴出来给你参考一下.
/**
* 加密数据.加解密的区别在于填充数据的不同
* @param input String
* 输入数据.要求为16进制BCD表示的数据
* @param module String
* 模
* @param key String
* 公钥/私钥
* @return String
* 加密完毕的数据.16进制BCD表示
*/
public static String encrypt(String input, String module, String key) {
BigInteger pubExp = new BigInteger( "00 "+key, 16);
BigInteger mod = new BigInteger( "00 "+module, 16);
StringBuffer sb = new StringBuffer();
sb.append( "0001 ");
for (int i = 0; i < module.length() - input.length() - 4; i++) {
sb.append( 'F ');
}
sb.append( "00 ");
sb.append(input);
BigInteger edgeInput = new BigInteger(sb.toString(), 16);
BigInteger b = edgeInput.modPow(pubExp, mod);
return b.toString(16);
}
------解决方案--------------------一般来说比较少会直接使用PQNED这样保存Key
Java另外有提供方法去保存的:
KeyPairGenerator generator = KeyPairGenerator.getInstance( "RSA ");
generator.initialize(512);
KeyPair pair = generator.generateKeyPair();
byte[] encode = pair.getPrivate().getEncoded();
PKCS8EncodedKeySpec pkcs = new PKCS8EncodedKeySpec(encode);
PrivateKey privateKey = KeyFactory.getInstance( "RSA ").generatePrivate(pkcs);
System.out.println(Arrays.equals(encode, privateKey.getEncoded()));
encode = pair.getPublic().getEncoded();
X509EncodedKeySpec x509 = new X509EncodedKeySpec(encode);
PublicKey publicKey = KeyFactory.getInstance( "RSA ").generatePublic(x509);
System.out.println(Arrays.equals(encode, publicKey.getEncoded()));