0

我正在使用 Windows Live Id 服务为我的应用程序进行日志记录和身份验证。用户通过身份验证后,我在 Windows Live Id 服务发送的响应中获得了一个令牌。我希望解码此令牌以便从中获取唯一标识符。这是更好地解释这一点的链接:http: //msdn.microsoft.com/en-us/library/bb676622.aspx

当我尝试创建 CryptoStream 对象时,我在 Visual Studio 中调试时看到异常,尽管代码没有中断。

但是当我尝试将流转换为字节时,它会引发错误并且代码会中断。

它说:

“要解密的数据长度无效”

这是我正在使用的代码:

     string token="";                     //Token Sent by the service
     string SecretKey = "";              //SecretKey Obtained while registering my application
     byte[] cryptKey = derive(secretKey, "ENCRYPTION");  


    static byte[] derive(string secret, string prefix)
      {
         using(HashAlgorithm hashAlg = HashAlgorithm.Create("SHA256"))
         { 
          const int keyLength = 16;
          byte[] data = Encoding.Default.GetBytes(prefix+secret);
          byte[] hashOutput = hashAlg.ComputeHash(data);
          byte[] byteKey = new byte[keyLength];
          Array.Copy(hashOutput, byteKey, keyLength);
          return byteKey;
         }
      }

    const int ivLength = 16;
    token = HttpUtility.UrlDecode(token);
    byte[] ivAndEncryptedValue = Convert.FromBase64String(token);
    aesAlg = new RijndaelManaged();
    aesAlg.KeySize = 128;
    aesAlg.Key = cryptKey;
    aesAlg.Padding = PaddingMode.PKCS7;
    memStream = new MemoryStream(ivAndEncryptedValue);
    byte[] iv = new byte[ivLength];
    memStream.Read(iv, 0, ivLength);
    aesAlg.IV = iv; 
    cStream = new CryptoStream(memStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Read);
    sReader = new StreamReader(cStream, Encoding.ASCII);

下一行代码抛出错误:“要解密的数据长度无效”

    decodedValue = sReader.ReadToEnd();    //Throws error:"Length of the data to decrypt is invalid"

有谁知道这背后的原因是什么?

任何形式的帮助或指导将不胜感激。

先感谢您。

问候,

阿布舍克

4

1 回答 1

1

这是我目前在解密值时使用的示例,希望这将帮助您了解您在现有代码中做错了什么

static string Decrypt() 
    {            
      byte[] keyBytes = Convert.FromBase64String("U6XksFkhWV4.......eo3fRg=="");
      byte[] iv = Convert.FromBase64String("KLnP....wA=="");
      byte[] cipherTextBytes = Convert.FromBase64String("Put the EncryptedText here");

      var symmetricKey = new RijndaelManaged { Mode = CipherMode.CBC, IV = iv, KeySize = 128, Key = keyBytes, Padding = PaddingMode.Zeros};

      using (var decryptor = symmetricKey.CreateDecryptor())
      using (var ms = new MemoryStream(cipherTextBytes))
      using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) {
        var plainTextBytes = new byte[cipherTextBytes.Length];
        int decryptedByteCount = cs.Read(plainTextBytes, 0, plainTextBytes.Length);
        return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
      }
    }
于 2012-11-14T19:01:30.017 回答