├── .circleci
└── config.yml
├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
├── spotbugs.xml
└── src
├── main
└── java
│ └── com
│ └── codahale
│ └── fastuuid
│ └── UUIDGenerator.java
└── test
└── java
└── com
└── codahale
└── fastuuid
├── Benchmarks.java
└── tests
└── UUIDGeneratorTest.java
/.circleci/config.yml:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright © 2017 Coda Hale (coda.hale@gmail.com)
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 | version: 2
18 | jobs:
19 | build:
20 | docker:
21 | - image: maven:3-jdk-12-alpine
22 | working_directory: ~/repo
23 | environment:
24 | MAVEN_OPTS: -Xmx3200m
25 | steps:
26 | - checkout
27 | - restore_cache:
28 | keys:
29 | - v1-dependencies-{{ checksum ".circleci/config.yml" }}-{{ checksum "pom.xml" }}
30 | # fallback to using the latest cache if no exact match is found
31 | - v1-dependencies-
32 | - run: mvn clean verify
33 | - save_cache:
34 | paths:
35 | - ~/.m2
36 | key: v1-dependencies-{{ checksum ".circleci/config.yml" }}-{{ checksum "pom.xml" }}
37 | - run:
38 | name: Save test results
39 | command: |
40 | mkdir -p ~/junit/
41 | find . -type f -regex ".*/target/surefire-reports/.*xml" -exec cp {} ~/junit/ \;
42 | when: always
43 | - store_test_results:
44 | path: ~/junit
45 | - store_artifacts:
46 | path: ~/junit
47 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | target/
2 | pom.xml.tag
3 | pom.xml.releaseBackup
4 | pom.xml.versionsBackup
5 | pom.xml.next
6 | release.properties
7 | dependency-reduced-pom.xml
8 | buildNumber.properties
9 | .mvn/timing.properties
10 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # fast-uuid
2 |
3 | [](https://circleci.com/gh/codahale/fast-uuid)
4 |
5 | **N.B.: This is a cool design, but is only an order of magnitude faster than the Java 12 standard library. Just use that instead.**
6 |
7 | I dunno, man. It generates v4 UUIDs really quickly.
8 |
9 | ## How quickly
10 |
11 | ```
12 | Benchmark Mode Cnt Score Error Units
13 | Benchmarks.fast avgt 25 48.554 ± 0.568 ns/op
14 | Benchmarks.stdLib avgt 25 1440.938 ± 30.051 ns/op
15 | ```
16 |
17 | ## Ok but how tho
18 |
19 | Instead of `SecureRandom`, `UUIDGenerator` uses
20 | [SipHash-2-4](https://131002.net/siphash/siphash.pdf) in a
21 | [fast-key-erasure](https://blog.cr.yp.to/20170723-random.html) CSPRNG.
22 |
23 | For each UUID, it uses SipHash-2-4 to hash four single-byte values selected for their high Hamming
24 | distances from each other. The first two results are used to re-key the hash; the second two are
25 | used to produce the UUID.
26 |
27 | For UUIDs, a few key properties are desirable:
28 |
29 | 1. They should be uniformly distributed to reduce the probability of collisions.
30 | 2. Anyone who collects a set of UUIDs should be unable to determine which UUIDs were generated and
31 | which UUIDs will be generated.
32 | 3. Anyone who gets privileged access to the computer generating UUIDs should be unable to determine
33 | which UUIDs were previously generated.
34 |
35 | This library attempts to provide those properties.
36 |
37 | **N.B.: I'm not a cryptographer, so no cryptographer evaluated this design. Do not use this without
38 | hiring a cryptographer to evaluate it.**
39 |
40 | For the first property, SipHash is a cryptographically strong PRF, which should make it
41 | indistinguishable from a uniform random function. The UUIDs generated from its output, therefore,
42 | should also be uniformly distributed.
43 |
44 | For the second property, consider the information an attacker might collect: `{h(k, C), h(k, D)}`.
45 | In order to calculate future values, an attacker would need to learn information about `k`. SipHash
46 | is a strong MAC, however, which means key recovery attacks should be as difficult as brute force.
47 | Without the ability to recover `k`, the attacker would find it doubly difficult to calculate past
48 | values (e.g. `h(k, C)` given `h(h(k, A) . h(k, B), C)`).
49 |
50 | For the third property, consider the information an attacker might collect: `h(h(k, A) . h(k, B),
51 | A)`. Again, because SipHash is a strong MAC, an attacker should be unable to recover information
52 | about `k` and therefore unable to calculate past values (e.g. `h(k, C)`). Of course, they *will* be
53 | able to calculate future values, so don't let attackers look at your memory.
54 |
55 | ## Fascinating
56 |
57 | What can I say. I got bored.
58 |
59 | ## License
60 |
61 | Copyright © 2018 Coda Hale
62 |
63 | Distributed under the Apache License 2.0.
64 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
19 |
For each UUID, it uses SipHash-2-4 to hash four single-byte values selected for their high 25 | * Hamming distances from each other. The first two results are used to re-key the hash; the second 26 | * two are used to produce the UUID. 27 | * 28 | *
This design allows for very fast UUID generation (~50ns/UUID) as well as forward-secrecy (i.e. 29 | * a compromised generator reveals no information about previously-generated UUIDs). 30 | * 31 | *
To provide backward-secrecy (i.e. a compromised generator reveals no information about UUIDs 32 | * which will be generated), the generator should be periodically re-seeded. 33 | */ 34 | public class UUIDGenerator { 35 | // four bytes selected for their relatively high Hamming distances 36 | private static final byte A = 0b00000110; 37 | private static final byte B = 0b01111111; 38 | private static final byte C = (byte) 0b10111000; 39 | private static final byte D = (byte) 0b11000001; 40 | 41 | // underlying PRNG 42 | private final SecureRandom random; 43 | 44 | // SipHash state 45 | private long v0, v1, v2, v3; 46 | 47 | /** 48 | * Creates a new {@link UUIDGenerator} seeded from the given PRNG. 49 | * 50 | * @param random a PRNG to use for a seed 51 | */ 52 | public UUIDGenerator(SecureRandom random) { 53 | this.random = random; 54 | reseed(); 55 | } 56 | 57 | /** Re-seeds the {@link UUIDGenerator}. */ 58 | public void reseed() { 59 | reseed(random.nextLong(), random.nextLong()); 60 | } 61 | 62 | private void reseed(long k0, long k1) { 63 | // SipHash magic constants 64 | this.v0 = k0 ^ 0x736F6D6570736575L; 65 | this.v1 = k1 ^ 0x646F72616E646F6DL; 66 | this.v2 = k0 ^ 0x6C7967656E657261L; 67 | this.v3 = k1 ^ 0x7465646279746573L; 68 | } 69 | 70 | /** 71 | * Generates a random {@link UUID}. 72 | * 73 | * @return a random {@link UUID} 74 | */ 75 | public UUID generate() { 76 | final long k0 = sipHash24(v0, v1, v2, v3, A); 77 | final long k1 = sipHash24(v0, v1, v2, v3, B); 78 | final long msb = (sipHash24(v0, v1, v2, v3, C) & ~0xF000L) | 0x4000L; 79 | final long lsb = ((sipHash24(v0, v1, v2, v3, D) << 2) >>> 2) | 0x8000000000000000L; 80 | reseed(k0, k1); 81 | return new UUID(msb, lsb); 82 | } 83 | 84 | // a very slimmed-down version of SipHash-2-4 which operates on a single byte 85 | @SuppressWarnings("Duplicates") 86 | private static long sipHash24(long v0, long v1, long v2, long v3, byte data) { 87 | final long m = (data & 0xFFL) | 0x100000000000000L; // simplify the masking 88 | 89 | v3 ^= m; 90 | for (int i = 0; i < 2; i++) { // put the 2 in SipHash-2-4 91 | v0 += v1; 92 | v2 += v3; 93 | v1 = Long.rotateLeft(v1, 13); 94 | v3 = Long.rotateLeft(v3, 16); 95 | 96 | v1 ^= v0; 97 | v3 ^= v2; 98 | v0 = Long.rotateLeft(v0, 32); 99 | 100 | v2 += v1; 101 | v0 += v3; 102 | v1 = Long.rotateLeft(v1, 17); 103 | v3 = Long.rotateLeft(v3, 21); 104 | 105 | v1 ^= v2; 106 | v3 ^= v0; 107 | v2 = Long.rotateLeft(v2, 32); 108 | } 109 | v0 ^= m; 110 | 111 | v2 ^= 0xFF; 112 | for (int i = 0; i < 4; i++) { // put the 4 in SipHash-2-4 113 | v0 += v1; 114 | v2 += v3; 115 | v1 = Long.rotateLeft(v1, 13); 116 | v3 = Long.rotateLeft(v3, 16); 117 | 118 | v1 ^= v0; 119 | v3 ^= v2; 120 | v0 = Long.rotateLeft(v0, 32); 121 | 122 | v2 += v1; 123 | v0 += v3; 124 | v1 = Long.rotateLeft(v1, 17); 125 | v3 = Long.rotateLeft(v3, 21); 126 | 127 | v1 ^= v2; 128 | v3 ^= v0; 129 | v2 = Long.rotateLeft(v2, 32); 130 | } 131 | return v0 ^ v1 ^ v2 ^ v3; 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/test/java/com/codahale/fastuuid/Benchmarks.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2018 Coda Hale (coda.hale@gmail.com) 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 | package com.codahale.fastuuid; 17 | 18 | import java.security.SecureRandom; 19 | import java.util.UUID; 20 | import java.util.concurrent.TimeUnit; 21 | import org.openjdk.jmh.annotations.Benchmark; 22 | import org.openjdk.jmh.annotations.BenchmarkMode; 23 | import org.openjdk.jmh.annotations.Mode; 24 | import org.openjdk.jmh.annotations.OutputTimeUnit; 25 | import org.openjdk.jmh.annotations.Scope; 26 | import org.openjdk.jmh.annotations.State; 27 | 28 | @BenchmarkMode(Mode.AverageTime) 29 | @OutputTimeUnit(TimeUnit.NANOSECONDS) 30 | @State(Scope.Benchmark) 31 | public class Benchmarks { 32 | private final UUIDGenerator generator = new UUIDGenerator(new SecureRandom()); 33 | 34 | @Benchmark 35 | public UUID fast() { 36 | return generator.generate(); 37 | } 38 | 39 | @Benchmark 40 | public UUID stdLib() { 41 | return UUID.randomUUID(); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/test/java/com/codahale/fastuuid/tests/UUIDGeneratorTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright © 2018 Coda Hale (coda.hale@gmail.com) 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 | package com.codahale.fastuuid.tests; 17 | 18 | import static org.assertj.core.api.Assertions.assertThat; 19 | import static org.mockito.Mockito.mock; 20 | import static org.mockito.Mockito.when; 21 | 22 | import com.codahale.fastuuid.UUIDGenerator; 23 | import java.security.SecureRandom; 24 | import org.junit.jupiter.api.Test; 25 | 26 | class UUIDGeneratorTest { 27 | @Test 28 | void generating() { 29 | final SecureRandom random = mock(SecureRandom.class); 30 | when(random.nextLong()) 31 | .thenReturn( 32 | 0xb8d59fd5bc12dbb4L, 0x31e9f344b73ee369L, 0xb8d59fd5bc12dbb4L, 0x31e9f344b73ee369L); 33 | 34 | final UUIDGenerator generator = new UUIDGenerator(random); 35 | assertThat(generator.generate().toString()).isEqualTo("88e6891a-3dbc-423c-b51a-127083468307"); 36 | assertThat(generator.generate().toString()).isEqualTo("ad173908-cbe5-49a7-8a36-b516b033b4bd"); 37 | assertThat(generator.generate().version()).isEqualTo(4); 38 | assertThat(generator.generate().variant()).isEqualTo(2); 39 | 40 | generator.reseed(); 41 | assertThat(generator.generate().toString()).isEqualTo("88e6891a-3dbc-423c-b51a-127083468307"); 42 | } 43 | } 44 | --------------------------------------------------------------------------------