中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
关于使用crytoFramework库中的RSA用私钥加密或者公钥解密会报错。https://developer.huawei.com/consumer/cn/forum/topic/0202138475424398205
微信扫码分享
import { cryptoFramework } from '@kit.CryptoArchitectureKit'; import { buffer, util } from '@kit.ArkTS'; @Entry @Component struct RSAReverseCrypto { @State message: string = '点击开始'; build() { Row() { Column() { Text(this.message) .fontSize(50) .fontWeight(FontWeight.Bold) .onClick(() => { RsaReverse() }) } .width('100%') } .height('100%') } } // 字符串转成字节流 export function stringToUint8Array(str: string) { return new Uint8Array(buffer.from(str,'utf-8').buffer); } // Uint8Array转成String function uint8ArrayToString(input: Uint8Array): string { let textDecoder = util.TextDecoder.create('utf-8'); return textDecoder.decodeWithStream(input); } // 公钥解密 function verifyMessage(pubKey: cryptoFramework.PubKey,signMessageBlob: cryptoFramework.DataBlob) { let verifyAlg = "RSA2048|PKCS1|NoHash|Recover"; let verifier = cryptoFramework.createVerify(verifyAlg); verifier.initSync(pubKey); let rawSignData = verifier.recoverSync(signMessageBlob); console.log("rsa puk data " + uint8ArrayToString(rawSignData?.data)) return rawSignData; } //私钥加密 function signMessage(priKey: cryptoFramework.PriKey, plainText:cryptoFramework.DataBlob) { let signAlg = "RSA2048|PKCS1|NoHash|OnlySign"; let signer = cryptoFramework.createSign(signAlg); signer.initSync(priKey); let signData = signer.signSync({data:plainText.data}); return signData; } // 密钥转换 function genKeyPairByData(pubKeyData: Uint8Array, priKeyData: Uint8Array) { let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; let priKeyBlob: cryptoFramework.DataBlob = { data: priKeyData }; let rsaGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); let keyPair = rsaGenerator.convertKeySync(pubKeyBlob, priKeyBlob); console.info('convertKey success'); return keyPair; } //Rsa 加解密 function RsaReverse() { let pkData = "公钥"; let skData = "私钥"; let base64 = new util.Base64Helper(); let pubKeyBlob = base64.decodeSync(pkData) let priKeyBlob = base64.decodeSync(skData); let keyPair = genKeyPairByData(pubKeyBlob, priKeyBlob); let pubKey = keyPair.pubKey let priKey = keyPair.priKey let message = "This is a test"; let plainText: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, 'utf-8').buffer) }; let encryptText = signMessage(priKey, plainText); let decryptText = verifyMessage(pubKey, encryptText); console.info('decrypt plainText: ' + buffer.from(decryptText!.data).toString('utf-8')); }