2011-06-27 91 views
4

我正在尋找一種方法來由PHP腳本生成許可證密鑰,然後將其傳輸到我的應用程序(Air,AS3),並在此應用程序中正確讀取數據。例如,這裏是代碼:PHP許可證密鑰生成器

<?php 
    error_reporting(E_ALL); 
    function KeyGen(){ 
    $key = md5(mktime()); 
    $new_key = ''; 
    for($i=1; $i <= 25; $i ++){ 
       $new_key .= $key[$i]; 
       if ($i%5==0 && $i != 25) $new_key.='-'; 
    } 
    return strtoupper($new_key); 
    } 
    echo KeyGen(); 
?> 

的生成有關這樣的關鍵:1AS7-09BD-96A1-CC8D-F106。 我想向關鍵電子郵件用戶添加一些信息,然後將其傳遞給客戶端(Air應用程序),解密數據和應用程序中的編碼錯誤。

可能嗎?

+0

嗯,這不是那麼容易,你需要擁有屬於該序列所有者的特定數據,以使它們獨一無二 – RobertPitt

+0

需要將多少數據字節存儲到「密鑰」中? – hakre

+0

@RobertPitt。是的,當然,鑰匙必須是獨一無二的。 – Astraport

回答

3

確定可以打破你問:

您希望:

  1. 添加一些信息到關鍵
    好你想添加什麼樣的信息?當你這樣做時,你想讓鑰匙更長嗎?你是否希望這些信息需要密鑰解密?在極端的意義上,這很可能與PHP
  2. 電子郵件用戶
    PHP有mail()函數。它幾乎只是工作。
  3. 然後將它傳遞給客戶端(Air app)
    空中應用程序是否通過http請求調用此php腳本?如果是的話,設置內容類型並輸出密鑰。
  4. 解密數據 回到第1點可能,但是您是否需要鑰匙,並且您是否在意格式是否更改。另外,你不想解密AS3應用程序中的數據嗎?
  5. 顯示在應用程序中。 如果AS3應用程序要顯示密鑰或解密的數據,那麼它是AS3,您需要讓它顯示數據。
+0

謝謝Justin。 1.我需要傳遞電子郵件地址([email protected]),當前日期,一對隨機數(檢查應用程序 - 這是對密鑰有效性的最簡單測試)2.哦,不,我不需要這個功能。電子郵件我需要將它保存在數據庫中。這就是我所知道的並且可以做到的。例如,我可以使用PHP和AS3 - base64和MD5。 5.例如顯示電子郵件 – Astraport

1

如果您只是想使用上面使用的符號集(0-9A-Z)「存儲」一些信息,那麼可以使用下面的算法。代碼是我的一箇舊的Python(3)程序。這絕對不是什麼花哨的東西,也沒有很好的測試,但是我認爲這比沒有好,因爲你還沒有很多答案。將代碼移植到PHP或AS應該很容易。例如,可以用命令式樣式循環代替reduce語句。另請注意,//表示Python中的整數除法。

它也應該很容易掌握一些壓縮/加密到它。希望它類似於你想要的。開始。

from functools import reduce 

class Coder: 
    def __init__(self, alphabet=None, groups=4): 
     if not alphabet: 
      alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 
     self.alphabet = alphabet 
     self.groups = groups 

    def encode(self, txt): 
     N = len(self.alphabet) 
     num = reduce(lambda x,y: (x*256)+y, map(ord, txt)) 

     # encode to alphabet 
     a = [] 
     while num > 0: 
      i = num % N 
      a.append(self.alphabet[i]) 
      num -= i 
      num = num//N 

     c = "".join(a) 
     if self.groups > 0: 
      # right zero pad 
      while len(c) % self.groups != 0: 
       c = c + self.alphabet[0] 
      # make groups 
      return '-'.join([c[x*self.groups:(x+1)*self.groups] 
          for x in range(len(c)//self.groups)]) 
     return c 

    def decode(self, txt, separator='-'): 
     # remove padding zeros and separators 
     x = txt.rstrip(self.alphabet[0]) 
     if separator != None: 
      x = x.replace(separator, '') 
     N = len(self.alphabet) 
     x = [self.alphabet.find(c) for c in x] 
     x.reverse() 
     num = reduce(lambda x,y: (x*N)+y, x) 

     a = [] 
     while num > 0: 
      i = num % 256 
      a.append(i) 
      num -= i 
      num = num//256 
     a.reverse() 
     return ''.join(map(chr, a)) 

if __name__ == "__main__": 
    k = Coder() 
    s = "Hello world!" 
    e = k.encode(s) 
    print("Encoded:", e) 
    d = k.decode(e) 
    print("Decoded:", d) 

輸出示例:

Encoded: D1RD-YU0C-5NVG-5XL8-7620 
Decoded: Hello world! 
1

與MD5,你不能這樣做,因爲這是一個單向散列。您應該使用解密方法來執行此操作,因爲它使用密鑰對其進行編碼和解碼。有幾個PHP擴展可以做到這一點,請參閱PHP手冊。您也可以使用第三方軟件,例如http://wwww.phplicengine.com