如何在.net中生成AES256密钥

时间:2018-07-18 13:34:45

标签: java .net key-generator

我有生成密钥AES256位密钥的Java代码,必须在.Net中实现相同的代码

这是我的示例Java

int SYMMETRIC_KEY_SIZE = 256;
public byte[] generateSessionKey() 
{
        //      KeyGenerator kgen = KeyGenerator.getInstance("AES", JCE_PROVIDER);
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(this.SYMMETRIC_KEY_SIZE);
        SecretKey key = kgen.generateKey();
        byte[] symmKey = key.getEncoded();
        return symmKey;
    }

下面是我的.net代码

public static string GenerateKey(int iKeySize)
        {
            RijndaelManaged aesEncryption = new RijndaelManaged();
            aesEncryption.KeySize = iKeySize;
            aesEncryption.BlockSize = 128;
            aesEncryption.Mode = CipherMode.CBC;
            aesEncryption.Padding = PaddingMode.PKCS7;
            aesEncryption.GenerateIV();
            string ivStr = Convert.ToBase64String(aesEncryption.IV);
            aesEncryption.GenerateKey();
            string keyStr = Convert.ToBase64String(aesEncryption.Key);
            string completeKey = ivStr + "," + keyStr;

            return Convert.ToBase64String(ASCIIEncoding.UTF8.GetBytes(completeKey));
        }

上面的代码生成密钥是“ MnRpUVZmT3p5bG94R1RHYklMYU5Qdz09LDRZTUVQVlZWMHd0T2k3VGxEci9pejlBT3QvY215TFVNcFZ5ei93YnFuZk09”

我从上面的代码中获取密钥AES256密钥,我不得不将其转换为字节并在下面的函数中传递“ skey”参数,但是在执行gcmb.Init(cipherOperation,ObjAeadParameters)时,我得到了错误“无效”参数传递给GCM”。

GCM块密码加密

public byte[] EncryptWithSessionKey(bool cipherOperation, byte[] skey, byte[] iv, byte[] aad, byte[] data)
            {
                try
                {
                    AeadParameters ObjAeadParameters = new AeadParameters(new Org.BouncyCastle.Crypto.Parameters.KeyParameter(skey), AUTH_TAG_SIZE_BITS, iv,aad );
                    GcmBlockCipher gcmb = new GcmBlockCipher(new AesFastEngine());
                    gcmb.Init(cipherOperation, ObjAeadParameters);
                    byte[] result = new byte[gcmb.GetOutputSize(data.Length)];
                    int processLen = gcmb.ProcessBytes(data, 0, data.Length, result, 0);
                    gcmb.DoFinal(result, processLen);
                    return result;
                }
                catch (Exception ex)
                {
                    lobjlog.LogWrite("EncryptWithSessionKey Exception" + ex.InnerException.Message);
                    throw ex;
                }


            }

0 个答案:

没有答案