将字节数组转换为CryptographicKey

时间:2016-05-13 00:32:25

标签: encryption unity3d win-universal-app

背景

我正在为Windows Store Universal 10构建我的Unity应用程序。它已经适用于Android和iOS以及WP8。

我的应用将加密的会话数据发送回服务器进行处理。目前它正在使用AesManaged()库,如下所示:

        using (var memoryStream = new MemoryStream())
        {
            Aes aes = new AesManaged();
            aes.BlockSize = 128;
            aes.KeySize = 256;
            aes.Key = keyBytes;
...
            using (CryptoStream cs = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cs.Write(plainTextBytes, 0, plainTextBytes.Length);
                cs.FlushFinalBlock();
                byte[] cipherTextBytes = memoryStream.ToArray();
                cs.Close();
                return cipherTextBytes;
            }
        }

我使用的密钥用于Aes.Key是一个自定义方法,它返回一个byte []:

 public static byte[] getKeyBytes(string pApiKey, string pSecret)

根据几篇文章,

https://social.msdn.microsoft.com/Forums/windowsapps/en-US/52080335-0016-4370-889b-3afe0c0dcb7a/how-to-do-simple-aes-encryptiondecryption-in-metro

http://forum.unity3d.com/threads/aesmanaged-wp8-1-the-type-or-namespace-name-aesmanaged-could-not-be-found.376732/

我的Unity Build错误,AesManaged库在定位Windows应用商店时无效,我需要使用更新的加密库(Windows.Security.Cryptography.Core):

https://msdn.microsoft.com/en-us/library/windows/apps/windows.security.cryptography.core.symmetrickeyalgorithmprovider.aspx

这似乎很简单,除了新的加密方法:

 CryptographicEngine.Encrypt(key, buffMsg, iv);

将CryptographicKey对象作为参数而不是byte [](我的密钥当前是)

问题:

如何将一个byte []转换为CryptographicKey对象,以便我可以将新的必需加密方法与现有密钥一起使用?

当我尝试:

CryptographicKey key = new CryptographicKey(pKeyByteArray);

我明白了:

error CS1729: 'CryptographicKey' does not contain a constructor that takes 1 arguments

注意:System.Web.Security.Cryptography中似乎有一个CryptographicKey执行此操作:

http://referencesource.microsoft.com/#System.Web/Security/Cryptography/CryptographicKey.cs,58f5cc896110a437,references

但这似乎不适用于Windows应用商店版本。

1 个答案:

答案 0 :(得分:0)

我无法测试下面的代码,但我修改了它以使用你的字节数组。

    byte[] pKeyByteArray;
    uint keyLength = 512; //512, 1024, 2048, or 4096 bits
    pKeyByteArray = new byte[50];

    string strAsymmetricAlgName = System.Text.Encoding.UTF8.GetString(pKeyByteArray);
    AsymmetricKeyAlgorithmProvider objAlgProv = AsymmetricKeyAlgorithmProvider.OpenAlgorithm(strAsymmetricAlgName);
    CryptographicKey keyPair = objAlgProv.CreateKeyPair(keyLength);

    // Export the public key to a buffer for use by others.
    IBuffer buffPublicKey = keyPair.ExportPublicKey();


    CryptographicKeyApp.buffKeyPair = keyPair.Export();

    // Retrieve the size of the key pair.
    UInt32 lengthKeyPair = keyPair.KeySize;

    // Do something with your the public key.
   buffPublicKey........