microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
alex/pythontelem

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

katas/content/key_distribution/examples/BB84Demo.qs

71lines · modecode

1namespace Kata {
2 open Microsoft.Quantum.Arrays;
3 open Microsoft.Quantum.Convert;
4 open Microsoft.Quantum.Diagnostics;
5 open Microsoft.Quantum.Random;
6
7 @EntryPoint()
8 operation RunBB84Protocol() : Unit {
9 // 1. Alice chooses a random set of bits to encode in her qubits
10 // and a random set of bases to prepare her qubits in.
11 // ...
12
13 // 2. Alice allocates qubits, encodes them using her choices and sends them to Bob.
14 // You can not express "sending the qubits to Bob" in Q#,
15 // so Bob will just use the same qubits.
16 // ...
17
18 // 3. Bob chooses a random set of bases to measure Alice's qubits in.
19 // ...
20
21 // 4. Bob measures Alice's qubits in his chosen bases.
22 // ...
23
24 // 5. Alice and Bob compare their chosen bases and
25 // use the bits in the matching positions to create a shared key.
26 // ...
27
28 // If you did everything correctly, the generated keys will always match,
29 // since there is no eavesdropping going on.
30 // In the next lesson we will discuss introducing eavesdropping.
31 }
32
33 // You might find these helper operations from earlier tasks useful.
34 operation RandomArray(N : Int) : Bool[] {
35 mutable array = [false, size = N];
36 for i in 0 .. N - 1 {
37 set array w/= i <- DrawRandomInt(0, 1) == 0;
38 }
39 return array;
40 }
41
42 operation PrepareQubits(qs : Qubit[], bases : Bool[], bits : Bool[]) : Unit {
43 for i in 0 .. Length(qs) - 1 {
44 if bits[i] {
45 X(qs[i]);
46 }
47 if bases[i] {
48 H(qs[i]);
49 }
50 }
51 }
52
53 operation MeasureQubits(qs : Qubit[], bases : Bool[]) : Bool[] {
54 for i in 0 .. Length(qs) - 1 {
55 if bases[i] {
56 H(qs[i]);
57 }
58 }
59 return ResultArrayAsBoolArray(MeasureEachZ(qs));
60 }
61
62 function GenerateSharedKey(basesAlice : Bool[], basesBob : Bool[], bits : Bool[]) : Bool[] {
63 mutable key = [];
64 for i in 0 .. Length(bits) - 1 {
65 if basesAlice[i] == basesBob[i] {
66 set key += [bits[i]];
67 }
68 }
69 return key;
70 }
71}
72