speck3264.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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;
  16. for(i=0;i<numbytes/2;i++){
  17. words[i]=(u16)bytes[j] | ((u16)bytes[j+1]<<8);
  18. j+=2;
  19. }
  20. }
  21. void Speck3264KeySchedule(u16 K[],u16 rk[])
  22. {
  23. u16 i,D=K[3],C=K[2],B=K[1],A=K[0];
  24. for(i=0;i<22;){
  25. rk[i]=A; ER16(B,A,i++);
  26. rk[i]=A; ER16(C,A,i++);
  27. rk[i]=A; ER16(D,A,i++);
  28. }
  29. }
  30. void Speck3264Encrypt(u16 Pt[],u16 Ct[],u16 rk[])
  31. {
  32. u16 i;
  33. Ct[0]=Pt[0]; Ct[1]=Pt[1];
  34. for(i=0;i<22;) ER16(Ct[1],Ct[0],rk[i++]);
  35. }
  36. void Speck3264Decrypt(u16 Pt[],u16 Ct[],u16 rk[])
  37. {
  38. int i;
  39. Pt[0]=Ct[0]; Pt[1]=Ct[1];
  40. for(i=21;i>=0;) DR16(Pt[1],Pt[0],rk[i--]);
  41. }
  42. void EncryptBlock(u8 pt[], u8 k[], u8 ct[]) {
  43. u16 Pt[2] = {0};
  44. u16 K[4] = {0};
  45. u16 rk[34] = {0};
  46. u16 Ct[2] = {0};
  47. BytesToWords16(pt,Pt,8);
  48. BytesToWords16(k,K,16);
  49. Speck3264KeySchedule(K,rk);
  50. for (int i=0; i < 16; i++)
  51. {
  52. printf("Key: 0x%x\n", rk[i]);
  53. }
  54. Speck3264Encrypt(Pt,Ct,rk);
  55. Words16ToBytes(Ct,ct,2);
  56. }
  57. int main() {
  58. u8 key[8] = {0x1, 0x2,0x3,0x4,0x5,0x6,0x7,0x8};
  59. u8 pt[4] = {0xde, 0xad, 0xbe, 0xef};
  60. u8 ct[4] = {0x0};
  61. EncryptBlock(pt, key, ct);
  62. printf("[[ Speck 32/64 ]]\n");
  63. printf("The output: \n");
  64. for (int i = 0; i < 4; i++) {
  65. printf("- %08x\n", ct[i]);
  66. }
  67. return 0;
  68. }