昨天需要把android版的用户注册功能,移植到ios版上。android版会将用户填写的手机号和密码,用RSA加密后发到server
android版没有使用证书,是直接用modulus和exponent就加密了
RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus), new BigInteger(publicExponent));
return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
byte[] originData = plaintext.getBytes();
Cipher ci = Cipher.getInstance("RSA");
ci.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedData = ci.doFinal(originData);
return new String(Hex.encodeHex(encryptedData));
ios rsa link1
ios rsa link2
ios rsa link3
ios rsa link4
这个就非常简单了,网上的例子很多,把我们自己的例子也贴出来:
+(NSString*) encryptWithRSA:(NSString*)plainText
{
SecKeyRef publicKey = [self getPublicKey];
size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
uint8_t *cipherBuffer = malloc(cipherBufferSize);
uint8_t *nonce = (uint8_t *)[plainText UTF8String];
SecKeyEncrypt(publicKey,
kSecPaddingOAEP,
nonce,
strlen((char*)nonce),
&cipherBuffer[0],
&cipherBufferSize);
NSData *encryptedData = [NSData dataWithBytes:cipherBuffer length:cipherBufferSize];
return [encryptedData base64EncodedString];
}
+(SecKeyRef) getPublicKey
{
NSString *certPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
NSData *certificateData = [[NSData alloc] initWithContentsOfFile:certPath];
SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certificateData);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus status = SecTrustCreateWithCertificates(certificate,policy,&trust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(trust, &trustResult);
}
return SecTrustCopyPublicKey(trust);
}
URSA
总之,用modulus + exponent在IOS上找不到办法,用证书在node上没调通。最后也不想在这个细枝末节上再继续纠结了,决定也不加密了,就客户端用base64编码,server解码得了。一下就弄好了,下面也把代码贴上来
+(NSString*) encodeWithBase64:(NSString*)plainText
{
NSData *data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
return [data base64EncodedString];
}
decodedInfo = new Buffer(info, 'base64').toString();
普通字符串转base64:
var a = new Buffer('key1=value1&key2=value2').toString('base64');
new Buffer(a, 'base64').toString();