uuid.c revision 8aef66d2125af8de7672a12895276802fcc1948f
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 <string.h>
18#include <arpa/inet.h>
19
20#include "ext4_utils.h"
21#include "sha1.h"
22#include "uuid.h"
23
24struct uuid {
25	u32 time_low;
26	u32 time_mid;
27	u16 time_hi_and_version;
28	u8 clk_seq_hi_res;
29	u8 clk_seq_low;
30	u16 node0_1;
31	u32 node2_5;
32};
33
34static void sha1_hash(const char *namespace, const char *name,
35	unsigned char sha1[SHA1_DIGEST_LENGTH])
36{
37	SHA1_CTX ctx;
38	SHA1Init(&ctx);
39	SHA1Update(&ctx, (const u8*)namespace, strlen(namespace));
40	SHA1Update(&ctx, (const u8*)name, strlen(name));
41	SHA1Final(sha1, &ctx);
42}
43
44void generate_uuid(const char *namespace, const char *name, u8 result[16])
45{
46	unsigned char sha1[SHA1_DIGEST_LENGTH];
47	struct uuid *uuid = (struct uuid *)result;
48
49	sha1_hash(namespace, name, (unsigned char*)sha1);
50	memcpy(uuid, sha1, sizeof(struct uuid));
51
52	uuid->time_low = ntohl(uuid->time_low);
53	uuid->time_mid = ntohs(uuid->time_mid);
54	uuid->time_hi_and_version = ntohs(uuid->time_hi_and_version);
55	uuid->time_hi_and_version &= 0x0FFF;
56	uuid->time_hi_and_version |= (5 << 12);
57	uuid->clk_seq_hi_res &= ~(1 << 6);
58	uuid->clk_seq_hi_res |= 1 << 7;
59}
60