Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: f1e073ebd2
Fetching contributors…

Cannot retrieve contributors at this time

105 lines (81 sloc) 2.979 kb
//
// PKWebSocketCrypto.m
// PKWebSocket
//
// Created by Pavel Kunc on 17/04/2012.
// Copyright (c) 2012 Pavel Kunc. All rights reserved.
//
#import "PKWebSocketCrypto.h"
@implementation NSData (PKWebSocketCrypto)
- (NSData *)pk_MD5 {
NSMutableData *digest = [NSMutableData dataWithLength:CC_MD5_DIGEST_LENGTH];
CC_MD5([self bytes], (unsigned)[self length], [digest mutableBytes]);
return (NSData *)digest;
}
- (NSData *)pk_SHA1 {
NSMutableData *digest = [NSMutableData dataWithLength:CC_SHA1_DIGEST_LENGTH];
CC_SHA1([self bytes], (unsigned)[self length], [digest mutableBytes]);
return (NSData *)digest;
}
+ (NSData *)pk_randomBytesOfLength:(NSUInteger)aLength {
NSMutableData *random = [NSMutableData dataWithLength:aLength];
arc4random_buf([random mutableBytes], aLength);
return (NSData *)random;
}
+ (NSData *)pk_hixie76ChallengeWithFirstKey:(SecKey)aKey1
secondKey:(SecKey)aKey2
randomData:(NSData *)aData {
unsigned char bytes[8];
pkws_hixie76ChallengeNumber(aKey1.num, &bytes[0]);
pkws_hixie76ChallengeNumber(aKey2.num, &bytes[4]);
NSMutableData *challenge = [NSMutableData dataWithBytes:bytes length:sizeof(bytes)];
[challenge appendData:aData];
return (NSData *)challenge;
}
@end
void pkws_hixie76ChallengeNumber(uint32_t number, unsigned char * buf) {
unsigned char *p = buf + 3;
for (int i = 0; i < 4; i++) {
*p = number & 0xFF;
--p;
number >>= 8;
}
}
SecKey pkws_hixie76Key() {
struct SecKey seckey;
uint32_t spaces, max, num, prod;
unichar letter;
NSInteger keylen;
NSString *space = @" ";
// As per 5.2.6, abort if numbers is not an integral multiple of spaces
NSMutableString *key;
do {
spaces = (arc4random() % 12) + 1;
// As per 5.2.5, abort the connection if spaces are zero.
assert(spaces > 0 && spaces <= 12);
max = (arc4random() % 4294967295U) / spaces;
assert(max >= 0 && max <= 4294967295U);
num = arc4random() % max;
assert(num >= 0 && num <= max);
prod = spaces * num;
key = [NSMutableString stringWithFormat:@"%ld", prod];
keylen = [key length];
} while (keylen % spaces != 0);
for (NSUInteger i = 0; i < 12; i++) {
if ((arc4random() % 2) == 0)
letter = (arc4random() % (47 - 33 + 1)) + 33;
else
letter = (arc4random() % (126 - 58 + 1)) + 58;
NSUInteger index = (arc4random() % (keylen-1));
NSString *letterString = [[NSString alloc] initWithCharacters:&letter length:1];
[key insertString:letterString atIndex:index];
}
keylen = [key length];
for (NSUInteger i = 0; i < spaces; i++) {
NSUInteger index = ((arc4random() % (keylen-2))+1);
[key insertString:space atIndex:index];
}
seckey.num = num;
seckey.key = key;
return seckey;
}
Jump to Line
Something went wrong with that request. Please try again.