HarmonyOS 鸿蒙Next:RSA 安卓验签方式“SHA1WithRSA” 鸿蒙要如何改
HarmonyOS 鸿蒙Next:RSA 安卓验签方式“SHA1WithRSA” 鸿蒙要如何改
//安卓代码
public boolean verifyWhole(String param,String signature,String keycode){
try {
//获取公钥
KeyFactory keyFactory=KeyFactory.getInstance(“RSA”);
byte[] keyByte=Base64.decode(keycode);
X509EncodedKeySpec encodeRule=new X509EncodedKeySpec(keyByte);
PublicKey publicKey= keyFactory.generatePublic(encodeRule);
//用获取到的公钥对 入参中未加签参数param 与 入参中的加签之后的参数signature 进行验签
Signature sign=Signature.getInstance(“SHA1WithRSA”);
sign.initVerify(publicKey);
sign.update(param.getBytes());
//将16进制码转成字符数组
byte[] hexByte=Hex.hexStringToBytes(signature);
//验证签名
return sign.verify(hexByte);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Base64DecodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeySpecException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SignatureException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
验签可以过
以下是我的
import { cryptoFramework } from ‘@kit.CryptoArchitectureKit’;
import { StrUtil } from ‘@pura/harmony-utils/src/main/ets/utils/StrUtil’;
import { Base64Util } from ‘@pura/harmony-utils/src/main/ets/utils/Base64Util’;
export class RsaUtil {
hexStr2Uint8Array(str: string): Uint8Array {
let arr = new Uint8Array(str.length / 2);
let index = 0;
for (let i = 0; i < str.length; i += 2) {
let tmp: string = str.slice(i, i + 2);
let result = Number.parseInt(“0x” + tmp);
arr[index++] = result
}
return arr;
}
async rsaVerify(content: string, signature: string,
menuPublicKey: string): Promise<boolean> {
let pkData = Base64Util.decodeSync(menuPublicKey)
let pubKey = await this.genRSAPubKey(pkData);
let signatureBlob: cryptoFramework.DataBlob = {
data: this.hexStr2Uint8Array(signature)
};
let verifier = cryptoFramework.createVerify(‘RSA1024|PKCS1|SHA256’);
await verifier.init(pubKey);
let inputVerify: cryptoFramework.DataBlob = { data: StrUtil.strToUint8Array(content, ‘utf-8’) };
return verifier.verify(inputVerify, signatureBlob);
}
async genRSAPubKey(pubKeyData: Uint8Array): Promise<cryptoFramework.PubKey> {
let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData };
let rsaGenerator = cryptoFramework.createAsyKeyGenerator(‘RSA1024’);
let KeyPair = await rsaGenerator.convertKey(pubKeyBlob, null);
return KeyPair.pubKey;
}
}
验签验不过,对应安卓的 Signature sign=Signature.getInstance(“SHA1WithRSA”) 的"SHA1WithRSA"是"SHA256WithRSA" 方式我的也可以过。
现在对应“SHA1WithRSA” 不知道怎么改
关于HarmonyOS 鸿蒙Next:RSA 安卓验签方式“SHA1WithRSA” 鸿蒙要如何改的问题,您也可以访问:https://www.itying.com/category-93-b0.html 联系官网客服。
HarmonyOS的流畅动画和过渡效果让操作更加顺畅,体验极佳。
cryptoFramework.createVerify('RSA1024|PKCS1|SHA256'),改成
cryptoFramework.createVerify('RSA1024|PKCS1|SHA1')就可以了
import { cryptoFramework } from ‘@kit.CryptoArchitectureKit’; import { Base64Util, StrUtil } from ‘@pura/harmony-utils’; import Venus from “…/…/…/…/Index” import { BusinessError } from ‘@kit.BasicServicesKit’;
export class CryptoUtil { static uint8ArrayToHexStr(data: Uint8Array): string { let hexString = “”; let i: number; for (i = 0; i < data.length; i++) { let char = (‘00’ + data[i].toString(16)).slice(-2); hexString += char; } return hexString; }
static hexStr2Uint8Array(str: string): Uint8Array { let arr = new Uint8Array(str.length / 2); let index = 0; for (let i = 0; i < str.length; i += 2) { let tmp: string = str.slice(i, i + 2); let result = Number.parseInt(“0x” + tmp); arr[index++] = result } return arr; }
// RSA 开始 static async rsaVerifyWithUint8Array(content: string, signatureUint8Array: Uint8Array, menuPublicKey: string = Venus.instance.env.menuPublicKey, algName: string = “RSA1024|PKCS1|SHA256”): Promise<boolean> { // 该数据取自Sign中的signData.data let signMessageBlob: cryptoFramework.DataBlob = { data: signatureUint8Array }; return CryptoUtil.rsaVerify(content, signMessageBlob, menuPublicKey, algName) }
static async rsaVerify(content: string, signatureBlob: cryptoFramework.DataBlob, menuPublicKey: string = Venus.instance.env.menuPublicKey, algName: string = “RSA1024|PKCS1|SHA256”): Promise<boolean> { let pkData = Base64Util.decodeSync(menuPublicKey) let pubKey = CryptoUtil.genRSAPubKey(pkData); let verifier = cryptoFramework.createVerify(algName); await verifier.init(pubKey);
let textSplitLen = 300; // 自定义的数据拆分长度
for (let i = 0; i < content.length; i += textSplitLen) {
let updateMessage: string = content.substring(i, i + textSplitLen);
let updateMessageBlob: cryptoFramework.DataBlob = { data: StrUtil.strToUint8Array(updateMessage, 'utf-8') };
// 分段update
await verifier.update(updateMessageBlob);
}
return verifier.verify(null, signatureBlob);
}
static genRSAPubKey(pubKeyData: Uint8Array): cryptoFramework.PubKey { let pubKeyBlob: cryptoFramework.DataBlob = { data: pubKeyData }; let rsaGenerator = cryptoFramework.createAsyKeyGenerator(‘RSA1024’); let KeyPair = rsaGenerator.convertKeySync(pubKeyBlob, null); return KeyPair.pubKey; }
// RSA 结束
// AES128 开始 static genIvParamsSpec(ivStr?: string): cryptoFramework.IvParamsSpec { let arr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; // 16 bytes let dataIv = new Uint8Array(arr); if (StrUtil.isNotNull(ivStr)) { dataIv = StrUtil.strToUint8Array(ivStr) } let ivBlob: cryptoFramework.DataBlob = { data: dataIv } let ivParamsSpec: cryptoFramework.IvParamsSpec = { algName: “IvParamsSpec”, iv: ivBlob }; return ivParamsSpec; }
static genSymKeyByData(symKeyData: Uint8Array): Promise<cryptoFramework.SymKey> { let symKeyBlob: cryptoFramework.DataBlob = { data: symKeyData }; let aesGenerator = cryptoFramework.createSymKeyGenerator(‘AES128’); return aesGenerator.convertKey(symKeyBlob);
}
static async aecEncrypt(symStr: string, plainText: string, ivStr?: string): Promise<cryptoFramework.DataBlob> { let plainDataBlob: cryptoFramework.DataBlob = { data: StrUtil.strToUint8Array(plainText) }; let symKey = await CryptoUtil.genSymKeyByData(StrUtil.strToUint8Array(symStr)); let cipher = cryptoFramework.createCipher(‘AES128|CBC|PKCS7’); let iv = CryptoUtil.genIvParamsSpec(ivStr); await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, iv); return cipher.doFinal(plainDataBlob);
}
static async aecDecrypt(symStr: string, decryptUint8Array: Uint8Array, ivStr?: string): Promise<string> { let str = “”; let decryptDataBlob: cryptoFramework.DataBlob = { data: decryptUint8Array }; let symKey = await CryptoUtil.genSymKeyByData(StrUtil.strToUint8Array(symStr)); let decoder = cryptoFramework.createCipher(‘AES128|CBC|PKCS7’); let iv = CryptoUtil.genIvParamsSpec(ivStr); await decoder.init(cryptoFramework.CryptoMode.DECRYPT_MODE, symKey, iv); let decryptData = await decoder.doFinal(decryptDataBlob); if (decryptData) { str = StrUtil.unit8ArrayToStr(decryptData.data) } return Promise.resolve(str); }
// AES128 结束
// MD 摘要开始
static doLoopMdBySync(messageText: string, callback: Function, mdAlgName: string = “SHA256”) { let md = cryptoFramework.createMd(mdAlgName); let messageData = StrUtil.strToUint8Array(messageText, ‘utf-8’) let updateMessageBlob: cryptoFramework.DataBlob = { data: messageData }; md.update(updateMessageBlob).then(() => { md.digest().then((out) => { callback(CryptoUtil.uint8ArrayToHexStr(out.data)) }).catch((err: BusinessError) => { console.error(" md.digest calculate file hash failed with error:" + err); }); }).catch((err: BusinessError) => { console.error(“md.update calculate file hash failed with error:” + err); callback("") });
}
static async doMd(messageData: Uint8Array, mdAlgName: string = “SHA256”): Promise<string> { let md = cryptoFramework.createMd(mdAlgName); let updateMessageBlob: cryptoFramework.DataBlob = { data: messageData }; await md.update(updateMessageBlob) let out = await md.digest(); return Promise.resolve(CryptoUtil.uint8ArrayToHexStr(out.data)) }
// MD 摘要结束
}
调用 const res = await CryptoUtil.rsaVerifyWithUint8Array(array[0], Base64Util.decodeSync(array[1])) if (!res) { ToastUtil.showToastShort(“签名验证失败”); return Promise.resolve(new Map) } else { return Promise.resolve(JSONUtil.jsonToMap(array[0])) }