Skip to content

Instantly share code, notes, and snippets.

@nicerobot
Created December 29, 2011 21:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicerobot/1536232 to your computer and use it in GitHub Desktop.
Save nicerobot/1536232 to your computer and use it in GitHub Desktop.
Mac OS X / iOS UInt32 randomness
#!/bin/bash
# Just:
# curl -kOs https://raw.github.com/gist/1536232/randomness.sh; chmod +x randomness.sh; ./randomness.sh
# I know, it seems pointless but it's just a simple example of how to:
# 1. Compile against a Framework on Mac OS.
# 2. Mix sources.
# 3. Determine if a script is sourced or executed directly.
sourced() { [ 'bash' == $0 ] || [ ${BASH_SOURCE[0]} != $0 ]; }
(
u="$(date -u +%Y%m%dt%H%M%S).$$.${RANDOM}" n="/tmp/${u}" c="${n}.c"
trap "rm -f '${n}' '${c}'" 0
l=$(grep -n '[#]import' ${BASH_SOURCE[0]} | head -1 | awk 'BEGIN{FS=":"} {print $1}')
sed -n ${l}',$p' ${BASH_SOURCE[0]} >${c}
cc -F/System/Library/Frameworks/Security.framework -framework Security -o "${n}" "${c}" || exit $?
[ -x "${n}" ] && "${n}" || exit $?
exit 0
); r=$? sourced && return ${r} || exit ${r}
#import <Security/SecRandom.h>
#import <stdio.h>
int main() {
UInt32 randomResult = 0;
int result = SecRandomCopyBytes(kSecRandomDefault, sizeof(int), (uint8_t*)&randomResult);
if (result != 0) randomResult = arc4random();
printf("%u\n",randomResult);
return randomResult;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment