xref: /openssl/crypto/des/str2key.c (revision 33388b44)
1 /*
2  * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 
10 /*
11  * DES low level APIs are deprecated for public use, but still ok for internal
12  * use.
13  */
14 #include "internal/deprecated.h"
15 
16 #include <openssl/crypto.h>
17 #include "des_local.h"
18 
DES_string_to_key(const char * str,DES_cblock * key)19 void DES_string_to_key(const char *str, DES_cblock *key)
20 {
21     DES_key_schedule ks;
22     int i, length;
23 
24     memset(key, 0, 8);
25     length = strlen(str);
26     for (i = 0; i < length; i++) {
27         register unsigned char j = str[i];
28 
29         if ((i % 16) < 8)
30             (*key)[i % 8] ^= (j << 1);
31         else {
32             /* Reverse the bit order 05/05/92 eay */
33             j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f);
34             j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33);
35             j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55);
36             (*key)[7 - (i % 8)] ^= j;
37         }
38     }
39     DES_set_odd_parity(key);
40     DES_set_key_unchecked(key, &ks);
41     DES_cbc_cksum((const unsigned char *)str, key, length, &ks, key);
42     OPENSSL_cleanse(&ks, sizeof(ks));
43     DES_set_odd_parity(key);
44 }
45 
DES_string_to_2keys(const char * str,DES_cblock * key1,DES_cblock * key2)46 void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2)
47 {
48     DES_key_schedule ks;
49     int i, length;
50 
51     memset(key1, 0, 8);
52     memset(key2, 0, 8);
53     length = strlen(str);
54     for (i = 0; i < length; i++) {
55         register unsigned char j = str[i];
56 
57         if ((i % 32) < 16) {
58             if ((i % 16) < 8)
59                 (*key1)[i % 8] ^= (j << 1);
60             else
61                 (*key2)[i % 8] ^= (j << 1);
62         } else {
63             j = ((j << 4) & 0xf0) | ((j >> 4) & 0x0f);
64             j = ((j << 2) & 0xcc) | ((j >> 2) & 0x33);
65             j = ((j << 1) & 0xaa) | ((j >> 1) & 0x55);
66             if ((i % 16) < 8)
67                 (*key1)[7 - (i % 8)] ^= j;
68             else
69                 (*key2)[7 - (i % 8)] ^= j;
70         }
71     }
72     if (length <= 8)
73         memcpy(key2, key1, 8);
74     DES_set_odd_parity(key1);
75     DES_set_odd_parity(key2);
76     DES_set_key_unchecked(key1, &ks);
77     DES_cbc_cksum((const unsigned char *)str, key1, length, &ks, key1);
78     DES_set_key_unchecked(key2, &ks);
79     DES_cbc_cksum((const unsigned char *)str, key2, length, &ks, key2);
80     OPENSSL_cleanse(&ks, sizeof(ks));
81     DES_set_odd_parity(key1);
82     DES_set_odd_parity(key2);
83 }
84