iOS is giving decryption error: RSAdecrypt wrong input (err -27) - swift

Diclaimer
In the first place this is a recap on recent development activities.
I am writing this down for lost souls - as I could not find any post containing this error except:
RSA encryption/decryption implementing in Swift from Android Java code
The Problem
During decryption of a cyphertext with a given private key, iOS throws this error:
Optional(Swift.Unmanaged<__C.CFErrorRef>(_value: Error Domain=NSOSStatusErrorDomain Code=-50 "RSAdecrypt wrong input (err -27)" UserInfo={numberOfErrorsDeep=0, NSDescription=RSAdecrypt wrong input (err -27)}))
For the sake of readability and search engine optimization the same error is given in a style which is more easy to be read:
Optional(
Swift.Unmanaged<__C.CFErrorRef>(
_value: Error
Domain=NSOSStatusErrorDomain
Code=-50 "RSAdecrypt wrong input (err -27)"
UserInfo={
numberOfErrorsDeep=0,
NSDescription=RSAdecrypt wrong input (err -27)
}
)
)
The Question
What are likely reasons for receiving this error?
However
My knowledge so far is given in one of the answers below ;-)

As mentioned by #not2savvy, I better answer as far as known here instead of 'within the question part' ... .. .
The good news
You probaply solved several problems already, such as:
Base64 decoding error
-> In case your ciphertext/private key had to be transformed back to binary
Algorithm error
-> Mismatch of PrivateKey in regards of the needed algorithm (e.g.: RSA)
Size error
-> Mismatch of Ciphertext- and Keysize
... .. . you are not far from the solution ;-)
The bad news
You probaply have the wrong private key to decrypt the given cyphertext.
Something else is wrong with your key, which I do know nothing about.

Related

IndexOutOfRangeException in zlib compression of iTextSharp

I found a pretty annoying and serious problem in iTextSharp's zlib implementation. Very hard to reproduce because it depends on the actual data going into the PDF but in some circumstances, the following exception occurs:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.util.zlib.Tree.d_code(Int32 dist)
at System.util.zlib.Deflate.compress_block(Int16[] ltree, Int16[] dtree)
In System.util.zlib.Tree.cs, there is obviously no range check, only an assumption of things never going wrong. Adding the following (byte) cast seems to be a solution:
internal static int d_code(int dist){
return ((dist) < 256 ? _dist_code[dist] : _dist_code[256+(byte)((dist)>>7)]);
}

Visual Studio, reading file, get bad ptr

I, recently I use fopen_s:
errno_t err = fopen_s( &fp, filename, mode );
and I get errno_t as zero, which means no error occured, but I didn't get a valid fp, actually, it is unchanged.
What possible is this situation?
Apparently, it encounter a NULL file pointer, which is not as expected, for why it encounter such a problem, please refer to this: Bad Pointer error when using File* object

Encrypting 16 bytes of UTF8 with SecKeyWrapper breaks (ccStatus == -4304)

I'm using Apple's SecKeyWrapper class from the CryptoExercise sample code in the Apple docs to do some symmetric encryption with AES128. For some reason, when I encrypt 1-15 characters or 17 characters, it encrypts and decrypts correctly. With 16 characters, I can encrypt, but on decrypt it throws an exception after the CCCryptorFinal call with ccStatus == -4304, which indicates a decode error. (Go figure.)
I understand that AES128 uses 16 bytes per encrypted block, so I get the impression that the error has something to do with the plaintext length falling on the block boundary. Has anyone run into this issue using CommonCryptor or SecKeyWrapper?
The following lines...
// We don't want to toss padding on if we don't need to
if (*pkcs7 != kCCOptionECBMode) {
if ((plainTextBufferSize % kChosenCipherBlockSize) == 0) {
*pkcs7 = 0x0000;
} else {
*pkcs7 = kCCOptionPKCS7Padding;
}
}
... are the culprits of my issue. To solve it, I simply had to comment them out.
As far as I can tell, the encryption process was not padding on the encryption side, but was then still expecting padding on the decryption side, causing the decryption process to fail (which is generally what I was experiencing).
Always using kCCOptionPKCS7Padding to encrypt/decrypt is working for me so far, for strings that satisfy length % 16 == 0 and those that don't. And, again, this is a modification to the SecKeyWrapper class of the CryptoExercise example code. Not sure how this impacts those of you using CommonCrypto with home-rolled wrappers.
I too have encountered this issue using the CommonCrypto class but for ANY string with a length that was a multiple of 16.
My solution is a total hack since I have not yet found a real solution to the problem.
I pad my string with a space at the end if it is a multiple of 16. It works for my particular scenario since the extra space on the data does not affect the receipt of the data on the other side but I doubt it would work for anyone else's scenario.
Hopefully somebody smarter can point us in the right direction to a real solution.

AudioSessionInitialize returning inscrutable error code

I'm calling AudioSessionInitialize like so
OSStatus result = AudioSessionInitialize(NULL,NULL,interruptionListener,NULL);
and getting the result 0xbfffde94 (i.e. -1073750040) which doesn't match anything in the documentation, which are all readable 4CC's like '!ini' and so forth.
The good news is that it seems like the call worked. Nevertheless, can anyone shed light on this error code?
EDIT: The above error code is returned in the simulator. On the device the error code is 2fffe810.
Since these results are bogus and not defined or described by Apple, I am left with only but one assumption; you have a weird mix of Frameworks installed - possibly old versions mixed with newer ones. So all I could recommend is to reinstall the entire iPhone SDK.
I figured it out. I'm an idiot. There was an error in the macro I had wrapping the call & reporting the error, which called the AudioSessionInitialize twice. That doesn't quite explain the error code I saw, but it sure isn't worth wondering about.
UPDATE: Actually this is pretty slapstick so I'm going to explain.
The offending macro was originally:
#define CHECK(S) { OSStatus err = (S); if (S) printf("Error %x at \"%s\"\n", err, #S);}
so bug #1 is the if (S) which should be if if (err). Hence I'm repeating every call to the audio system, which explains various other weird things, so I'm very happy I tried to figure out what had seemed like a harmless anomaly. In this case the second call complained that the audio session was already initialized.
But why the weird error code? I wanted to see the 4CC's so I changed the macro to this, carrying the error along:
#define CHECK(S) { OSStatus err[2] = {S,0}; if (S) printf("Error %x '%4s' at \"%s\"\n", err, &err, #S); }
(The second OSStatus of 0 terminates the string defined by the 4CC first OSStatus, so I can print it with format %s.) But I forgot to change err to err[0], so it was indeed printing the address of the err array. This I'm pretty sure is correct now:
#define CHECK(S) { OSStatus err[2] = {S,0}; if (*err) printf("Error %x '%4s' at \"%s\"\n", *err, err, #S); }
Look at the OSStatus variable in the debugger's list of variables (lower left). Right click on it and select View Value As->Bytes (Hex with ASCII). Read the 4-letter code backwards.* This should match one of the documented result codes.
A value of 1768843636 is 74 69 6e 69 when viewed this way. Next to that the debug window shows 'tini'. Turn that around and you get 'init', which the documentation says is kAudioSessionAlreadyInitialized.
*No, I don't know why.

AVAudioPlayer initialization: error code -50

I recently ran into a problem that I couldn't find discussed anywhere on the internet - I was initializing an AVAudioPlayer to play an audio file, and getting the following error:
Error Domain=NSOSStatusErrorDomain Code=-50 "Operation could not be completed. (OSStatus error -50.)
As it turns out, I had made a mistake creating my NSURL to send to the audio player init method, resulting in the NSURL object being null. Stupid mistake, pretty easy to find when debugging, but I thought I'd list it here just in case someone else does the same thing.
“ OSStatus error -50” means paramErr, an old-style Mac error code indicating a bad parameter.
Regarding the comment from Brynjar:
The Apple NSURL Class Reference describing URLWithString states
To create NSURL objects for file system paths, use
fileURLWithPath:isDirectory: instead.
I have found that using URLWithString for file system paths generates the error reported by pix0r and therefore could be another explanation for error code = -50
Make sure your NSURL is valid, or you will get error code -50 "Operation could not be completed".
I'm adding my version of the issue and solution because I encountered the error with a print statement. I think it was related to string interpolation and or trying to forcibly print nsattributedstrings. I attempted to do the following.
print("THE ARRAY COUNT IS : \(unwrappedResults.count)\n\n\n
THE FULL ARRAY IS THE FIRST WHOLE RESULT IS: \(unwrappedResults)\n\n\n \ (unwrappedResults[0])\n
THE ATTRIBUTED FULL TEXT IS: \(unwrappedResults[0].attributedFullText)\n\n\n
THE ATTRIBUTED PRIMARY TEXT IS: \(unwrappedResults[0].attributedPrimaryText)\n\n\n
THE ATTRIBUTED SECONDARY TEXT IS: \(unwrappedResults[0].attributedSecondaryText)\n\n\n")
something about this was incorrect and no print would occur. I would receive the error following errors in my console.
boringssl_metrics_log_metric_block_invoke(131) Failed to log metrics
&
boringssl_metrics_log_metric_block_invoke(133) Error Domain=NSOSStatusErrorDomain Code=-50 "Unsupported xpc type"
UserInfo={NSDescription=Unsupported xpc type}
I fixed this issue by changing the way I unwrapped/the variables values. Fundamentally I think I was trying to print something using string interpolation that could not be printed and that is what caused this error.