首页 > 解决方案 > 如何在 .net 中生成 AES256 密钥

问题描述

我有生成密钥 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;
                }


            }

标签: java.netkey-generator

解决方案


推荐阅读