第一方案为
window.crypto.subtle.generateKey
但是某些情况下,在http链接无法获取 window.crypto.subtle对象,只能在https请求和localHost的时候能够获取到window.crypto.subtle对象。
为了解决任何时候都能生成密钥对,因此我选择了node-rsa来生成。
第二方案:使用node-rsa 库。
使用:
public static CreateAesAPair(func: Function) {
try {
const key = new NodeRSA({ b: 512 }); //生成512, 1024, 2048位的密钥
var publicDer = key.exportKey("pkcs8-public-pem"); //公钥
var privateDer = key.exportKey('pkcs8-private-pem');//私钥
// 'pkcs1' — public key starts from '-----BEGIN RSA PUBLIC KEY-----' header and private key starts from '-----BEGIN RSA PRIVATE KEY-----' header
// 'pkcs8' — public key starts from '-----BEGIN PUBLIC KEY-----' header and private key starts from '-----BEGIN PRIVATE KEY-----' header
// 'pem'— 带有页眉和页脚的 Base64 编码字符串。默认使用。
// 'der' — 二进制编码的密钥数据。
return func(privateDer, publicDer);
} catch(e) {
console.error("------e: ", e);
return func(null, null);
}
}
生成密钥如下所示:
this.model.privateKey =
"-----BEGIN PRIVATE KEY-----" +
'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIXawhnxuqzgnwam' +
'IHZ94tpqTsQtmWIUIVidPCkRN+vJXk8k7o2dUDHSY5w0Ls6MeNUPDxW2ED90yrop' +
'YPhXTlT1caRaeINa4bOB6zaKymXNvpZdDbf+CR1dKWSAfTkUgKm+Pxi3EKRidP9D' +
'lLRkKQEgLdUMQmmbSDXW3bmfWjiJAgMBAAECgYEAg/o/q6kGMHKBGeMu2uYgiM6M' +
'vy1esK+8eUz/Blbt1lQD4vE9LPBRI+6XPGrPQ+SJNznT28pZltenE4q9C9+5YOM3' +
'9Z+UU2tpAKaymOR8L/3VTeFrfd2iRi+gM7TWpXeM7jdEUfyY3dAQVDjZkHSrBnKC' +
'n51u9YA4fI/DyiI1XAECQQDhjo+nastsDCu6c9Hcj4KAtt39+mou/Hz4ZnTP5Avc' +
'8K5nERTy1LoyML+VUYu7hSFH5V2BNsOHSMCYmVuXl9zBAkEAl+uywk53HKdqWj57' +
'ATNVvWFN5o2/mfosZuxMrwcxbHM8fp7pWppGJRYDmaNqhppWiFrHFDLl46QQu5dr' +
'9bYlyQJBALpoaUyBNBDdlh4Hrf7ME5xwhNJra+nc/SME+bD91NgJiPjg4yE0sZTd' +
'ONgchpC5G6Ihar9pFPrvI0x6IXoNJYECQBGFvwWIVVa5vJuSD0/xIteIDJsmCE5z' +
'O4HXiXS6qKmwlO6p15J6rtKCOoITBitmS8rIZaPfxwI9nyxz56DclHkCQEH04rGr' +
'qeIBSDAzuJt7+KhplTSeHsuTZfkw0RZBx6+rrEn9wsEuj9rB+j78LPU1665VNF5z' +
'jZIkl4lnJi0Ij6k=' +
"-----END PRIVATE KEY-----";
this.model.publicKey =
'-----BEGIN PUBLIC KEY-----' +
'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCF2sIZ8bqs4J8GpiB2feLaak7E' +
'LZliFCFYnTwpETfryV5PJO6NnVAx0mOcNC7OjHjVDw8VthA/dMq6KWD4V05U9XGk' +
'WniDWuGzges2isplzb6WXQ23/gkdXSlkgH05FICpvj8YtxCkYnT/Q5S0ZCkBIC3V' +
'DEJpm0g11t25n1o4iQIDAQAB' +
'-----END PUBLIC KEY-----';