COSA
An Object-Oriented Platform for Arduino Programming
Vigenere.hh
Go to the documentation of this file.
1 
21 #ifndef COSA_VIGENERE_HH
22 #define COSA_VIGENERE_HH
23 
24 #include "Cosa/Types.h"
25 
33 template<uint8_t N>
34 class Vigenere {
35 public:
43  Vigenere(uint32_t seed, uint8_t n = N)
44  {
45  if (UNLIKELY(n > N)) n = N;
46  srandom(seed);
47  for (uint8_t i = 0; i < n; i++)
48  m_key[i] = random();
49  m_nr = 0;
50  m_max = n;
51  m_pos = n;
52  }
53 
59  Vigenere(const char* password)
60  {
61  uint8_t i;
62  for (i = 0; i < N && password[i]; i++)
63  m_key[i] = password[i];
64  m_nr = 0;
65  m_max = i;
66  m_pos = i;
67  }
68 
72  void restart()
73  {
74  m_max = m_pos;
75  m_nr = 0;
76  }
77 
83  char encrypt(char c)
84  {
85  char res = c + m_key[m_nr++];
86  if (m_max != N) m_key[m_max++] = c;
87  if (m_nr == N) m_nr = 0;
88  return (res);
89  }
90 
96  void encrypt(void* buf, size_t n)
97  {
98  for (char* bp = (char*) buf; n--; bp++)
99  *bp = encrypt(*bp);
100  }
101 
108  void encrypt(void* dest, const void* src, size_t n)
109  {
110  char* dp = (char*) dest;
111  const char* sp = (const char*) src;
112  while (n--) *dp++ = encrypt(*sp++);
113  }
114 
120  char decrypt(char c)
121  {
122  char res = c - m_key[m_nr++];
123  if (m_max != N) m_key[m_max++] = res;
124  if (m_nr == N) m_nr = 0;
125  return (res);
126  }
127 
133  void decrypt(void* buf, size_t n)
134  {
135  for (char* bp = (char*) buf; n--; bp++)
136  *bp = decrypt(*bp);
137  }
138 
145  void decrypt(void* dest, const void* src, size_t n)
146  {
147  char* dp = (char*) dest;
148  const char* sp = (const char*) src;
149  while (n--) *dp++ = decrypt(*sp++);
150  }
151 
152 private:
153  char m_key[N];
154  uint8_t m_nr;
155  uint8_t m_max;
156  uint8_t m_pos;
157 };
158 
159 #endif
Vigenere(const char *password)
Definition: Vigenere.hh:59
void encrypt(void *dest, const void *src, size_t n)
Definition: Vigenere.hh:108
char decrypt(char c)
Definition: Vigenere.hh:120
void restart()
Definition: Vigenere.hh:72
char encrypt(char c)
Definition: Vigenere.hh:83
void encrypt(void *buf, size_t n)
Definition: Vigenere.hh:96
uint32_t random(uint32_t range)
Definition: Math.hh:59
void decrypt(void *buf, size_t n)
Definition: Vigenere.hh:133
Vigenere(uint32_t seed, uint8_t n=N)
Definition: Vigenere.hh:43
#define UNLIKELY(x)
Definition: Types.h:153
void decrypt(void *dest, const void *src, size_t n)
Definition: Vigenere.hh:145