gpt4 book ai didi

javascript - TypeScript 中的 RSA 加密/解密

转载 作者:太空狗 更新时间:2023-10-29 18:02:48 76 4
gpt4 key购买 nike

我正在使用 Angular 4 制作我的应用程序的前端。我在后端实现了 OAuth2(使用 Java 中的 Spring 开发),因此使用我的应用程序的人必须经过身份验证。

问题是我们可以从后端服务器日志中清楚地看到密码,并且在我添加 SSL 之前它可能会被 MITM 捕获。

这就是为什么我决定用 RSA 加密发送的密码。我的后端已经准备就绪,但我没有找到任何最新的库提供用于从 RSA key 对加密/解密的合适 API。

还看到了 crypto 模块,但在 ECMAS6 上不再可用。 crypto-js 仅提供 AES 和一些哈希算法,例如 MD5/SHA。

最佳答案

终于找到办法了,安装了一些。

npm install buffer
npm install crypto-browserify

然后使用它

import {config} from "../app.config";
import {Buffer} from 'buffer/';
import * as crypto from "crypto-browserify";

export class RsaService {
private privateKey: string;
private publicKey: string;
private enabled: boolean;

constructor() {
this.privateKey = config.authentication.rsa.privateKey;
this.publicKey = config.authentication.rsa.publicKey;
this.enabled = config.authentication.rsa.enabled;
}

isEnabled(): boolean {
return this.enabled;
}

encrypt(plaintext: string): string {
if (!this.enabled)
return plaintext;

let buffer = new Buffer(plaintext);
let encrypted = crypto.privateEncrypt(this.privateKey, buffer);

return encrypted.toString('base64');
}

decrypt(cypher: string): string {
if (!this.enabled)
return cypher;

let buffer = Buffer.from(cypher, 'base64');
let plaintext = crypto.publicDecrypt(this.publicKey, buffer);

return plaintext.toString('utf8')
}
}

关于javascript - TypeScript 中的 RSA 加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46642143/

76 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com