MIHCrypto icon indicating copy to clipboard operation
MIHCrypto copied to clipboard

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

Open testower opened this issue 10 years ago • 3 comments

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

testower avatar Jun 24 '15 17:06 testower

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.

hohl avatar Jun 24 '15 20:06 hohl

This report is from 2015, was this fixed?

chriscoderdr avatar Jan 31 '19 21:01 chriscoderdr

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.

hohl avatar Feb 01 '19 09:02 hohl