我有一个系统需要安排一些任务并向某些外部对象返回这些任务的标识符。用户基本上需要执行以下操作:
identifier = MyLib.Schedule(something)
# Nah, let's unschedule it.
MyLib.Unschedule(identifier)
我在内部代码中经常使用这种模式,我总是使用普通整数作为标识符。但如果标识符被不受信任的代码使用,恶意用户可能通过执行单个Unschedule(randint())
来破坏整个系统。
我需要代码的用户能够只取消已经安排的标识符。
我能想到的唯一解决方案是生成64位随机数作为标识符,并跟踪当前分配的标识符,以避免极不可能的重复。或者是128位?如果有的话,什么时候可以说“这已经足够随机了,不可能出现重复”,或者永远不可能?
或者更好的方法是什么?有没有一种方法可以生成标识符令生成器可以轻松跟踪(避免重复),但对接收者来说与随机数无法区分的标识符令牌?
编辑-基于被接受的答案的解决方案:
from Crypto.Cipher import AES
import struct, os, itertools
class AES_UniqueIdentifier(object):
def __init__(self):
self.salt = os.urandom(8)
self.count = itertools.count(0)
self.cipher = AES.new(os.urandom(16), AES.MODE_ECB)
def Generate(self):
return self.cipher.encrypt(self.salt +
struct.pack("Q", next(self.count)))
def Verify(self, identifier):
"Return true if identifier was generated by this object."
return self.cipher.decrypt(identifier)[0:8] == self.salt