objective c encrypt decrypt string
To encrypt and decrypt strings in Objective-C, you can use various cryptographic algorithms and libraries available in the language. One commonly used library is CommonCrypto, which provides functions for encryption and decryption operations.
To encrypt a string using CommonCrypto in Objective-C, you can use the following code:
#import <CommonCrypto/CommonCryptor.h>
- (NSData )encryptString:(NSString )string withKey:(NSString *)key {
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *encryptedData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
size_t encryptedLength;
CCCryptorStatus cryptStatus = CCCrypt(kCCEncrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyData.bytes,
keyData.length,
NULL,
data.bytes,
data.length,
encryptedData.mutableBytes,
encryptedData.length,
&encryptedLength);
if (cryptStatus == kCCSuccess) {
encryptedData.length = encryptedLength;
return encryptedData;
}
return nil;
}
To decrypt the encrypted data, you can use the following code:
- (NSString )decryptData:(NSData )data withKey:(NSString *)key {
NSData *keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
NSMutableData *decryptedData = [NSMutableData dataWithLength:data.length + kCCBlockSizeAES128];
size_t decryptedLength;
CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt,
kCCAlgorithmAES,
kCCOptionPKCS7Padding,
keyData.bytes,
keyData.length,
NULL,
data.bytes,
data.length,
decryptedData.mutableBytes,
decryptedData.length,
&decryptedLength);
if (cryptStatus == kCCSuccess) {
decryptedData.length = decryptedLength;
NSString *decryptedString = [[NSString alloc] initWithData:decryptedData encoding:NSUTF8StringEncoding];
return decryptedString;
}
return nil;
}
Please note that this code uses the AES encryption algorithm with a 128-bit key size and PKCS7 padding. You need to provide a key for encryption and decryption. Make sure to handle the key securely.
Remember to include the necessary header files and frameworks for CommonCrypto in your project.
I hope this helps! Let me know if you have any further questions.