Kenny Root | 3b1abba | 2010-10-13 15:00:07 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2010 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include <openssl/evp.h> |
| 18 | |
| 19 | #include <sys/types.h> |
| 20 | #include <errno.h> |
| 21 | #include <fcntl.h> |
| 22 | #include <stdio.h> |
| 23 | #include <string.h> |
| 24 | #include <unistd.h> |
| 25 | |
| 26 | /** |
| 27 | * Simple program to generate a key based on PBKDF2 with preset inputs. |
| 28 | * |
| 29 | * Will print out the salt and key in hex. |
| 30 | */ |
| 31 | |
| 32 | #define SALT_LEN 8 |
| 33 | #define ROUNDS 1024 |
| 34 | #define KEY_BITS 128 |
| 35 | |
| 36 | int main(int argc, char* argv[]) |
| 37 | { |
| 38 | if (argc != 2) { |
| 39 | fprintf(stderr, "Usage: %s <password>\n", argv[0]); |
| 40 | exit(1); |
| 41 | } |
| 42 | |
| 43 | int fd = open("/dev/urandom", O_RDONLY); |
| 44 | if (fd < 0) { |
| 45 | fprintf(stderr, "Could not open /dev/urandom: %s\n", strerror(errno)); |
| 46 | close(fd); |
| 47 | exit(1); |
| 48 | } |
| 49 | |
| 50 | unsigned char salt[SALT_LEN]; |
| 51 | |
| 52 | if (read(fd, &salt, SALT_LEN) != SALT_LEN) { |
| 53 | fprintf(stderr, "Could not read salt from /dev/urandom: %s\n", strerror(errno)); |
| 54 | close(fd); |
| 55 | exit(1); |
| 56 | } |
| 57 | close(fd); |
| 58 | |
| 59 | unsigned char rawKey[KEY_BITS]; |
| 60 | |
| 61 | if (PKCS5_PBKDF2_HMAC_SHA1(argv[1], strlen(argv[1]), salt, SALT_LEN, |
| 62 | ROUNDS, KEY_BITS, rawKey) != 1) { |
| 63 | fprintf(stderr, "Could not generate PBKDF2 output: %s\n", strerror(errno)); |
| 64 | exit(1); |
| 65 | } |
| 66 | |
| 67 | printf("salt="); |
| 68 | for (int i = 0; i < SALT_LEN; i++) { |
| 69 | printf("%02x", salt[i]); |
| 70 | } |
| 71 | printf("\n"); |
| 72 | |
| 73 | printf("key="); |
| 74 | for (int i = 0; i < (KEY_BITS / 8); i++) { |
| 75 | printf("%02x", rawKey[i]); |
| 76 | } |
| 77 | printf("\n"); |
| 78 | } |