Generating unique IDs
When identifiers are used solely within a database, their generation
should be left to the database itself. (See Statement.getGeneratedKeys
.)
Unique identifiers which are "published" in some way may need special
treatment, since the identifier may need to be difficult to guess or forge.
A typical example is the value of a cookie used as a session identifier
- simply using a series of consecutive integers is generally unacceptable,
since one user could easily impersonate another by altering the value of
the cookie to some nearby integer.
Style 1 - UUID
When Java 5 is available, the
UUID
class provides a simple means for generating
unique ids. The identifiers generated by UUID are actually universally
unique identifiers.
Example
import java.util.UUID;
public class GenerateUUID {
public static final void main(String... aArgs){
UUID idOne = UUID.randomUUID();
UUID idTwo = UUID.randomUUID();
log("UUID One: " + idOne);
log("UUID Two: " + idTwo);
}
private static void log(Object aObject){
System.out.println( String.valueOf(aObject) );
}
}
Example run :
>java -cp . GenerateUUID
UUID One: 067e6162-3b6f-4ae2-a171-2470b63dff00
UUID Two: 54947df8-0e9e-4471-a2f9-9af509fb5889
If Java 5 is not available
, then there are other more laborious ways to generate unique ids (see below).
Style 2 - SecureRandom and MessageDigest
The following method uses SecureRandom
and MessageDigest
:
-
upon startup, initialize SecureRandom
(this may be a lengthy operation)
-
when a new identifier is needed, generate a random number using SecureRandom
-
create a MessageDigest
of the random number
-
encode the byte[]
returned by the MessageDigest
into
some acceptable textual form
-
check if the result is already being used ; if it is not already taken,
it is suitable as a unique identifier
The MessageDigest
class is suitable for generating a "one-way
hash" of arbitrary data. (Note that hash values never uniquely identify
their source data, since different source data can produce the same hash
value. The value of hashCode
, for example, does not uniquely identify
its associated object.) A MessageDigest
takes any input, and produces
a String
which :
-
is of fixed length
-
does not allow the original input to be easily recovered (in fact, this
is very hard)
-
does not uniquely identify the input ; however, similar input will produce
dissimilar message digests
MessageDigest
is often used as a checksum, for verifying that
data has not been altered since its creation.
Example
import java.security.SecureRandom;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class GenerateId {
public static void main (String... arguments) {
try {
SecureRandom prng = SecureRandom.getInstance("SHA1PRNG");
String randomNum = new Integer( prng.nextInt() ).toString();
MessageDigest sha = MessageDigest.getInstance("SHA-1");
byte[] result = sha.digest( randomNum.getBytes() );
System.out.println("Random number: " + randomNum);
System.out.println("Message digest: " + hexEncode(result) );
}
catch ( NoSuchAlgorithmException ex ) {
System.err.println(ex);
}
}
static private String hexEncode( byte[] aInput){
StringBuilder result = new StringBuilder();
char[] digits = {'0', '1', '2', '3', '4','5','6','7','8','9','a','b','c','d','e','f'};
for ( int idx = 0; idx < aInput.length; ++idx) {
byte b = aInput[idx];
result.append( digits[ (b&0xf0) >> 4 ] );
result.append( digits[ b&0x0f] );
}
return result.toString();
}
}
Example run :
>java -cp . GenerateId
Random number: -1103747470
Message digest: c8fff94ba996411079d7114e698b53bac8f7b037
Style 3 - UID
Finally, here is another method, using a java.rmi.server.UID
.
The Serializable
identifiers generated by this class are unique
on the host on which they are generated, provided that
- the host takes more than one millisecond to reboot
- the host's clock is never set to run backwards
In order to construct a UID
that is globally unique, simply pair
a UID
with an InetAddress
.
Example
import java.rmi.server.UID;
public class UniqueId {
public static void main (String... arguments) {
for(int idx=0; idx<10; ++idx){
UID userId = new UID();
System.out.println("User Id: "+ userId);
}
}
}
Example run :
User Id: 3179c3:ec6e28a7ef:-8000
User Id: 3179c3:ec6e28a7ef:-7fff
User Id: 3179c3:ec6e28a7ef:-7ffe
User Id: 3179c3:ec6e28a7ef:-7ffd
User Id: 3179c3:ec6e28a7ef:-7ffc
User Id: 3179c3:ec6e28a7ef:-7ffb
User Id: 3179c3:ec6e28a7ef:-7ffa
User Id: 3179c3:ec6e28a7ef:-7ff9
User Id: 3179c3:ec6e28a7ef:-7ff8
User Id: 3179c3:ec6e28a7ef:-7ff7
Clearly, these are not secure identifiers - knowing one, it is easy
to guess another.
分享到:
相关推荐
each Exe has a unique process id.
简单的随机 ID 生成器。 $ npm install get-uid var...amp-unique-id 基因 简单的 uid 随机 ID 智能身份证 uuid 纯 简单随机ID 无 这个更短更简单,几乎就像id++ ,但没有不良副作用。 该技术被 、 等内部使用。
Get the next unique ID. 2) array atom_explain(string ID); Change unique ID to array includes: timestamp, datacenter id and worker id. example: <?php $id = atom_next_id(); echo $id...
开源项目-denisbrodbeck-machineid.zip,Get the unique machine id of any host (without admin privileges)
安装通过去获取工具$ go get github.com/matoous/go-nanoid/v2用法产生编号id , err := gonanoid . New () 生成具有自定义字母和长度的ID id , err := gonanoid . Generate ( "abcde" , 54 )注意如果您在项目中使用...
email VARCHAR(255) UNIQUE password VARCHAR(255) remember_token VARCHAR(100) NULL Timestamps Laravel 每天的进入和退出时间必须存储在包含以下列的users_times关系表中: id (采用laravel生成的格式) us
h_id references Husband(id) unique 基于主键的一对一 Wife Husband id references Husband(id) id name name create table Husband( id number primary key, name varchar2(15) ); create table Wife( ...
When set, IntraWeb will use an alternate unique ID in URL when SessionOptions.UniqueUrl = True. The actual session id is not exposed which increases application security (this option requires that ...
for example:Via this sequence number to produce an encrypts the ID.The GetDiskSerial.DLL hases already in Delphi, C++Builder, C#, Visual Basic, VB.NET, PowerBuilder and Visual Foxpro succeed to get ...
TitaniumiOSUniqueIDs ...Ti.API.info("UUID : " + iOSUniqueID.getUUID); Ti.API.info("Identifier for vendor: " + iOSUniqueID.getIdentifierForVendor); Ti.API.info("Identifier for advertising: " + iOSUni
_id: uniqueId, map: { loc: { lat: String, long: String }, marker: String, caption: String } GET API /餐厅/:ID 根据其唯一ID返回特定餐厅的数据 api/restaurant/555be35472e4ac971324f9d9 >返回The ...
FinTx共同项目FinTx [1]什么是FinTx? FinTx是一个专注于金融技术的开源组织... String id = UniqueId . get() . toBase64String(); 解析ID以获取时间戳,机器标识符(物理MAC地址),进程标识符,计数器编号。 Unique
目标:一种RESTful应用程序,可支持用户创建新端点,向其发布数据并进行访问。 For the project sake... DETAIL(GET): /webhook-testing/v1/endpoints/{uniqueid} CREATE(GET): /webhook-testing/v1/endpoints/create
这个怎么运作/path/api/stuff.js : /** * @api { get } /user/:id Request User information * @apiName GetUser * @apiGroup User * * @apiParam {Number} id Users unique ID. * * @apiSuccess {String} ...
acme : # replace acme by the unique id name : ACME title : Get a 20 € in your ACME account color : ' #f4f4f4 ' # should match the theme color of the company guide : Create an account using this ...
akamai netlist get all | jq -r ' .networkLists[].uniqueId ' | xargs -I{} sh -c " akamai netlist get by-id --id {} --includeElements | jq -r '.list|.[]' > {} " 执行操作所需的凭据 要运行此命令,您确实...
$ go get github.com/aofei/sandid 完毕。 唯一的要求是Go ,至少v1.13。 社区 如果您想讨论SandID或提出有关问题,只需在此处发表问题或想法。 贡献 如果您想帮助构建SandID,只需遵循此步骤即可在此处发送请求...
* @apiParam {Number} id User's unique ID. * * @apiSuccess {String} firstname Firstname of the User. * @apiSuccess {String} lastname Lastname of the User. */ 现在将文档从src/成为doc/ 。 $ apidoc...
另请参见 获得持久的价值 该操作将获得一个值,该值将在GitHub Actions作业,步骤或工作流中持续存在。 配置 该操作采用以下输入: ... id : set_persistent_value uses : aaimio/set-persistent-value@master with :
介绍 已经存在了一段时间。 该库是顶部的补充层,使您... [ Description ( " Retrieve book by its globally unique ID. " )] public Task < Book> Book ( UserContext context , Id id ) => context . Get ( id );