-
Notifications
You must be signed in to change notification settings - Fork 9
/
NYMnemonic.m
199 lines (164 loc) · 7.4 KB
/
NYMnemonic.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
// NYMnemonic.m
//
// Copyright (c) 2014 Nybex, Inc. (https://nybex.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#import "NYMnemonic.h"
@implementation NYMnemonic
+ (NSString *)mnemonicStringFromRandomHexString:(NSString *)seed language:(NSString *)language {
// Convert our hex string to NSData
NSData *seedData = [seed ny_dataFromHexString];
// Calculate the sha256 hash to use with a checksum
NSMutableData *hash = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CC_SHA256(seedData.bytes, (int)seedData.length, hash.mutableBytes);
NSMutableArray *checksumBits = [NSMutableArray
arrayWithArray:[[NSData dataWithData:hash] ny_hexToBitArray]];
NSMutableArray *seedBits =
[NSMutableArray arrayWithArray:[seedData ny_hexToBitArray]];
// Append the appropriate checksum bits to the seed
for (int i = 0; i < (int)seedBits.count / 32; i++) {
[seedBits addObject: checksumBits[i]];
}
NSString *path = [NSString stringWithFormat:@"%@/%@.txt", [[NSBundle mainBundle] bundlePath], language];
NSString *fileText = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
NSArray *lines = [fileText componentsSeparatedByCharactersInSet: [NSCharacterSet newlineCharacterSet]];
// Split into groups of 11, and change to numbers
NSMutableArray *words = [NSMutableArray arrayWithCapacity:(int)seedBits.count / 11];
for (int i = 0; i < (int)seedBits.count / 11; i++) {
NSUInteger wordNumber =
strtol(
[[[seedBits subarrayWithRange: NSMakeRange(i * 11, 11)] componentsJoinedByString: @""] UTF8String],
NULL,
2);
[words addObject: lines[wordNumber]];
}
return [words componentsJoinedByString:@" "];
}
+ (NSString *)deterministicSeedStringFromMnemonicString:(NSString *)mnemonic
passphrase:(NSString *)passphrase
language:(NSString *)language {
NSData *data = [mnemonic dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *dataString = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
NSData *normalized = [dataString dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: NO];
NSData *saltData =
[[@"mnemonic" stringByAppendingString: [[NSString alloc] initWithData:[passphrase dataUsingEncoding: NSASCIIStringEncoding
allowLossyConversion:YES]
encoding:NSASCIIStringEncoding]]
dataUsingEncoding: NSASCIIStringEncoding
allowLossyConversion: NO];
NSMutableData *hashKeyData =
[NSMutableData dataWithLength:CC_SHA512_DIGEST_LENGTH];
CCKeyDerivationPBKDF(kCCPBKDF2, normalized.bytes, normalized.length,
saltData.bytes, saltData.length, kCCPRFHmacAlgSHA512,
2048, hashKeyData.mutableBytes, hashKeyData.length);
return [[NSData dataWithData:hashKeyData] ny_hexString];
}
+ (NSString *)generateMnemonicString:(NSNumber *)strength
language:(NSString *)language {
// Check that the strength is divisible by 32
if ([strength intValue] % 32 != 0) {
[NSException raise:@"Strength must be divisible by 32"
format:@"Strength Was: %@", strength];
}
// Create an array of bytes
NSMutableData *bytes = [NSMutableData dataWithLength: ([strength integerValue]/8)];
// Generate the random data
int status = SecRandomCopyBytes(kSecRandomDefault, bytes.length, bytes.mutableBytes);
// Make sure we were successful
if (status != -1) {
return [self mnemonicStringFromRandomHexString:[bytes ny_hexString] language:language];
} else {
[NSException raise:@"Unable to get random data!"
format:@"Unable to get random data!"];
}
return nil;
}
@end
@implementation NSData (NYMnemonic)
- (NSString *)ny_hexString {
const unsigned char *dataBuffer = (const unsigned char *)[self bytes];
if (!dataBuffer) {
return [NSString string];
}
NSUInteger dataLength = [self length];
NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
for (int i = 0; i < dataLength; ++i) {
[hexString appendString:[NSString stringWithFormat:@"%02lx", (unsigned long)dataBuffer[i]]];
}
return [NSString stringWithString:hexString];
}
- (NSArray *)ny_hexToBitArray {
NSMutableArray *bitArray = [NSMutableArray arrayWithCapacity:(int)self.length * 8];
NSString *hexStr = [self ny_hexString];
// Loop over the string and convert each char
for (NSUInteger i = 0; i < [hexStr length]; i++) {
NSString *bin = [self _hexToBinary:[hexStr characterAtIndex:i]];
// Each character will return a string representation of the binary
// Create NSNumbers from each and append to the array.
for (NSInteger j = 0; j < bin.length; j++) {
[bitArray addObject:
@([[NSString stringWithFormat: @"%C", [bin characterAtIndex: j]] intValue])];
}
}
return [NSArray arrayWithArray:bitArray];
}
- (NSString *)_hexToBinary:(unichar)value {
switch (value) {
case '0': return @"0000";
case '1': return @"0001";
case '2': return @"0010";
case '3': return @"0011";
case '4': return @"0100";
case '5': return @"0101";
case '6': return @"0110";
case '7': return @"0111";
case '8': return @"1000";
case '9': return @"1001";
case 'a':
case 'A': return @"1010";
case 'b':
case 'B': return @"1011";
case 'c':
case 'C': return @"1100";
case 'd':
case 'D': return @"1101";
case 'e':
case 'E': return @"1110";
case 'f':
case 'F': return @"1111";
}
return @"-1";
}
@end
@implementation NSString (NYMnemonic)
- (NSData *)ny_dataFromHexString {
const char *chars = [self UTF8String];
int i = 0, len = (int)self.length;
NSMutableData *data = [NSMutableData dataWithCapacity:len / 2];
char byteChars[3] = { '\0', '\0', '\0' };
unsigned long wholeByte;
while (i < len) {
byteChars[0] = chars[i++];
byteChars[1] = chars[i++];
wholeByte = strtoul(byteChars, NULL, 16);
[data appendBytes:&wholeByte length:1];
}
return data;
}
@end