对接场景:
服务器端使用java生成公钥和私钥,将公钥传递给iOS加密 or 将私钥传递给iOS端使用openssl进行签名,然后在服务器端进行验证
java端:
1、使用常规的KeyPairGenerator类生成公钥和私钥
KeyPairGenerator gen = KeyPairGenerator.getInstance(RSA);
gen.initialize(1024, new SecureRandom());
KeyPair keyPair = gen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
2、常规生成的私钥格式是DER的,而iOS端使用的是PEM格式的(对DER进行了Base64编码+头尾信息),所以需要将生成的密钥文件做一个格式转化
// PEM文件起止字符串
public final static String PUBLIC_KEY_BEGIN = "-----BEGIN PUBLIC KEY-----";
public final static String PUBLIC_KEY_END = "-----END PUBLIC KEY-----";
public final static String PRIVATE_KEY_BEGIN = "-----BEGIN RSA PRIVATE KEY-----";
public final static String PRIVATE_KEY_END = "-----END RSA PRIVATE KEY-----";
private static String replaceNewLine(String strText){
//兼容linux环境和windows环境
strText = strText.replace("\n","\r\n");
String strResult = "";
int intStart = 0;
int intLoc = strText.indexOf("\n", intStart);
while(intLoc != -1){ strResult += strText.substring(intStart, intLoc - 1);
intStart = intLoc + 1; intLoc = strText.indexOf("\n", intStart);
}
strResult += strText.substring(intStart,strText.length());
return strResult;
}
// 转换为iOS端可使用的PEM秘钥格式
public static void savePEMPublicKey(RSAPublicKey pubKey,String strPEMKeyFile) {
String strKey = replaceNewLine(getPublicKeyString(pubKey));
try {
FileWriter keyFile = new FileWriter(strPEMKeyFile);
PrintWriter out = new PrintWriter(keyFile);
out.println(PUBLIC_KEY_BEGIN);
int keyLength = strKey.length();
int lines = keyLength / 64;
for (int i = 0; i < lines; i++) {
out.println(strKey.substring(i * PEM_LINE_LENGTH, i* PEM_LINE_LENGTH + PEM_LINE_LENGTH));
}
out.println(strKey.substring(lines * PEM_LINE_LENGTH, keyLength));
out.println(PUBLIC_KEY_END); out.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void savePEMPrivateKey(RSAPrivateKey privateKey,String strPEMKeyFile) {
String strKey = replaceNewLine(getPrivateKeyString(privateKey));
try {
FileWriter keyFile = new FileWriter(strPEMKeyFile);
PrintWriter out = new PrintWriter(keyFile);
out.println(PRIVATE_KEY_BEGIN);
int keyLength = strKey.length();
int lines = keyLength / PEM_LINE_LENGTH;
for (int i = 0; i < lines; i++) {
out.println(strKey.substring(i * PEM_LINE_LENGTH, i* PEM_LINE_LENGTH + PEM_LINE_LENGTH));
}
out.println(strKey.substring(lines * PEM_LINE_LENGTH, keyLength));
out.println(PRIVATE_KEY_END);
out.close();}
catch (IOException e) {
e.printStackTrace();
}}
iOS端:参考我的资源《iOS和java之间的RSA加密解密、加签认证对接-iOS端》