]> git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_cryptkit/lib/NSRandomNumberGenerator.m
Security-57336.1.9.tar.gz
[apple/security.git] / OSX / libsecurity_cryptkit / lib / NSRandomNumberGenerator.m
1 /* Copyright (c) 1998,2011,2014 Apple Inc. All Rights Reserved.
2 *
3 * NOTICE: USE OF THE MATERIALS ACCOMPANYING THIS NOTICE IS SUBJECT
4 * TO THE TERMS OF THE SIGNED "FAST ELLIPTIC ENCRYPTION (FEE) REFERENCE
5 * SOURCE CODE EVALUATION AGREEMENT" BETWEEN APPLE, INC. AND THE
6 * ORIGINAL LICENSEE THAT OBTAINED THESE MATERIALS FROM APPLE,
7 * INC. ANY USE OF THESE MATERIALS NOT PERMITTED BY SUCH AGREEMENT WILL
8 * EXPOSE YOU TO LIABILITY.
9 ***************************************************************************
10 *
11 * NSRandomNumberGenerator.m
12 *
13 * Revision History
14 * ----------------
15 * 28 Mar 97 at Apple
16 * Rewrote using feeRandom module.
17 * ?? 96 Blaine Garst at NeXT
18 * Created.
19 */
20
21 /*
22 * Note: out _priv ivar is actually a feeRand pointer.
23 */
24
25 #import <Foundation/Foundation.h>
26 #import "NSRandomNumberGenerator.h"
27 #import "feeRandom.h"
28 #import "falloc.h"
29
30 @implementation NSRandomNumberGenerator
31
32 - init
33 {
34 if(_priv == NULL) {
35 _priv = feeRandAlloc();
36 }
37 /*
38 * else no need to re-init
39 */
40 return self;
41 }
42
43 - initWithSeed:(unsigned)seed
44 {
45 if(_priv != NULL) {
46 /*
47 * Free & re-init to use new seed
48 */
49 feeRandFree(_priv);
50 }
51 _priv = feeRandAllocWithSeed(seed);
52 return self;
53 }
54
55 - (unsigned)nextNumber
56 {
57 if(_priv == NULL) {
58 return 0;
59 }
60 return feeRandNextNum(_priv);
61 }
62
63 - (unsigned)nextNumberInRange:(NSRange)range
64 {
65 if(_priv == NULL) {
66 return 0;
67 }
68 return range.location + ([self nextNumber] % range.length);
69 }
70
71 - (NSData *)randomDataWithLength:(unsigned)l
72 {
73 unsigned char *cp;
74
75 if(_priv == NULL) {
76 return nil;
77 }
78 cp = fmalloc(l);
79 feeRandBytes(_priv, cp, l);
80 return [NSData dataWithBytesNoCopy:cp length:l];
81 }
82
83 @end