speck3264.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #include <stdio.h>
  2. #include <stdint.h>
  3. #include "speck.h"
  4. void Words16ToBytes(u16 words[],u8 bytes[],int numwords)
  5. {
  6. int i,j=0;
  7. for(i=0;i<numwords;i++){
  8. bytes[j]=(u8)words[i];
  9. bytes[j+1]=(u8)(words[i]>>8);
  10. j+=2;
  11. }
  12. }
  13. void BytesToWords16(u8 bytes[],u16 words[],int numbytes)
  14. {
  15. int i,j=0; for(i=0;i<numbytes/2;i++){
  16. words[i]=(u16)bytes[j] | ((u16)bytes[j+1]<<8);
  17. j+=2;
  18. }
  19. }
  20. void Speck3264KeySchedule(u16 K[],u16 rk[])
  21. {
  22. u16 i,D=K[3],C=K[2],B=K[1],A=K[0];
  23. for(i=0;i<22;){
  24. rk[i]=A; ER16(B,A,i++);
  25. rk[i]=A; ER16(C,A,i++);
  26. rk[i]=A; ER16(D,A,i++);
  27. }
  28. }
  29. void Speck3264Encrypt(u16 Pt[],u16 Ct[],u16 rk[])
  30. {
  31. u16 i;
  32. Ct[0]=Pt[0]; Ct[1]=Pt[1];
  33. // full 22 rounds
  34. // for(i=0;i<22;) ;
  35. //ER16(Ct[1],Ct[0],rk[0]);
  36. for(i=0;i<22;) {
  37. //ER16(Ct[1],Ct[0],0xdead);
  38. ER16(Ct[1],Ct[0],rk[i++]);
  39. }
  40. }
  41. void Speck3264Decrypt(u16 Pt[],u16 Ct[],u16 rk[])
  42. {
  43. int i;
  44. Pt[0]=Ct[0]; Pt[1]=Ct[1];
  45. for(i=21;i>=0;) DR16(Pt[1],Pt[0],rk[i--]);
  46. }
  47. void Speck3264_EncryptBlock(u8 pt[], u8 k[], u8 ct[]) {
  48. u16 Pt[2] = {0};
  49. u16 K[4] = {0};
  50. u16 rk[34] = {0};
  51. u16 Ct[2] = {0};
  52. BytesToWords16(pt,Pt,8);
  53. BytesToWords16(k,K,16);
  54. Speck3264KeySchedule(K,rk);
  55. // DEBUG Purposes
  56. /*
  57. for (int i=0; i < 16; i++)
  58. {
  59. printf("Key: 0x%x\n", rk[i]);
  60. }
  61. */
  62. Speck3264Encrypt(Pt,Ct,rk);
  63. Words16ToBytes(Ct,ct,2);
  64. }
  65. /*
  66. int main() {
  67. // test are from https://github.com/inmcm/Simon_Speck_Ciphers
  68. //u8 key[8] = {0x00, 0x01, 0x08, 0x09, 0x10, 0x11, 0x18, 0x19};
  69. u8 pt[4] = {0x4c, 0x69, 0x74, 0x65};
  70. u8 key[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
  71. u8 ct[4] = {0x0};
  72. Speck3264_EncryptBlock(pt, key, ct);
  73. printf("[[ Speck 32/64 ]]\n");
  74. printf("The output: \n");
  75. for (int i = 0; i < 4; i++) {
  76. printf("- %08x\n", ct[i]);
  77. }
  78. return 0;
  79. }
  80. */