nist.html
001| '''NIST (National Institute for Standards and Technology.'''
002|
003| from os import path
004| from datetime import datetime
005| from json import loads, dump
006| from htget import htget
007| from goodies import str2bytes
008|
009|
010|
011| class RandomNIST (htget):
012| '''Connects to the NIST https Random Beacon and grabs lastest data.'''
013| Url = r'https://beacon.nist.gov/beacon/2.0/pulse/last'
014|
015| @classmethod
016| def Doit (cls):
017| rqst = RandomNIST()
018| for nam,val in rqst.headers:
019| print('%s: %s' % (nam,val))
020| print()
021| return rqst
022|
023| def __init__ (self):
024| super().__init__(RandomNIST.Url)
025| self.json = loads(self.data)
026| self.main = self.json['pulse']
027| self.uri = self.main['uri']
028| self.ver = self.main['version']
029| self.stat = self.main['statusCode']
030| self.pulse = self.main['pulseIndex']
031| self.chain = self.main['chainIndex']
032| self.suite = self.main['cipherSuite']
033| self.rand = str2bytes(self.main['localRandomValue'])
034| self.outp = str2bytes(self.main['outputValue'])
035| self.date = datetime.fromisoformat(self.main['timeStamp'].replace('Z','+00:00:00'))
036| self.vals = {}
037| for dd in self.main['listValues']:
038| name = dd['type']
039| valu = dd['value']
040| self.vals[name] = str2bytes(valu)
041|
042| def __call__ (self, name=None):
043| '''The name can be [previous,hour,day,month,year].'''
044| if (name is None) or (len(name)==0):
045| return self.rand
046| if name not in self.vals:
047| return None
048| return self.vals[name]
049|
050| def save (fname='randnist.json', fpath=None):
051| ''' Save the NIST JSON to file file.'''
052| fn = path.join(fpath, fname) if fpath else fname
053| fp = open(fn, mode='w', encoding='utf8')
054| try:
055| dump(self.json, fp, indent=True, ensure_ascii=True)
056| print('wrote: %s' % fn)
057| except Exception as e:
058| raise e
059| finally:
060| fp.close()
061|
062| def __bytes__ (self): return bytes(self.rand)
063| def __len__ (self): return len(self.rand)
064| def __iter__ (self): return iter(self.rand)
065| def __getitem__ (self, ix): return self.rand[ix]
066| def __setitem__ (self, ix, val): raise RuntimeError('Values are read-only!')
067| def __delitem__ (self, ix): raise RuntimeError('Values may not be deleted!')
068|
069| def __str__ (self):
070| return ','.join(['%02x' % x for x in self.rand])
071|
072| def __repr__ (self):
073| t = (self.chain, self.pulse, self.date, self.rand)
074| s = '{RandomNIST:{"chain":"%d", "pulse":"%d", "date":"%s", "rand":%s}}'
075| return s%t
076|
077|
078|
079| '''eof'''
080|