iOS和java之间的RSA加密解密、加签认证对接

1 篇文章 0 订阅
1 篇文章 0 订阅

对接场景:

服务器端使用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端

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值