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 <stdlib.h> 24 #include <string.h> 25 #include <unistd.h> 26 27 /** 28 * Simple program to generate a key based on PBKDF2 with preset inputs. 29 * 30 * Will print out the salt and key in hex. 31 */ 32 33 #define SALT_LEN 8 34 #define ROUNDS 1024 35 #define KEY_BITS 128 36 37 int main(int argc, char* argv[]) 38 { 39 if (argc != 2) { 40 fprintf(stderr, "Usage: %s <password>\n", argv[0]); 41 exit(1); 42 } 43 44 int fd = open("/dev/urandom", O_RDONLY); 45 if (fd < 0) { 46 fprintf(stderr, "Could not open /dev/urandom: %s\n", strerror(errno)); 47 close(fd); 48 exit(1); 49 } 50 51 unsigned char salt[SALT_LEN]; 52 53 if (read(fd, &salt, SALT_LEN) != SALT_LEN) { 54 fprintf(stderr, "Could not read salt from /dev/urandom: %s\n", strerror(errno)); 55 close(fd); 56 exit(1); 57 } 58 close(fd); 59 60 unsigned char rawKey[KEY_BITS]; 61 62 if (PKCS5_PBKDF2_HMAC_SHA1(argv[1], strlen(argv[1]), salt, SALT_LEN, 63 ROUNDS, KEY_BITS, rawKey) != 1) { 64 fprintf(stderr, "Could not generate PBKDF2 output: %s\n", strerror(errno)); 65 exit(1); 66 } 67 68 printf("salt="); 69 for (int i = 0; i < SALT_LEN; i++) { 70 printf("%02x", salt[i]); 71 } 72 printf("\n"); 73 74 printf("key="); 75 for (int i = 0; i < (KEY_BITS / 8); i++) { 76 printf("%02x", rawKey[i]); 77 } 78 printf("\n"); 79 } 80