Generate an encrypted hash from the passed password. If the password is longer than eight characters, only the first eight will be used. The first two characters of the salt are used to modify the encryption algorithm used to generate in the hash in one of 4096 different ways. The characters for t
(password, salt)
| 545 | |
| 546 | |
| 547 | def crypt(password, salt): |
| 548 | """Generate an encrypted hash from the passed password. If the password |
| 549 | is longer than eight characters, only the first eight will be used. |
| 550 | |
| 551 | The first two characters of the salt are used to modify the encryption |
| 552 | algorithm used to generate in the hash in one of 4096 different ways. |
| 553 | The characters for the salt should be upper- and lower-case letters A |
| 554 | to Z, digits 0 to 9, '.' and '/'. |
| 555 | |
| 556 | The returned hash begins with the two characters of the salt, and |
| 557 | should be passed as the salt to verify the password. |
| 558 | |
| 559 | Example: |
| 560 | |
| 561 | >>> from fcrypt import crypt |
| 562 | >>> password = 'AlOtBsOl' |
| 563 | >>> salt = 'cE' |
| 564 | >>> hash = crypt(password, salt) |
| 565 | >>> hash |
| 566 | 'cEpWz5IUCShqM' |
| 567 | >>> crypt(password, hash) == hash |
| 568 | 1 |
| 569 | >>> crypt('IaLaIoK', hash) == hash |
| 570 | 0 |
| 571 | |
| 572 | In practice, you would read the password using something like the |
| 573 | getpass module, and generate the salt randomly: |
| 574 | |
| 575 | >>> import random, string |
| 576 | >>> saltchars = string.ascii_letters + string.digits + './' |
| 577 | >>> salt = random.choice(saltchars) + random.choice(saltchars) |
| 578 | |
| 579 | Note that other ASCII characters are accepted in the salt, but the |
| 580 | results may not be the same as other versions of crypt. In |
| 581 | particular, '_', '$1' and '$2' do not select alternative hash |
| 582 | algorithms such as the extended passwords, MD5 crypt and Blowfish |
| 583 | crypt supported by the OpenBSD C library. |
| 584 | """ |
| 585 | |
| 586 | # Extract the salt. |
| 587 | if len(salt) == 0: |
| 588 | salt = 'AA' |
| 589 | elif len(salt) == 1: |
| 590 | salt = salt + 'A' |
| 591 | Eswap0 = _con_salt[ord(salt[0]) & 0x7f] |
| 592 | Eswap1 = _con_salt[ord(salt[1]) & 0x7f] << 4 |
| 593 | |
| 594 | # Generate the key and use it to apply the encryption. |
| 595 | ks = _set_key((password + '\0\0\0\0\0\0\0\0')[:8]) |
| 596 | o1, o2 = _body(ks, Eswap0, Eswap1) |
| 597 | |
| 598 | # Extract 24-bit subsets of result with bytes reversed. |
| 599 | t1 = (o1 << 16 & 0xff0000) | (o1 & 0xff00) | (o1 >> 16 & 0xff) |
| 600 | t2 = (o1 >> 8 & 0xff0000) | (o2 << 8 & 0xff00) | (o2 >> 8 & 0xff) |
| 601 | t3 = (o2 & 0xff0000) | (o2 >> 16 & 0xff00) |
| 602 | # Extract 6-bit subsets. |
| 603 | r = [ t1 >> 18 & 0x3f, t1 >> 12 & 0x3f, t1 >> 6 & 0x3f, t1 & 0x3f, |
| 604 | t2 >> 18 & 0x3f, t2 >> 12 & 0x3f, t2 >> 6 & 0x3f, t2 & 0x3f, |
no test coverage detected
searching dependent graphs…