Rom*_*tec 6 javascript encryption rsa typescript angular
我正在使用 Angular 4 来制作我的应用程序的前端。我已经在我的后端实现了 OAuth2(用 Java 中的 Spring 开发),所以使用我的应用程序的人必须经过身份验证。
问题是我们可以清楚地看到后端服务器日志中的密码,并且在我添加 SSL 之前,它可能会被 MITM 捕获。
这就是为什么我决定用 RSA 加密发送的密码。我的后端已经准备好了,但我没有找到任何最新的库来提供一个不错的 API 来从 RSA 密钥对加密/解密。
也看到了crypto模块,但在 ECMAS6 上不再可用。在crypto-js一个仅提供AES和一些散列诸如MD5 / SHA。
终于找到办法了,装了一些之后。
npm install buffer
npm install crypto-browserify
Run Code Online (Sandbox Code Playgroud)
然后使用它
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')
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21298 次 |
| 最近记录: |