Objective-C Encode JWT RS256 with privatekey

Viewed 126

I am using openssl to generate rsa keypair with below command
openssl req -newkey rsa:2048 -nodes -keyout private.key -x509 -days 365 -out public.crt
then i'm using this library to encode an JWT RS256 https://github.com/yourkarma/JWT
with private.key that i generated before.

But it failed with this error.
Error Domain=NSOSStatusErrorDomain Code=-50 "RSA private key creation from data failed" UserInfo={numberOfErrorsDeep=0, NSDescription=RSA private key creation from data failed}

Here is the sample code that I am using.

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"private" ofType:@"key"];
    NSString *key = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    key = [[key componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]] componentsJoinedByString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"-----BEGIN PRIVATE KEY-----" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"-----END PRIVATE KEY-----" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"-----BEGIN RSA PRIVATE KEY-----" withString:@""];
    key = [key stringByReplacingOccurrencesOfString:@"-----END RSA PRIVATE KEY-----" withString:@""];

    NSDictionary *payload = @{@"payload" : @"hidden_information"};

    id <JWTAlgorithmDataHolderProtocol> signDataHolder = [JWTAlgorithmRSFamilyDataHolder new]
            .keyExtractorType([JWTCryptoKeyExtractor privateKeyWithPEMBase64].type)
            .algorithmName(JWTAlgorithmNameRS256).secret(key);

    JWTCodingResultType *result = [JWTEncodingBuilder encodePayload:payload]
        .addHolder(signDataHolder)
        .result;

    NSString *token = result.successResult.encoded;
    NSError *error = result.errorResult.error;

Could anyone here help me with this, please? Thank you in advance.

0 Answers
Related