hohl / MIHCrypto

OpenSSL wrapper for Objective-C [cryptography]
MIT License
341 stars 68 forks source link

Error re-creating keys after encoding and decoding to/from strings #30

Open testower opened 9 years ago

testower commented 9 years ago

I'm trying to create instances of MIHRSAPublicKey and MIHRSAPrivateKey using initWithData: after they have been encoded as strings from their data values, and decoded back into data values.

See following code example. The asserts on data equality succeed but the asserts on key and keypair equality fail.

Not sure if this is a bug, or me misunderstanding the intended usage of these APIs. Would you be able to help?

  MIHRSAKeyFactory *keyFactory = [[MIHRSAKeyFactory alloc] init];
  MIHKeyPair *keyPair = [keyFactory generateKeyPair];
  MIHRSAPublicKey *publicKey = keyPair.public;
  MIHRSAPrivateKey *privateKey = keyPair.private;
  NSData *publicKeyData = [publicKey dataValue];
  NSData *privateKeyData = [privateKey dataValue];

  NSString *publicKeyString = [publicKeyData MIH_base64EncodedString];
  NSString *privateKeyString = [privateKeyData MIH_base64EncodedString];

  NSData *testPublicKeyData = [NSData MIH_dataByBase64DecodingString:publicKeyString];
  NSData *testPrivateKeyData = [NSData MIH_dataByBase64DecodingString:privateKeyString];

  assert([testPublicKeyData isEqualToData:publicKeyData]); // succeeds
  assert([testPrivateKeyData isEqualToData:privateKeyData]); // succeeds

  MIHRSAPublicKey *testPublicKey = [[MIHRSAPublicKey alloc] initWithData:testPublicKeyData];
  MIHRSAPrivateKey *testPrivateKey = [[MIHRSAPrivateKey alloc] initWithData:testPrivateKeyData];

  assert([testPublicKey isEqual:publicKey]); // fails
  assert([testPrivateKey isEqual:privateKey]); // fails

  MIHKeyPair *testKeypair = [[MIHKeyPair alloc] init];
  testKeypair.public = testPublicKey;
  testKeypair.private = testPrivateKey;

  assert([testKeypair isEqualToPair:keyPair]); // fails
hohl commented 9 years ago

You're right. Thats a bug caused by missing implementation of isEqual: and hash in MIHRSAPrivateKey and MIHRSAPublicKey. Thanks for pointing out. I'll fix this in the next release.

chriscoderdr commented 5 years ago

This report is from 2015, was this fixed?

hohl commented 5 years ago

I don't think so. As described in my comment from 2015 it would be easy to fix, by implementing isEqual: and hash methods, but I never did so. If you need this functionality, fastest way to get it into this library would be to implement it yourself and create a pull-request. Simplest possible solution for hash would be to call dataValue and create a hash of the returned string. For isEqual: simple compare the individual parameters of the key.