HarmonyOS getPublicKey和Cipher的RSA_MODE可用哪个api替代

private String genEncryptKey(KeyStore store) throws Exception { 
  byte[] key = new byte[16]; //128 bits 
  new SecureRandom().nextBytes(key); 
  PublicKey publicKey; 
  if (Build.VERSION.SDK_INT >= 28) { 
    publicKey = store.getCertificate(KEY_ALIAS).getPublicKey(); 
  } else { 
    KeyStore.PrivateKeyEntry asymmetricKey = (KeyStore.PrivateKeyEntry) store.getEntry(KEY_ALIAS, null); 
    publicKey = asymmetricKey.getCertificate().getPublicKey(); 
  } 
  Cipher cipher = Cipher.getInstance(RSA_MODE); 
  cipher.init(Cipher.ENCRYPT_MODE, publicKey); 
  return StringUtils.base64String(cipher.doFinal(key)); 
}

前面代码是生成公私钥并保存,下面是使用的地方获取到私钥

PrivateKey privateKey; 
if (Build.VERSION.SDK_INT >= 28) { 
  privateKey = (PrivateKey) store.getKey(KEY_ALIAS, null); 
} else { 
  KeyStore.PrivateKeyEntry asymmetricKey = (KeyStore.PrivateKeyEntry) store.getEntry(KEY_ALIAS, null); 
  privateKey = asymmetricKey.getPrivateKey(); 
}
HarmonyOS
2024-08-13 14:56:20
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

可参考https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/crypto-convert-binary-data-to-asym-key-pair-V5

以下方法来实现

async genRsaPubKey () { 
  const pubKey = "asdasd123231dsasdasd123123asdasd12312xxxxxxxxxxxxxxxxxxxxxxxxxxxx"; 
  /* 
  * 引入外部的公钥加密 
  * */ 
  const base64 = new util.Base64Helper() 
  let publicKeyDataBlob: cryptoFramework.DataBlob = { data: base64.decodeSync(pubKey) }; 
  let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator('RSA1024'); 
  let cipher = cryptoFramework.createCipher('RSA|ECB|PKCS1'); //创建一个 Cipher (解密)对象 
  let keyGenPromise: cryptoFramework.KeyPair = await asyKeyGenerator.convertKey(publicKeyDataBlob, null); 
  await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyGenPromise.pubKey, null); 
  const plaintext = '我是明文' 
  let put: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(plaintext).buffer) }; 
  const finalRes = await cipher.doFinal(put) 
  console.log(TAG, `加密成功 ${finalRes.data}`) 
}
分享
微博
QQ
微信
回复
2024-08-13 21:40:37
相关问题
HarmonyOS消息订阅该使用哪个api
297浏览 • 1回复 待解决
HarmonyOS获取公共下载目录api可用
351浏览 • 1回复 待解决
安卓IBinder在鸿蒙使用什么API替代
5527浏览 • 1回复 待解决
java对象hashcode方法有替代api或者库吗
881浏览 • 1回复 待解决
ImageReader 在HarmonyOS替代方案
1530浏览 • 1回复 待解决
调用其他用户程序要使用哪个 API
1906浏览 • 1回复 待解决
HarmonyOS RSA加密方式
485浏览 • 1回复 待解决
HarmonyOS RSA解密问题
376浏览 • 1回复 待解决