Guest User

Untitled

a guest
Jul 1st, 2018
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.58 KB | None | 0 0
  1. when defined(windows):
  2.   import winlean
  3.  
  4.   {.push, stdcall, dynlib: "Advapi32.dll".}
  5.   proc CryptAcquireContext(
  6.       prov: ptr int,
  7.       ignored1: WideCString,
  8.       ignored2: WideCString,
  9.       provType: uint32,
  10.       provFlags: uint32
  11.   ): WinBool {.importc: "CryptAcquireContextW".}
  12.  
  13.   proc CryptGenRandom(
  14.       hProv: int,
  15.       dwLen: uint32,
  16.       pbBuffer: pointer
  17.   ): WinBool {.importc: "CryptGenRandom".}
  18.   {.pop.}
  19.  
  20.   var prov: int
  21.   if CryptAcquireContext(addr prov, nil, nil, 1'u32, 4026531840'u32) == 0:
  22.       raise newException(Exception, "Couldn't acquire a cryptographic context")
  23.  
  24.   proc randbytes(quantity: int): seq[char] =
  25.       result = newSeq[char](quantity)
  26.       for i in 0 ..< quantity:
  27.           if CryptGenRandom(prov, 8'u32, addr result[i]) == 0:
  28.               raise newException(Exception, "Couldn't get a random byte")
  29. # else:
  30. #   proc randbytes(quantity: int): seq[char] =
  31. #       result = newSeq[char](quantity)
  32.      
  33. #       var urandom: File = open("/dev/urandom")
  34. #       discard urandom.readChars(result, 0, quantity)
  35. #       urandom.close()
  36.  
  37. type PrivateKey* = ref object of RootObj
  38.     secret*: array[32, uint8]
  39.  
  40. proc random*(quantity: int): seq[uint8] =
  41.     result = newSeq[uint8](quantity)
  42.     var bytes: seq[char] = randbytes(quantity)
  43.     for i in 0 ..< quantity:
  44.         result[i] = (uint8) bytes[i]
  45.  
  46. proc newPrivateKey*(): PrivateKey =
  47.     result = PrivateKey()
  48.  
  49.     result.secret[0 ..< 32] = random(32)[0 ..< 32]
  50.  
  51. for i in 0 .. 500:
  52.   var privKey: PrivateKey = newPrivateKey()
  53.   echo "privkeyDebug: ", privkey.secret
Add Comment
Please, Sign In to add comment