此代码使用 Apple 的 CryptoKit 框架在 iOS 平台中使用带有 AES-GCM 的私钥和公钥生成消息字符串的加密和解密版本。
import CryptoKit
func generatePrivateKey() -> P256.KeyAgreement.PrivateKey {
let privateKey = P256.KeyAgreement.PrivateKey()
return privateKey
}
func exportPrivateKey(_ privateKey: P256.KeyAgreement.PrivateKey) -> String {
let rawPrivateKey = privateKey.rawRepresentation
let privateKeyBase64 = rawPrivateKey.base64EncodedString()
let percentEncodedPrivateKey = privateKeyBase64.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
return percentEncodedPrivateKey
}
func importPrivateKey(_ privateKey: String) throws -> Curve25519.KeyAgreement.PrivateKey {
let privateKeyBase64 = privateKey.removingPercentEncoding!
let rawPrivateKey = Data(base64Encoded: privateKeyBase64)!
return try Curve25519.KeyAgreement.PrivateKey(rawRepresentation: rawPrivateKey)
}
func deriveSymmetricKey(privateKey: P256.KeyAgreement.PrivateKey, publicKey: P256.KeyAgreement.PublicKey) throws -> SymmetricKey {
let sharedSecret = try privateKey.sharedSecretFromKeyAgreement(with: publicKey)
let symmetricKey = sharedSecret.hkdfDerivedSymmetricKey(
using: SHA256.self,
salt: "My Key Agreement Salt".data(using: .utf8)!,
sharedInfo: Data(),
outputByteCount: 32
)
return symmetricKey
}
func encrypt(text: String, symmetricKey: SymmetricKey) throws -> String {
let textData = text.data(using: .utf8)!
let encrypted = try AES.GCM.seal(textData, using: symmetricKey)
return encrypted.combined!.base64EncodedString()
}
func decrypt(text: String, symmetricKey: SymmetricKey) -> String {
do {
guard let data = Data(base64Encoded: text) else {
return "Could not decode text: \(text)"
}
let sealedBox = try AES.GCM.SealedBox(combined: data)
let decryptedData = try AES.GCM.open(sealedBox, using: symmetricKey)
guard let text = String(data: decryptedData, encoding: .utf8) else {
return "Could not decode data: \(decryptedData)"
}
return text
}
catch let error {
return "Error decrypting message: \(error.localizedDescription)"
}
}
我怎样才能在 Angular (10) 中做同样的事情?我写了一些代码,但不幸的是我没有从中获得任何成功。这是我在 Angular 中的相同代码。
import { Component } from '@angular/core';
import cryptokit from "cryptokit";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'MyEnc';
my_public_key = '';
other_public_key = '';
constructor() { }
async apps() {
const P256Password = "some long random string";
const P256Keys = await cryptokit.P256.generateKeys(P256Password);
console.log("P256 private key (encrypted)= " + P256Keys.privateKey);
console.log("P256 public key = " + P256Keys.publicKey);
}
}
我收到了这个错误
错误错误:未捕获(承诺):TypeError:crypto_1.generateKeyPair不是函数