使用 AES GCM 从 Angular 到 C# 进行加密和解密

问题描述 投票:0回答:0

如何在C#中实现与我现有的Angular加密和解密方法兼容的加密和解密方法?目前,我在 Angular 中有两种方法用于加密和解密,但我还需要能够在后端使用 C# 执行这些操作。这是我的 Angular 方法:

 async encryptStringAES256(key: string, xSalt: string, data: string): Promise<any> {
    return new Promise((resolve, reject) => {
      const salt = new Uint8Array(this.toUin8Arry(xSalt));
      const decryptedData = new Uint8Array(this.stringToArray(data));
      this.getKeyMaterial(key).then( async (res: any) => {
        const xkey = await window.crypto.subtle.deriveKey(
          {
            name: 'PBKDF2',
            iterations: 100000,
            salt,
            hash: 'SHA-256'
          },
          res,
          { name: 'AES-GCM', length: 256},
          true,
          ['encrypt', 'decrypt']
        );
        window.crypto.subtle.encrypt({ name: 'AES-GCM', iv: salt }, xkey, decryptedData).then(
          encrypted => {
            resolve(this.arrayToString(new Uint8Array(encrypted)));
          })
        .catch(err => {
           // catch
        });
      });
    });
  }

  async decryptStringAES256(key: string, xSalt: string, data: string): Promise<any> {
      const salt = new Uint8Array(this.toUin8Arry(xSalt));
      const encryptedData = new Uint8Array(this.stringToArray(data));
      this.getKeyMaterial(key).then( async (res: any) => {
        const xkey = await window.crypto.subtle.deriveKey(
          {
            name: 'PBKDF2',
            iterations: 100000,
            salt,
            hash: 'SHA-256'
          },
          res,
          { name: 'AES-GCM', length: 256},
          true,
          ['encrypt', 'decrypt']
        );
        window.crypto.subtle.decrypt({ name: 'AES-GCM', iv: salt }, xkey, encryptedData).then(
          decrypted => {
            const dec = this.arrayToString(new Uint8Array(decrypted));
            resolve(dec);
          })
          .catch(err => {
            reject(data);
          });
      });
    });
  }

  getKeyMaterial(password: string): any {
    const enc = new TextEncoder();
    return window.crypto.subtle.importKey(
      'raw',
      enc.encode(password),
      'PBKDF2',
      false,
      ['deriveBits', 'deriveKey']
    );
  }

c#:

    public static void Decrypt(byte[] sourceData, string password)
    {
        try
        {
            var encryptedData = sourceData.AsSpan();
            var key = Convert.FromBase64String(password).AsSpan();
            var ivSizeBytes = 10;
            var tagSizeBytes = 0; 

            var cipherSize = encryptedData.Length - tagSizeBytes - ivSizeBytes;

            var iv = encryptedData.Slice(0, ivSizeBytes);

            var cipherBytes = encryptedData.Slice(ivSizeBytes, cipherSize);

            var tagStart = ivSizeBytes + cipherSize;
            var tag = encryptedData.Slice(tagStart);

            using Rfc2898DeriveBytes pbkdf2 = new(Encoding.UTF8.GetBytes(password), iv.ToArray(), 100000, HashAlgorithmName.SHA256); 

            Span<byte> plainBytes = cipherSize < 1024
                ? stackalloc byte[cipherSize]
                : new byte[cipherSize];
            using var aes = new AesGcm(pbkdf2.GetBytes(32));
            aes.Decrypt(iv, cipherBytes, tag, plainBytes);

            var x = Encoding.UTF8.GetString(plainBytes);
        }
        catch (Exception e)
        {
            throw new Exception($"Fehler Decrypt: {e.Message}");
        }
    }
c# .net angular cryptography aes
© www.soinside.com 2019 - 2024. All rights reserved.