Objective-C
Objective-C
RSA Sign with PKCS8 Encrypted Key
See more RSA Examples
Demonstrates how to load a private key from an encrypted PKCS8 file and create an RSA digital signature (and then verify it).Chilkat Objective-C Downloads
#import <CkoPrivateKey.h>
#import <CkoRsa.h>
#import <NSString.h>
#import <CkoCert.h>
#import <CkoPublicKey.h>
BOOL success = NO;
// This example assumes the Chilkat API to have been previously unlocked.
// See Global Unlock Sample for sample code.
CkoPrivateKey *privKey = [[CkoPrivateKey alloc] init];
// Load the private key from an RSA PEM file:
success = [privKey LoadAnyFormatFile: @"raul_privateKey.key" password: @"a0123456789"];
if (success == NO) {
NSLog(@"%@",privKey.LastErrorText);
return;
}
CkoRsa *rsa = [[CkoRsa alloc] init];
// Import the private key into the RSA component:
success = [rsa UsePrivateKey: privKey];
if (success == NO) {
NSLog(@"%@",rsa.LastErrorText);
return;
}
// This example will sign a string, and receive the signature
// in a hex-encoded string. Therefore, set the encoding mode
// to "hex":
rsa.EncodingMode = @"hex";
NSString *strData = @"This is the string to be signed.";
// Sign the string using the sha256 hash algorithm.
// Other valid choices are sha1, sha384, sha512 and others.
NSString *hexSig = [rsa SignStringENC: strData hashAlg: @"sha256"];
if (rsa.LastMethodSuccess == NO) {
NSLog(@"%@",rsa.LastErrorText);
return;
}
NSLog(@"%@",hexSig);
// Now verify with the public key.
// This example shows how to use the public key from
// a digital certificate (.cer file)
CkoCert *cert = [[CkoCert alloc] init];
success = [cert LoadFromFile: @"raul_publicKey.cer"];
if (success == NO) {
NSLog(@"%@",cert.LastErrorText);
return;
}
CkoPublicKey *pubKey = [[CkoPublicKey alloc] init];
[cert GetPublicKey: pubKey];
CkoRsa *rsa2 = [[CkoRsa alloc] init];
success = [rsa2 UsePublicKey: pubKey];
if (success == NO) {
NSLog(@"%@",rsa2.LastErrorText);
return;
}
// Verify the signature against the original data:
rsa2.EncodingMode = @"hex";
success = [rsa2 VerifyStringENC: strData hashAlg: @"sha256" sig: hexSig];
if (success == NO) {
NSLog(@"%@",rsa2.LastErrorText);
return;
}
NSLog(@"%@",@"Signature verified!");
// Verify with incorrect data:
success = [rsa2 VerifyStringENC: @"something else" hashAlg: @"sha256" sig: hexSig];
if (success != YES) {
NSLog(@"%@",@"Signature not verified! (which was expected in this case)");
}
else {
NSLog(@"%@",@"Hmmm... that's not right...");
}