2
0

str2key.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the OpenSSL license (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <openssl/crypto.h>
  10. #include "des_locl.h"
  11. void DES_string_to_key(const char *str, DES_cblock *key)
  12. {
  13. DES_key_schedule ks;
  14. int i, length;
  15. memset(key, 0, 8);
  16. length = strlen(str);
  17. for (i = 0; i < length; i++) {
  18. register unsigned char j = str[i];
  19. if ((i % 16) < 8)
  20. (*key)[i % 8] ^= (j << 1);
  21. else {
  22. /* Reverse the bit order 05/05/92 eay */
  23. j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f);
  24. j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33);
  25. j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55);
  26. (*key)[7 - (i % 8)] ^= j;
  27. }
  28. }
  29. DES_set_odd_parity(key);
  30. DES_set_key_unchecked(key, &ks);
  31. DES_cbc_cksum((const unsigned char *)str, key, length, &ks, key);
  32. OPENSSL_cleanse(&ks, sizeof(ks));
  33. DES_set_odd_parity(key);
  34. }
  35. void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2)
  36. {
  37. DES_key_schedule ks;
  38. int i, length;
  39. memset(key1, 0, 8);
  40. memset(key2, 0, 8);
  41. length = strlen(str);
  42. for (i = 0; i < length; i++) {
  43. register unsigned char j = str[i];
  44. if ((i % 32) < 16) {
  45. if ((i % 16) < 8)
  46. (*key1)[i % 8] ^= (j << 1);
  47. else
  48. (*key2)[i % 8] ^= (j << 1);
  49. } else {
  50. j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f);
  51. j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33);
  52. j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55);
  53. if ((i % 16) < 8)
  54. (*key1)[7 - (i % 8)] ^= j;
  55. else
  56. (*key2)[7 - (i % 8)] ^= j;
  57. }
  58. }
  59. if (length <= 8)
  60. memcpy(key2, key1, 8);
  61. DES_set_odd_parity(key1);
  62. DES_set_odd_parity(key2);
  63. DES_set_key_unchecked(key1, &ks);
  64. DES_cbc_cksum((const unsigned char *)str, key1, length, &ks, key1);
  65. DES_set_key_unchecked(key2, &ks);
  66. DES_cbc_cksum((const unsigned char *)str, key2, length, &ks, key2);
  67. OPENSSL_cleanse(&ks, sizeof(ks));
  68. DES_set_odd_parity(key1);
  69. DES_set_odd_parity(key2);
  70. }