Skip to content

Instantly share code, notes, and snippets.

@SaidBySolo
Created August 31, 2022 06:44
Show Gist options
  • Save SaidBySolo/3e7eb40c69dd65e220b687bc06539948 to your computer and use it in GitHub Desktop.
Save SaidBySolo/3e7eb40c69dd65e220b687bc06539948 to your computer and use it in GitHub Desktop.
import binascii
import math
from random import Random
from qiskit import (
IBMQ,
ClassicalRegister,
QuantumCircuit,
QuantumRegister,
BasicAer,
execute,
)
class QRNG:
def __init__(self, token: str) -> None:
IBMQ.enable_account(token)
self.provider = IBMQ.get_provider()
self.backend = BasicAer.get_backend("qasm_simulator")
self.circuit = self.make_circuit()
def make_circuit(self):
qreg_q = QuantumRegister(5, "q")
creg_c = ClassicalRegister(2, "c")
circuit = QuantumCircuit(qreg_q, creg_c)
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
circuit.h(qreg_q[3])
circuit.h(qreg_q[4])
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
circuit.h(qreg_q[3])
circuit.h(qreg_q[4])
circuit.h(qreg_q[0])
circuit.h(qreg_q[1])
circuit.h(qreg_q[2])
circuit.h(qreg_q[3])
circuit.h(qreg_q[4])
circuit.barrier(qreg_q[0])
circuit.barrier(qreg_q[1])
circuit.barrier(qreg_q[2])
circuit.barrier(qreg_q[3])
circuit.barrier(qreg_q[4])
circuit.measure(qreg_q[0], creg_c[1])
circuit.measure(qreg_q[1], creg_c[0])
circuit.measure(qreg_q[2], creg_c[1])
circuit.measure(qreg_q[3], creg_c[1])
circuit.measure(qreg_q[4], creg_c[1])
return circuit
# https://github.com/ozaner/qRNG/blob/master/qrng/__init__.py
def _bit_from_counts(self, counts: dict[str, int]):
return [k for k, v in counts.items() if v == 1][0]
def _request_bits(self, n: int):
iterations = math.ceil(n / self.circuit.width() * 2)
for _ in range(iterations):
# Create new job and run the quantum circuit
job = execute(self.circuit, self.backend, shots=1)
self._bit_cache += self._bit_from_counts(job.result().get_counts())
def get_bit_string(self, n: int):
if len(self._bit_cache) < n:
self._request_bits(n - len(self._bit_cache))
bit_string = self._bit_cache[0:n]
self._bit_cache = self._bit_cache[n:]
return bit_string
def get_random_int32(self):
self._bit_cache = ""
return int(self.get_bit_string(32), 2)
def token_hex(self, n: int):
random = Random(self.get_random_int32())
return binascii.hexlify(random.randbytes(n)).decode("ascii")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment