#import "TPViewController.h"
@interface TPViewController ()
NSMutableString * EncryptString(NSString *plainText, NSString *encryptKey);
NSMutableString * DecryptString(NSString *encryptedText, NSString *decryptKey);
@end
@implementation TPViewController
@synthesize btnEncrypt;
@synthesize btnDecrypt;
@synthesize textInput;
@synthesize textKey;
@synthesize textOutput;
NSMutableString * EncryptString(NSString *plainText, NSString *encryptKey)
{
int cycleIndex = 0;
NSMutableString *result = [[NSMutableString alloc] initWithCapacity:plainText.length];
for (int i = 0; i < plainText.length; ++i) {
int rotate = [encryptKey characterAtIndex:cycleIndex];
[result appendFormat:@"%c", [plainText characterAtIndex:i] + rotate];
cycleIndex = (cycleIndex + 1) % encryptKey.length;
}
return result;
}
NSMutableString * DecryptString(NSString *encryptedText, NSString *decryptKey)
{
int cycleIndex = 0;
NSMutableString *result = [[NSMutableString alloc] initWithCapacity:encryptedText.length];
for (int i = 0; i < encryptedText.length; ++i) {
int rotate = [decryptKey characterAtIndex:cycleIndex];
[result appendFormat:@"%c", [encryptedText characterAtIndex:i] - rotate];
cycleIndex = (cycleIndex + 1) % decryptKey.length;
}
return result;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)showEncryptedOutput:(id)sender
{
[textKey resignFirstResponder];
NSMutableString *encryptedMutable = EncryptString(textInput.text, textKey.text);
textOutput.text = [NSString stringWithString:encryptedMutable];
}
- (IBAction)showDecryptedOutput:(id)sender
{
[textKey resignFirstResponder];
NSMutableString *decryptedMutable = DecryptString(textInput.text, textKey.text);
textOutput.text = [NSString stringWithString:decryptedMutable];
}
@end