ideawu / objective-c-rsa Goto Github PK
View Code? Open in Web Editor NEWDoing RSA encryption and decryption with Objective-C on iOS
Home Page: http://www.ideawu.com/blog/post/132.html
License: Other
Doing RSA encryption and decryption with Objective-C on iOS
Home Page: http://www.ideawu.com/blog/post/132.html
License: Other
字符串加密都没有问题,现在是我们有一个NSData类型的数据
数据格式是{0x97, 0x0, 0x10}
先用+ (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey加密
接着用+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey解密
你会发现解密出来的数据只有1字节,也就是说代码中用0x0做了分隔符
In order to properly encrypt a string with a public key, Keychain Entitlements must be enabled.
你好,我们 App 在发布到 App Store 后,RSA 加密失败率挺高的,但是我们本地开发调试时,没有遇到过,也无法重现。发生错误的机型和系统,基本全覆盖。
需要说明的是,在这之前我们对代码做过一些修改。首先是把 RSA 类改为了 NSString 的分类;其次,由于需要对钥匙串做 Delete -> Add -> Matching
的操作,在多线程环境下发生了错误,就对这一部分代码加了 @synchronized
同步锁,如下:
@synchronized ([UIApplication sharedApplication]) {
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PubKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
[publicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[publicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)publicKey);
// Add persistent version of the key to system keychain
[publicKey setObject:data forKey:(__bridge id)kSecValueData];
[publicKey setObject:(__bridge id)kSecAttrKeyClassPublic forKey:(__bridge id)kSecAttrKeyClass];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnPersistentRef];
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
[publicKey removeObjectForKey:(__bridge id)kSecValueData];
[publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[publicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
RSA.h的注释:
enc with private key NOT working YET!
程序从运行时始终在前台,加密是没有问题的,但是程序退到后台时,打开微信,QQ等应用进行操作后,再次进入自己的程序后,RSA加密就为空了,这是什么原因呢?
NSData *decryData= [[NSData alloc]initWithBytes:u->data length:256];
NSData *priData = [RSA decryptData:decryData privateKey:priKey];
decryData有值,priData 没有值。
貌似在这里返回为空的,是不是不能够解密长度为256的data。
unsigned char *c_key = (unsigned char *)[d_key bytes];
unsigned int idx = 22; //magic byte at offset 22
if (0x04 != c_key[idx++]) return nil;
ps,我需要加密和解密的都是byte数组,以为提供的接口是nsdata,所以我需要转为BYTE。
最后还是要感谢你的分享。
并发的加解密会导致加密和解密失败
I created public key and private key by command line like in website https://rietta.com/blog/2012/01/27/openssl-generating-rsa-key-from-command/
It encrypt with public key very good but decWithPrivKey always empty.
Pls help me. Tks
同样的方法,js怎么通过公钥解密怎么做啊?
我自己想改成NSASCIIStringEncoding编码的加密方式,因为分段加密的分段逻辑是我们自己做的,但是考虑到汉字是多字节, 用NSASCIIStringEncoding编码后和密钥长度进行比较然后分段才才合适,但是我简单的改了编码方式后就出问题了,请问如何修改编码方式呢?
IOS10 回傳都會nil,有沒有解決方法?
SecKeyRef keyRef = [self addPrivateKey:privKey];
锁屏的时候这行代码不执行,解密就返回nil
前一段时间做 RSA 加密,使用了这个库,上线后出现大量解密失败的数据,整了这么大个坑,年终奖都要泡汤了,心里哇凉哇凉的。。。
+[RSA addPublicKey:]
, +[RSA addPrivateKey:]
这两个方法线程不安全,并发读写 Keychain 数据时,会出现获取密钥失败的情况,导致加密失败
读写 Keychain 数据时,用了一个默认的标记 tag RSAUtil_PubKey
、RSAUtil_PrivKey
,许多 SDK 都使用了这个库,而且没有修改 tag,如果不修改 tag,并发环境下,有可能读到其他 SDK 的密钥,导致加密数据错乱
dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
for (int i = 0; i< 100; i++) {
dispatch_async(queue, ^{
NSString *test = [[params md5String] uppercaseString];
NSString *test1 = [self p_publicKey];
NSString *test2 = [RSA encryptString:test publicKey:test1];
if (test2.length == 0) {
NSLog(@"出错啦");
NSLog(@"md5===%@", test);
NSLog(@"pubkey===%@", test1);
NSLog(@"encrypted===%@", test2);
} else {
NSLog(@"任务ccc===%@", test2);
}
});
}
会有出现test2为空的情况
I downloaded this project and run it, but it's returning empty values in the log:
2017-03-09 13:40:20.992 RSAUtil[1260:44798] Original string(207): hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world! hello world!
2017-03-09 13:40:21.007 RSAUtil[1260:44798] Enctypted with public key:
2017-03-09 13:40:21.015 RSAUtil[1260:44798] Decrypted with private key:
2017-03-09 13:40:21.024 RSAUtil[1260:44798] (PHP enc)Decrypted with private key:
2017-03-09 13:40:21.033 RSAUtil[1260:44798] (PHP enc)Decrypted with public key:
Please advise.
Thank you.
As stated in the Developer Program License Agreement:
Section 2.3, You certify that (i) none of the Licensed Applications contains, uses or supports any data encryption or cryptographic functions; or (ii) in the event that any Licensed Application contains, uses or supports any such data encryption or cryptographic functionality, You certify that You have complied with the United States Export Administration Regulations, and are in possession of, and will, upon request, provide Apple with a PDF copy of Your Encryption Registration Number (ERN), or export classification ruling (CCATS) issued by the United States Commerce Department, Bureau of Industry and Security and PDF copies of appropriate authorizations from other countries that mandate import authorizations for that Licensed Application, as required.
https://developer.apple.com/programs/terms/ios/standard/ios_program_standard_agreement_20140909.pdf
Or even better, have any successfully submit their app to the store with this code?
请问demo中的密钥对从哪里来呀?为什么我用openssl生成的pem格式的密钥对在此解密不出来,在终端中使用openssl能解密出来?
Hi, I have a key from Java that looks like
OpenSSLRSAPublicKey{modulus=3b11f044.....58df890,publicExponent=10001}
Do I just use the modulus string as the public key or would I need to somehow convert this whole key to another format to use?
Thanks
公钥和私钥和你的格式一样,但是为什么可以加密 但解密出来的就是nil 啊 ?急问
私钥加密不行啊~~~
Unpadding is there for a reason. Without unpadding you are not even sure if you're decrypting with the right key.
Do you have any experience creating this kind of crypto related code, and if not, why are you posting it here?
-----BEGIN RSA PUBLIC KEY-----
这种格式的公钥如何加密呢?能不能支持一下?
Hello, ideawu,
When I use RSA api decryptData:publicKey:, I meet this error code, -25308
But this occurs very few times.
请问有C#服务器的加密和解密算法么?
Dear all,
I have successfully generated the signature value (pkcs7 data) with swiftRSA. Now i want to embed that signature into pdf can one please tell me how to achive this in ios or share me if you have any demo code.
I am student , working on my sem project...
Thanks & Regards,
Naresh.
Hi, I have an issue with this RSA implementation and any help would be appreciated.
The first issue is that with rsa keys fetched from server(generated on server side), the RSA encryption fails on: ' if (memcmp(&c_key[idx], seqiod, 15)) return(nil);' but if i use they key from Usage section, i get some encrypted data.
What i am missing here?
以下是我的key:
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDCK6xfyRdsRmM1jkfTFznPlLRgL46R+PsVjwpucZljLF4Vsjx4
Vagfh/Vml8n3c6XdwC+//es1j5ia6jUkMoU8qYsAH0zEgnMx/RLW3L93dt60kCUN
0m9jd+gsSlFSAAprqGm6G2IPETWL7YKWSJuJWVVmv+pDP7t+ORl0WuK7GQIDAQAB
AoGAbTssaWYy6xJd1U8JUNMMDp7VKhcW2T974JDriV4WsBfRhdsS8Y8eWT6e6uwR
Dkfc03a+Zf9uRl9VtjBzXL2e/Zor0WytV/vQ/f0GXMBs5lQ27WFtED8rzp3qA4CJ
xxxGi2fe8leStGLTnYbGv/qcFNKlF0DZ+Ep6gw37rFBkoEECQQDqO0OuziMEJ50P
yUqsO5zUeZ7OzOL4SdkHA8ttGQhf8ShggQv6NBBKbjLzVnptYK45Q1VQukIECgSm
J7jv/dTlAkEA1DdMDy4wxnmeqW5dV4byGKatirjlMP96GPPsIwln/ykDaPHNf2Jo
D1qplzyWgBKdQH+LBM061b2L2KryMF2+JQJAK4kKYnIz9fC685UxSOPnmWJljwBr
60Qmj3Q4GjX95X84Rv+VT1Lf+EWVOL9JEA1ZNJF8SP3liUSnao6VhB3EtQJAK+2e
Yu4OzqbSPwRHchzO9GdcOQD5AGGB5rRnRwFlc54LxKd5AEtgev0radDy3mP8BSPh
pQbOjPwFfL42D+j3uQJAWX6v1UnfsGUAJBNuosdA31Xn7+S0pDd1c7zEaI2K7Szz
xPiDgP9ZVNhKdhg5P2LBkEglSxBKLdCv5O1La27Y4w==
-----END RSA PRIVATE KEY-----
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCK6xfyRdsRmM1jkfTFznPlLRg
L46R+PsVjwpucZljLF4Vsjx4Vagfh/Vml8n3c6XdwC+//es1j5ia6jUkMoU8qYsA
H0zEgnMx/RLW3L93dt60kCUN0m9jd+gsSlFSAAprqGm6G2IPETWL7YKWSJuJWVVm
v+pDP7t+ORl0WuK7GQIDAQAB
-----END PUBLIC KEY-----
生成方法 参考
http://blog.csdn.net/lvxiangan/article/details/45318443
生成的公钥私钥如下
NSString *pubkey3 = @"-----BEGIN PUBLIC KEY-----\
\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0kEAhcOo1tdfjDIJBVhK\
\nRHadXe3dkJNmcku93lXOIdP4KA60KiymAnCsDn5hnKXBsw9JRLjfVx7XUdXgo+ED\
\nQ/ik30tvRad7j7IMT4y+a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zlNGlCA/HwSezx69NAXYowznol8bmIN9HM92XBAhLH8BOD8Ud\
\nz7Ue5/BFQDzkW+XvI4bcta8OXSJ3cGBUsfiiaACC32+RtxiktTFR0Q73QJj8qSHp\
\nn0TyVycm556yZNZGU7XwcDkPKBzMeXLu4S6q8tM8tvOJpvgXu7CIsDLnAoGBAOMn\
\n/U03JhpK8bUG1yxyTUOmyl6sSvSbFpthkdRhXWWmx/xOaEp1/eGHW1RJWzGR9Epz\
\nksOCrwukd3cKC9m9E/iRG+mE8I2DwU2uZFOQhZ2kS/9Hb1F/MxM0SZcAo0cAbBzD\
\nrYL8i9WoOr37wSAdqjIfnj/hf3Za509niUvI5pQ5AoGANolpu0bssBUd0/GBCEwF\
\nBhkjtfRe2pyk/D77JQlZGD+SM0TERG40HE/cumR2AI3eyPFdj/DEsGHx9bjf2Iwl\
\n2kAnB9cXbipvpfBi89MM9xDZgVzF4NRQoCHXBV/i95e/tcHCCqIocjmW1eoKGfX5\
\nRjB6azwSL8OC9p8fx+XuCAkCgYEAg77bwH7t0G4LBc0z2wloGoaP9JzE1F1mnTPX\
\nmm/l9WDnuEPZZOZOGxGgPKBXDcbzAoNJaa9PytbWmunuuZhaDt5KbAO4aLszz9QH\
\nSBgYBrgVg7dwrrmxa7/1tmieSj3KdlxfNAs5Ju/tMebjuba60VtZMv+cJ47NfVY1\
\nYQjiArECgYA229nt/888DntuvZQrSde4cEtthVFahgNqHq87lyC1htuwMirKkN+e\
\nnyFw/TV7RcDUctoJ9DRGfwwgIVGdzKx/2iiktfejryBxZX8RB/uIBEKuf+Z6VT8S\
\nkiAnhIGqUu8DUniqsyRztGTTcPx3DDCLBeo/00Q2k9ri1i7+r3Fj1A==\
\n-----END RSA PRIVATE KEY-----";
demo :
NSData *oridata = UIImagePNGRepresentation([UIImage imageNamed:@"QQ20150805"]);
NSLog(@"oridata with public key: %@", oridata);
NSData *encdata = [RSA encryptData:oridata publicKey:pubkey];
NSLog(@"Enctypted with public key: %@", encdata);
result:Enctypted with public key: null
调试发现进入如下if语句里,不知为何?因为图片数据比较大?
size_t outlen = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
if(srclen > outlen - 11){
CFRelease(keyRef);
return nil;
}
这个好像只提供了加密解密,没有提供签名.签名是需要使用己方私钥加密的.
How to decrypt files/text in Android client?
使用公钥加密后 java后台不能解密
I tried the demo in the README.md. If the *pubkey and *privkey is PKCS#8 format, it works good. But when I replace the *pubkey and *privkey with PKCS#1 format, the decrypted is empty.
Hi,
我最近在用 Swift 写一个类似的 RSA Public Key 的 Framework。比较奇怪的是 iOS 没问题,但 OSX 却卡在了 SecItemAdd 上了。
我用你的 Objective-C 代码简单弄了一个 OSX Framework,也是卡在同一个地方。无法通过 SecItemAdd 添加 Public Key,返回错误 -25303。应该是不能在 CFDictionary 里面包含 kSecAttrKeyClassPublic。如果删掉这个函数,Keychain Access 会弄一个 Symmetric Key 在里面,但是肯定是出错了,现在都无法通过 Keychain Access 删掉这个错误的 Key。
网上找了一下,都是关于 iOS 的,没有 OSX 的,你觉得有没有解决办法呢?
感谢!
Sorry for my ignorance, but what is the equivalent openssl command for to encrypt a string using this your code?
I have tried openssl rsautl -in test.txt -out output.txt -encrypt -pubin -inkey public.pem
but gets different result from encrypting the same text using this library.
I am trying to verify that what I have encrypted in iOS will be able to decrypt using another library.
Thanks
我对 @"123456"
加密后,, 运行多次,发现每次结果都不一样
Xcode8上运行demo失败,加密一直为空。
Hello,
I want to encrypt a pdf file with public key before sending it to the server where i can decrypt it with a private key.
Before that, I was using the demo application on ios and I was trying to read pdf file as NSData then generate the encrytion and decryption result in order to validate the output of the hole process , in other words , I wanted to check if the output file after the encrytion and decryption is still a valid pdf file like the original one.
Unfortenetly , it seems that the output file is corrupted since I get this error when I tried to show the final pdf file on a webview .
failed to find `endstream' marker; trying to recover.
FlateDecode: decoding error: invalid bit length repeat.
Hello,
i found this useful obc-c class and tested it. It works on iOS but not on OSX. I was searching all over the internet an i didn't find any class for OSX. Can be this somehow modified or are u planning OSX support?
Thanks for info, have a nice day
很好用的一个 RSA 第三方库,希望能够加上解密的功能。
iphone6 iOS10.1.1,有时会出现加密失败的情况,错误代码为:SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef); 调用,返回的status 是-25300,
这个问题不是必现,手机放个几个小时,然后第一次build的时候想对比较容易出现,连续build的话后面就很难重现。
Sometimes the code would return nil at this point:
on RSA.m line 150
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
I'm getting a status -34018
Sometimes it works just fine. Others it doesn't. Always using the same Public Key.
Why could that happen?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.