|
16 | 16 |
|
17 | 17 | #import "FirebaseAuthUI/Sources/Public/FirebaseAuthUI/FUIAuthUtils.h" |
18 | 18 |
|
| 19 | +#import <CommonCrypto/CommonCrypto.h> |
| 20 | + |
19 | 21 | #if SWIFT_PACKAGE |
20 | 22 | NSString *const FUIAuthBundleName = @"FirebaseUI_FirebaseAuthUI"; |
21 | 23 | #else |
@@ -74,4 +76,51 @@ + (nullable UIImage *)imageNamed:(NSString *)name fromBundle:(nullable NSBundle |
74 | 76 | } |
75 | 77 | } |
76 | 78 |
|
| 79 | ++ (NSString *)randomNonce { |
| 80 | + // Adapted from https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce |
| 81 | + NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._"; |
| 82 | + NSMutableString *result = [NSMutableString string]; |
| 83 | + NSInteger remainingLength = 32; |
| 84 | + |
| 85 | + while (remainingLength > 0) { |
| 86 | + NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16]; |
| 87 | + for (NSInteger i = 0; i < 16; i++) { |
| 88 | + uint8_t random = 0; |
| 89 | + int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random); |
| 90 | + if (errorCode != errSecSuccess) { |
| 91 | + [NSException raise:@"FUIAuthGenerateRandomNonce" |
| 92 | + format:@"Unable to generate nonce: OSStatus %i", errorCode]; |
| 93 | + } |
| 94 | + |
| 95 | + [randoms addObject:@(random)]; |
| 96 | + } |
| 97 | + |
| 98 | + for (NSNumber *random in randoms) { |
| 99 | + if (remainingLength == 0) { |
| 100 | + break; |
| 101 | + } |
| 102 | + |
| 103 | + if (random.unsignedIntValue < characterSet.length) { |
| 104 | + unichar character = [characterSet characterAtIndex:random.unsignedIntValue]; |
| 105 | + [result appendFormat:@"%C", character]; |
| 106 | + remainingLength--; |
| 107 | + } |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + return result; |
| 112 | +} |
| 113 | + |
| 114 | ++ (NSString *)stringBySHA256HashingString:(NSString *)input { |
| 115 | + const char *string = [input UTF8String]; |
| 116 | + unsigned char result[CC_SHA256_DIGEST_LENGTH]; |
| 117 | + CC_SHA256(string, (CC_LONG)strlen(string), result); |
| 118 | + |
| 119 | + NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2]; |
| 120 | + for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) { |
| 121 | + [hashed appendFormat:@"%02x", result[i]]; |
| 122 | + } |
| 123 | + return hashed; |
| 124 | +} |
| 125 | + |
77 | 126 | @end |
0 commit comments