【问题标题】:Generating activation key from serial number从序列号生成激活密钥
【发布时间】:2011-11-22 23:05:43
【问题描述】:

我有具有唯一序列号(字符串递增)的设备,例如:AS1002 和 AS1003。

我需要找出一种算法来为每个序列号生成一个唯一的激活密钥。

最好的方法是什么?

谢谢!

(必须离线完成)

【问题讨论】:

标签: c# .net asp.net vb.net algorithm


【解决方案1】:

这里有两件事需要考虑:
- 您生成的任何密钥都必须能够轻松输入,因此这消除了一些奇怪的散列,这些散列可能会产生难以输入的字符,尽管可以克服这一点,但这是您应该考虑的问题。
- 您所说的操作必须在线完成

首先,没有办法绝对肯定地说,无论您尝试如何混淆,都无法破译您的密钥生成程序。只需对“Crack for Xyz software”进行搜索引擎查询。

这是一场永无止境的长期战斗,因此将软件作为服务交付,即在线生产者对其内容有更多控制权,并且可以明确授权和验证用户。在您的情况下,您想离线执行此操作。因此,在您的场景中,有人会将您的设备连接到某个系统,而您打算编写此例程的随附软件将根据设备的序列号与用户输入进行检查。

根据@sll 的回答,鉴于您的请求是离线的。不幸的是,最好的办法是生成一组随机代码,并在用户调用时验证它们。

这是从另一个 SO 答案借来的method,我也添加了数字

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; //Added 1-9

private string RandomString(int size)
{
    char[] buffer = new char[size];

    for (int i = 0; i < size; i++)
    {
        buffer[i] = _chars[_rng.Next(_chars.Length)];
    }
    return new string(buffer);
}

因此,出于离线考虑,为您的每台设备生成一个并将它们存储在某处可能是您唯一的选择。

当设置为创建一个相当随机的 10 位字符串时,此例程将生成类似这样的字符串。

3477KXFBDQ
ROT6GRA39O
40HTLJPFCL
5M2F44M5CH
CAVAO780NR
8XBQ44WNUA
IA02WEWOCM
EG11L4OGFO
LP2UOGKKLA
H0JB0BA4NJ
KT8AN18KFA

【讨论】:

    【解决方案2】:

    到目前为止,最安全的方法是拥有一个集中的(序列号、激活密钥)对数据库,并让用户通过互联网激活,这样您就可以在本地(在服务器上)检查密钥。

    在这个实现中,激活密钥可以是完全随机的,因为它不需要依赖于序列号。

    【讨论】:

      【解决方案3】:

      您希望它易于检查,并且难以“倒退”。你会看到很多关于使用散列函数的建议,这些函数很容易单向,但很难倒退。 Previously,我说的是“把牛变成汉堡很容易,但是把汉堡变成牛很难”。在这种情况下,设备应该知道自己的序列号,并且能够“添加”(或附加)一些秘密(通常称为“盐”)到序列号,然后对其进行散列或加密。

      如果您使用的是可逆加密,您想在序列号中添加某种“check digit”,这样如果有人确定了您的加密方案,那么他们还有另一层需要弄清楚。

      我解决了with Excel while trying to avoid homework 的一个很容易“倒退”的函数示例。

      并且您可能希望通过在手写激活码时减少编码混乱的可能性(例如您从电子邮件中写下来然后走到设备所在的位置并打卡),从而使您的客户更轻松中的字母/数字)。在许多字体中,I 和 1,0 和 O 足够相似,以至于许多编码,例如您的汽车的 VIN 不使用字母 i 和 o(我记得旧打字机缺少数字 1 的键,因为您应该使用小写字母 L)。在这种情况下,Y、4 和 7 可能会根据某些笔迹显示相同。所以要了解你的听众以及他们的极限。

      【讨论】:

      • 盐不是秘密的,用于防止预计算攻击。在这种情况下,它是一个密钥,应该在 HMAC 中使用。
      【解决方案4】:

      如果您的设备有一些无法通过连接编程器或其他设备读取的安全内存 - 您可以存储一些密钥代码,然后使用任何散列算法(如 MD5 或 SHA-1/2)通过以下方式生成散列:

      HASH(PUBLIC_SERIALNUMBER + PRIVATE_KEYCODE)
      

      并且成对的 SERIALNUMBER + KEYCODE 应该存储在本地数据库中。

      这样:(离线)

      • 客户打电话给您并要求提供激活码
      • 您要求提供特定设备的序列号
      • 然后您在本地数据库中按给定的 SERIALNUMBER 搜索 KEYCODE 并生成激活码(即使使用 MD5,只要 KEYCODE 私下存储在您的数据库中,这将是安全的)
      • 客户端将激活码输入设备,设备能够生成哈希 通过自己的 SERIALNUMBER 和 KEYCODE,然后与用户输入的激活码进行比较

      如果设备具有板载安全内存(如智能卡),则可以通过存储激活码本身来简化此操作。这样您就可以保留自己的 SerialCode - ActivationCode 对数据库。

      【讨论】:

      • 如果你要追求安全,那就放弃 MD5 是安全的谬论。
      • @Mr.失望:我之前有说过MD5是安全的吗?基本上我说的是相反的,如果让你感到困惑,对不起:)
      • 也许这就是您的意思,但您原始输入的以下内容似乎与此矛盾:'例如,我将使用 MD5 或 SHA-1/2'
      • 是的,但我也说过 anyone can generate activation key by serial number because hash would be the same. 这显然意味着这不是安全的方式
      • 您是在通过默默无闻来倡导安全。我们真的有理由认为这是个坏主意吗?
      【解决方案5】:

      激活密钥

      下面是激活密钥的简单结构:

      Part Description
      Data A part of the key encrypted with a password. Contains the key expiration date and application options.
      Hash Checksum of the key expiration date, password, options and environment parameters.
      Tail The initialization vector that used to decode the data (so-called "salt").
      class ActivationKey
      {
          public byte[] Data { get; set; } // Encrypted part.
          public byte[] Hash { get; set; } // Hashed part.
          public byte[] Tail { get; set; } // Initialization vector.
      }
      

      密钥可以表示为文本格式:DATA-HASH-TAIL。 例如:
      KCATBZ14Y-VGDM2ZQ-ATSVYMI.
      以下工具将使用加密转换来生成和验证密钥。

      生成

      获取数据集唯一激活密钥的算法包括几个步骤:

      • 数据收集,
      • 获取哈希和数据加密,
      • 将激活密钥转换为字符串。

      数据收集

      在这一步,需要获取序列号、设备ID、到期日期等数据数组。这个目的可以通过下面的方式来实现

      方法:

      unsafe byte[] Serialize(params object[] objects)
      {
        using (MemoryStream memory = new MemoryStream())
        using (BinaryWriter writer = new BinaryWriter(memory))
        {
          foreach (object obj in objects)
          {
            if (obj == null) continue;
            switch (obj)
            {
              case string str:
                if (str.Length > 0)
                  writer.Write(str.ToCharArray());
                continue;
              case DateTime date:
                writer.Write(date.Ticks);
                continue;
              case bool @bool:
                writer.Write(@bool);
                continue;
              case short @short:
                writer.Write(@short);
                continue;
              case ushort @ushort:
                writer.Write(@ushort);
                continue;
              case int @int:
                writer.Write(@int);
                continue;
              case uint @uint:
                writer.Write(@uint);
                continue;
              case long @long:
                writer.Write(@long);
                continue;
              case ulong @ulong:
                writer.Write(@ulong);
                continue;
              case float @float:
                writer.Write(@float);
                continue;
              case double @double:
                writer.Write(@double);
                continue;
              case decimal @decimal:
                writer.Write(@decimal);
                continue;
              case byte[] buffer:
                if (buffer.Length > 0)
                  writer.Write(buffer);
                continue;
              case Array array:
                if (array.Length > 0)
                  foreach (var a in array) writer.Write(Serialize(a));
                continue;
              case IConvertible conv:
                writer.Write(conv.ToString(CultureInfo.InvariantCulture));
                continue;
              case IFormattable frm:
                writer.Write(frm.ToString(null, CultureInfo.InvariantCulture));
                continue;
              case Stream stream:
                stream.CopyTo(stream);
                continue;
              default:
                try
                {
                  int rawsize = Marshal.SizeOf(obj);
                  byte[] rawdata = new byte[rawsize];
                  GCHandle handle = GCHandle.Alloc(rawdata, GCHandleType.Pinned);
                  Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false);
                  writer.Write(rawdata);
                  handle.Free();
                }
                catch(Exception e)
                {
                  // Place debugging tools here.
                }
                continue;
            }
          }
          writer.Flush();
          byte[] bytes = memory.ToArray();
          return bytes;
        }
      }
      

      获取哈希和数据加密

      此步骤包含以下子步骤:

      • 使用密码创建加密引擎并将初始化向量存储在 Tail 属性中。
      • 下一步,到期日期和选项被加密,加密的数据被保存到 Data 属性中。
      • 最后,哈希引擎根据过期日期、密码、选项和环境计算出一个哈希,并将其放入哈希属性中。
      ActivationKey Create<TAlg, THash>(DateTime expirationDate, 
                                        object password, 
                                        object options = null, 
                                        params object[] environment)
          where TAlg : SymmetricAlgorithm
          where THash : HashAlgorithm
      {
          ActivationKey activationKey = new ActivationKey();
          using (SymmetricAlgorithm cryptoAlg = Activator.CreateInstance<TAlg>())
          {
              if (password == null)
              {
                  password = new byte[0];
              }
              activationKey.Tail = cryptoAlg.IV;
              using (DeriveBytes deriveBytes = 
              new PasswordDeriveBytes(Serialize(password), activationKey.Tail))
              {
                  cryptoAlg.Key = deriveBytes.GetBytes(cryptoAlg.KeySize / 8);
              }
              expirationDate = expirationDate.Date;
              long expirationDateStamp = expirationDate.ToBinary();
              using (ICryptoTransform transform = cryptoAlg.CreateEncryptor())
              {
                  byte[] data = Serialize(expirationDateStamp, options);
                  activationKey.Data = transform.TransformFinalBlock(data, 0, data.Length);
              }
              using (HashAlgorithm hashAlg = Activator.CreateInstance<THash>())
              {
                  byte[] data = Serialize(expirationDateStamp, 
                                          cryptoAlg.Key, 
                                          options, 
                                          environment, 
                                          activationKey.Tail);
                  activationKey.Hash = hashAlg.ComputeHash(data);
              }
          }
          return activationKey;
      }
      

      转换成字符串

      使用 ToString 方法获取包含关键文本的字符串,准备好传输给最终用户。

      基于 N 的编码(其中 N 是数字系统的基数)通常用于将二进制数据转换为人类可读的文本。最常用于 激活密钥是 base32。这种编码的优点是由不区分大小写的数字和字母组成的大字母表。缺点是这种编码没有在 .NET 标准库中实现,您应该自己实现。您还可以使用 mscorlib 中内置的 hex 编码和 base64。在我的示例中使用了 base32,但我不会在这里给出它的源代码。这个网站上有很多base32实现的例子。

      string ToString(ActivationKey activationKey)
      {
          if (activationKey.Data == null 
             || activationKey.Hash == null 
             || activationKey.Tail == null)
          {
              return string.Empty;
          }
          using (Base32 base32 = new Base32())
          {
              return base32.Encode(activationKey.Data) 
                     + "-" + base32.Encode(activationKey.Hash) 
                     + "-" + base32.Encode(activationKey.Tail);
          }
      }
      

      使用以下方法恢复:

      ActivationKey Parse(string text)
      {
          ActivationKey activationKey;
          string[] items = text.Split('-');
          if (items.Length >= 3)
          {
              using (Base32 base32 = new Base32())
              {
                  activationKey.Data = base32.Decode(items[0]);
                  activationKey.Hash = base32.Decode(items[1]);
                  activationKey.Tail = base32.Decode(items[2]);
              }
          }
          return activationKey;
      }
      

      检查

      使用 GetOptions 和 Verify 方法进行密钥验证。

      • GetOptions 检查密钥并将嵌入的数据恢复为字节数组,如果密钥无效,则返回 null。
      • 验证只检查密钥。
      byte[] GetOptions<TAlg, THash>(object password = null, params object[] environment)
          where TAlg : SymmetricAlgorithm
          where THash : HashAlgorithm
      {
          if (Data == null || Hash == null || Tail == null)
          {
              return null;
          }
          try
          {
              using (SymmetricAlgorithm cryptoAlg = Activator.CreateInstance<TAlg>())
              {
                  cryptoAlg.IV = Tail;
                  using (DeriveBytes deriveBytes = 
                  new PasswordDeriveBytes(Serialize(password), Tail))
                  {
                      cryptoAlg.Key = deriveBytes.GetBytes(cryptoAlg.KeySize / 8);
                  }
                  using (ICryptoTransform transform = cryptoAlg.CreateDecryptor())
                  {
                      byte[] data = transform.TransformFinalBlock(Data, 0, Data.Length);
                      int optionsLength = data.Length - 8;
                      if (optionsLength < 0)
                      {
                          return null;
                      }
                      byte[] options;
                      if (optionsLength > 0)
                      {
                          options = new byte[optionsLength];
                          Buffer.BlockCopy(data, 8, options, 0, optionsLength);
                      }
                      else
                      {
                          options = new byte[0];
                      }
                      long expirationDateStamp = BitConverter.ToInt64(data, 0);
                      DateTime expirationDate = DateTime.FromBinary(expirationDateStamp);
                      if (expirationDate < DateTime.Today)
                      {
                          return null;
                      }
                      using (HashAlgorithm hashAlg = 
                      Activator.CreateInstance<THash>())
                      {
                          byte[] hash = 
                          hashAlg.ComputeHash(
                               Serialize(expirationDateStamp, 
                                         cryptoAlg.Key, 
                                         options, 
                                         environment, 
                                         Tail));
                          return ByteArrayEquals(Hash, hash) ? options : null;
                      }
                  }
              }
          }
          catch
          {
              return null;
          }
      }
      
      bool Verify<TAlg, THash>(object password = null, params object[] environment)
          where TAlg : SymmetricAlgorithm
          where THash : HashAlgorithm
      {
          try
          {
              byte[] key = Serialize(password);
              return Verify<TAlg, THash>(key, environment);
          }
          catch
          {
              return false;
          }
      }
      

      示例

      Here 是使用您自己的任意数据量(文本、字符串、数字、字节等)组合生成激活密钥的完整示例。

      使用示例:

      string serialNumber = "0123456789"; // The serial number.
      const string appName = "myAppName"; // The application name.
      
      // Generating the key. All the parameters passed to the costructor can be omitted.
      ActivationKey activationKey = new ActivationKey(
      //expirationDate:
      DateTime.Now.AddMonths(1),  // Expiration date 1 month later.
                                  // Pass DateTime.Max for unlimited use.
      //password:
      null,                       // Password protection;
                                  // this parameter can be null.
      //options:
      null                       // Pass here numbers, flags, text or other
                                 // that you want to restore 
                                 // or null if no necessary.
      //environment:
      appName, serialNumber      // Application name and serial number.
      );
      // Thus, a simple check of the key for validity is carried out.
      bool checkKey = activationKey.Verify((byte[])null, appName, serialNumber);
      if (!checkKey)
      {
        MessageBox.Show("Your copy is not activated! Please get a valid activation key.");
        Application.Exit();
      }
      

      【讨论】:

        【解决方案6】:

        怎么样:发明一个不向用户透露的密码。然后将此密码与序列号连接起来,并对组合进行哈希处理。

        您所做的任何事情都可能被足够敬业的黑客破解。问题不在于“我能创造绝对牢不可破的安全吗?”但是“我是否可以创建足够好的安全性来抵御不熟练的黑客并使熟练的黑客不值得付出努力?”如果您合理地期望销售 1000 万份您的产品,那么您将成为一个大目标,并且可能会有很多黑客试图破解它。如果您希望卖出几百或几千份,那就不要那么多了。

        【讨论】:

        • “你所做的任何事情都可能被足够敬业的黑客破解。” - 什么?不。那不是真的。
        猜你喜欢
        • 2012-08-12
        • 2014-07-24
        • 1970-01-01
        • 2012-11-30
        • 2023-03-03
        • 2011-12-27
        • 2021-02-08
        • 1970-01-01
        • 2011-01-05
        相关资源
        最近更新 更多