本站電子書

您可以在這些電子書店找到本站電子書: Google Play 圖書iBooks StoreHyReadReadmooPubu
===>>>本站推出學習遊戲意見調查<<<===《如何自學程式設計》入選 Google Play 台灣地區2016年度最佳書籍

Objective-C 入門指南 - Encrypt.m




Encrypt.m 的原始程式碼如下

#import <Foundation/Foundation.h>
#import "Encrypt.h"

@implementation Encrypt

@synthesize cArray, oArray;


- (id) initRandomEncrypt
{
    // 設置 y = a * x + b 中的 a 與 b
    int a = 0;
    int b = 0;
    do {
        a = arc4random() % 10;
        b = arc4random() % 10;
    } while (a % 2 == 0);
 
    // 建立 oArray 及 cArray
    oArray = [NSArray arrayWithObjects: 
               @"a", @"b", @"c", @"d", @"e", @"f", @"g", 
               @"h", @"i", @"j", @"k", @"l", @"m", @"n", 
               @"o", @"p", @"q", @"r", @"s", @"t", @"w", 
               @"v", @"u", @"x", @"y", @"z", nil];
    cArray = [NSMutableArray arrayWithCapacity: 26];

    // 製作密碼表 cArray
    int n = 26;
    char c = 'a';
    int i, d, ci, count, m;
    for (i = 0, count = c;i < n;i++) {
        ci = count;
        d = ci * a + b;
        m = d % n;
        [cArray addObject: [oArray objectAtIndex: m]];
        count++;
    }
 
    // 回傳 self
    return self;
}

- (NSString *) toEncode: (NSString *) s
{
    NSString *r = @"";
    int number = [s length];
    char ct; 
    int i;
    
    for (i = 0;i < number;i++) {
        ct = [s characterAtIndex: i];
        
        if (ct >= 97 && ct <= 122) {
      r = [r stringByAppendingString: [cArray objectAtIndex: ct - 97]];
        }
        else {
            r = [r stringByAppendingFormat: @"%c", ct];
        }
    }
    
    return r;
}

- (NSString *) toDecode: (NSString *) s
{
    NSString *r = @"";
    int number = [s length];
    char ct;
    int i, j;
    
    for (i = 0;i < number;i++) {
        ct = [s characterAtIndex: i];
        
        if (ct >= 97 && ct <= 122) {
            for (j = 0;j < 26;j++) {
                if (ct == [[cArray objectAtIndex: j] characterAtIndex: 0]) {
                    r = [r stringByAppendingString: [oArray objectAtIndex: j]];
                    break;
                }
            }
        }
        else {
            r = [r stringByAppendingFormat: @"%c", ct];
        }
    }
    
    return r;
}

@end


您可以繼續參考
範例程式碼


相關目錄
Objective-C 入門指南
Objective-C 教材
首頁



參考資料
Learning Objective-C: A Primer
The Objective-C Programming Language
Cocoa Fundamentals Guide
Coding Guidelines for Cocoa
Advanced Memory Management Programming Guide
Archives and Serializations Programming Guide

沒有留言: