· 9 years ago · Sep 25, 2016, 09:40 PM
1/*
2chat.cpp
3
4What you type on one Arduino shows up in the screen
5attached to the other one and vice versa.
6*/
7#include <Arduino.h>
8
9/* Calculates and returns (a**b) mod m.
10Parameters:
11 a: base, nonnegative integer
12 b: exponent, nonnegative integer, a=b=0 not allowed
13 m: positive integer
14*/
15uint32_t pow_mod( uint32_t a, uint32_t b, uint32_t m ) {
16 uint32_t result = 1;
17 for (uint32_t i=1; i<=b; ++i) {
18 Serial.print("Counter: ");
19 Serial.println(i);
20 Serial.print("Result: ");
21 Serial.println(result);
22 result = result * a;
23 }
24 result = result % m;
25 return result;
26}
27
28void test_pow_mod_case( uint32_t a, uint32_t b, uint32_t m, uint32_t expresult ) {
29 uint32_t result = pow_mod( a, b, m );
30 Serial.print("Expected result: ");
31 Serial.println(expresult);
32 Serial.print("Computed result: ");
33 Serial.println(result);
34}
35
36/* Tests pow_mod */
37void test_pow_mod() {
38 // test_pow_mod_case( 5, 10, 37, 30 );
39 // test_pow_mod_case( 8, 10, 37, 11 );
40 // Edge cases! Small values and big values
41 //
42 // test_pow_mod_case( 0, 10, 37, 0 );
43 // test_pow_mod_case( 8, 0, 37, 1 );
44
45 test_pow_mod_case( 5, 20, 37, 12 );
46 // test_pow_mod_case( 5, 200, 37, 12 );
47}
48
49/* Receives a number from the PC and returns it as a uint32_t number */
50uint32_t get_input() {
51 // TODO: Fix me!
52 return 0;
53}
54
55int main() {
56 init();
57 Serial.begin(9600);
58 Serial3.begin(9600);
59 test_pow_mod();
60 while (true) {
61 }
62 uint32_t prime = 37;
63 uint32_t generator = 5;
64 uint32_t private_key = 10; // TODO: Fix this!!! generate this randomly
65 uint32_t public_key = pow_mod( generator, private_key, prime );
66 // key exchange:
67 Serial.print("Hey, here is the key you were looking for to share with your partner: ");
68 Serial.println(public_key);
69 Serial.print("Can you please enter the key received from your partner? ");
70 uint32_t partners_public_key = get_input();
71 uint32_t shared_secret = pow_mod( partners_public_key, private_key, prime );
72 char secret_key = shared_secret; // lowest 8 bits of the shared_secret
73
74 while (true) {
75 // PC keystroke -> other Arduino
76 if (Serial.available()>0) {
77 char c = Serial.read();
78 // Serial.write(c); // echo back to screen
79 Serial.print("ASCII code of character to be sent: ");
80 Serial.println((int)c);
81 // encrypt data:
82 c = c ^ secret_key;
83 Serial.print("Encrypted information being sent: ");
84 Serial.println((int)c);
85 Serial3.write(c); // sending byte to the "other" Arduino
86 }
87 // Other Arduino to PC screen
88 if (Serial3.available()>0) {
89 char c = Serial3.read();
90 // decrypt data:
91 c = c ^ secret_key;
92 Serial.write(c); // show byte on screen as character
93 }
94 }
95
96 Serial3.end();
97 Serial.end();
98 return 0;
99}