You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular与ASP.NET Core MVC中实现相同的加解密逻辑?

实现方法与替代方案

一、前端实现与C#一致的加密逻辑

首先要明确C#中使用的加解密算法类型(对称加密如AES、DES;非对称加密如RSA等),以及对应的密钥、加密模式、填充规则、编码方式,再在Angular中用对应逻辑实现:

1. 对称加密(以AES CBC模式为例)

假设C#端用AES CBC模式,密钥和IV与前端约定一致,可借助crypto-js库实现:

  • 安装依赖:npm install crypto-js --save
  • 编写加密函数:
import * as CryptoJS from 'crypto-js';

// 与C#端完全一致的密钥、IV,注意编码匹配(如UTF8)
const AES_KEY = CryptoJS.enc.Utf8.parse('你的C#密钥');
const AES_IV = CryptoJS.enc.Utf8.parse('你的C#IV');

encryptUsername(username: string): string {
    const encrypted = CryptoJS.AES.encrypt(
        CryptoJS.enc.Utf8.parse(username),
        AES_KEY,
        { iv: AES_IV, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
    );
    // 转Base64字符串方便URL传递
    return encrypted.toString();
}
  • 修改API调用代码:
callExternalProject(Username : string): Observable<any> {
    const encryptedUsername = this.encryptUsername(Username);
    // 用encodeURIComponent处理加密串,避免URL转义异常
    return this.http.get<any>(`${environment.CMRDashboardURL}/Account/LoginUser?username=${encodeURIComponent(encryptedUsername)}`)
        .pipe(
            catchError(error => throwError(() => new Error(error)))
        );
}

注意:必须保证C#与前端的密钥、IV、加密模式、填充方式、编码完全匹配,否则后端解密会失败。

2. 非对称加密(以RSA为例)

如果C#端用RSA加密,前端可借助jsrsasign库用后端提供的公钥加密:

  • 安装依赖:npm install jsrsasign --save
  • 编写加密函数:
import { RSAKey } from 'jsrsasign';

encryptUsername(username: string): string {
    const publicKey = '-----BEGIN PUBLIC KEY-----你的C#公钥内容-----END PUBLIC KEY-----';
    const rsa = new RSAKey();
    rsa.readPublicKeyFromPEMString(publicKey);
    // 加密后转Base64
    return rsa.encrypt(username, 'utf8', 'base64');
}
  • 同样将加密后的字符串传入API的URL参数中即可。

二、替代方案

1. 改用POST请求传递加密数据

GET请求的URL参数有长度限制,且加密串暴露在URL中,改用POST更安全:

callExternalProject(Username : string): Observable<any> {
    const encryptedUsername = this.encryptUsername(Username);
    return this.http.post<any>(`${environment.CMRDashboardURL}/Account/LoginUser`, {
        username: encryptedUsername
    })
        .pipe(
            catchError(error => throwError(() => new Error(error)))
        );
}

后端对应修改为接收POST参数即可,同时避免URL转义问题。

2. 后端生成加密令牌替代前端加密

如果不想在前端实现加密逻辑,可让后端先生成包含用户名的加密令牌:

  • 前端先调用后端令牌接口:this.http.get('/api/generate-login-token')
  • 后端生成加密令牌(如JWT或自定义加密串)返回给前端
  • 前端携带令牌调用登录接口:this.http.get(${environment.CMRDashboardURL}/Account/LoginUser?token=${token})
  • 后端验证令牌并解析出用户名

3. 强制使用HTTPS

无论采用哪种方式,都必须确保API调用使用HTTPS,避免传输过程中数据被窃听,为加密内容再添一层传输安全保障。

内容的提问来源于stack exchange,提问作者Hasan Javed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 10:07:22