这是Android 加密解密方法,参考文档的写法加密出来的数据无法使用。如何把这个方法改写成HarmonyOS 鸿蒙Next代码?
这是Android 加密解密方法,参考文档的写法加密出来的数据无法使用。如何把这个方法改写成HarmonyOS 鸿蒙Next代码?
public class EncryptionHelper {
/**
-
Encrypts parts of a public key and returns the encrypted data as a JSON string.
-
@param context The application context.
-
@param employeeCode The employee’s public key used for encryption.
-
@return A JSON string of encrypted and Base64-encoded public key segments. */ public static String encryptPublicKeyParts(Context context, String employeeCode) { String pubkey1 = SPUtils.getString(context, Constant.PUBKEY, “”); if (TextUtils.isEmpty(pubkey1)) { return “”; } LogUtils.i("rsa: Frontend Public Key: " + pubkey1);
LogUtils.i("rsa: system pub key: " + employeeCode);
// Encrypting the key parts int partLength = pubkey1.length() / 3; ArrayList<String> encryptedSegments = new ArrayList<>(); encryptedSegments.add(encryptAndEncode(pubkey1.substring(0, partLength), employeeCode)); encryptedSegments.add(encryptAndEncode(pubkey1.substring(partLength, 2 * partLength), employeeCode)); encryptedSegments.add(encryptAndEncode(pubkey1.substring(2 * partLength), employeeCode)); // Convert to JSON Gson gson = new Gson(); String jsonEncryptedSegments = gson.toJson(encryptedSegments); LogUtils.i("rsa: Encrypted JSON Segments == " + jsonEncryptedSegments);
return jsonEncryptedSegments; }
/**
- Helper method to encrypt and encode a segment of a public key.
- @param keySegment The segment of the key to encrypt.
- @param publicKey The public key used for encryption.
- @return The encrypted and Base64-encoded segment. */ public static String encryptAndEncode(String keySegment, String publicKey) { byte[] encrypted; try { encrypted = RsaUtils.encryptByPublicKey(keySegment.getBytes(), publicKey); } catch (Exception e) { throw new RuntimeException(“Encryption failed”, e); } return Base64.encodeToString(encrypted, Base64.DEFAULT); }
/**
-
Encrypts segments of a public key, encodes them in Base64, and returns the segments as a JSON string.
-
@param pubkey The public key to be encrypted.
-
@param employeeCode The key used for RSA encryption.
-
@return JSON string of encrypted and Base64-encoded segments of the public key. */ public static String encryptPublicKey(String pubkey, String employeeCode) { int partLength = pubkey.length() / 3; ArrayList<String> encryptedSegments = new ArrayList<>(); encryptedSegments.add(encryptAndEncode(pubkey.substring(0, partLength), employeeCode)); encryptedSegments.add(encryptAndEncode(pubkey.substring(partLength, 2 * partLength), employeeCode)); encryptedSegments.add(encryptAndEncode(pubkey.substring(2 * partLength), employeeCode));
// Convert to JSON Gson gson = new Gson(); String jsonEncryptedSegments = gson.toJson(encryptedSegments); // Logging the encrypted segments LogUtils.i("rsa: Encrypted JSON Segments == " + jsonEncryptedSegments); return jsonEncryptedSegments; } }
public class RsaUtils {
private static final String KEY_ALGORITHM = “RSA”; private static final String CIPHER_ALGORITHM = “RSA/None/PKCS1Padding”; private static final int MAX_ENCRYPT_BLOCK = 53; // for 512-bit key private static final int MAX_DECRYPT_BLOCK = 64; // for 512-bit key private static final int KEY_SIZE = 512;
public static Map<String, Object> genKeyPair(String publicUserInfoKey, String privateUserInfoKey) throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(KEY_SIZE); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map<String, Object> keyMap = new HashMap<>(2); keyMap.put(publicUserInfoKey, publicKey); keyMap.put(privateUserInfoKey, privateKey); return keyMap; }
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception { byte[] keyBytes = Base64.decode(privateKey, Base64.DEFAULT); PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, privateK);
return processData(encryptedData, cipher, MAX_DECRYPT_BLOCK);
}
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception { byte[] keyBytes = Base64.decode(publicKey, Base64.DEFAULT); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); PublicKey publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, publicK);
return processData(data, cipher, MAX_ENCRYPT_BLOCK);
}
public static String getPrivateKey(Map<String, Object> keyMap, String privateUserInfoKey) { Key key = (Key) keyMap.get(privateUserInfoKey); return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); }
public static String getPublicKey(Map<String, Object> keyMap, String publicUserInfoKey) { Key key = (Key) keyMap.get(publicUserInfoKey); return Base64.encodeToString(key.getEncoded(), Base64.DEFAULT); }
private static byte[] processData(byte[] data, Cipher cipher, int blockSize) throws Exception { int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; while (inputLen - offSet > 0) { if (inputLen - offSet > blockSize) { cache = cipher.doFinal(data, offSet, blockSize); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * blockSize; } byte[] output = out.toByteArray(); out.close(); return output; }
// 新增方法:用于调试的加密过程 public static String encryptAndEncodeBase64(String data, String publicKey) throws Exception { byte[] encryptedBytes = encryptByPublicKey(data.getBytes(“UTF-8”), publicKey); return Base64.encodeToString(encryptedBytes, Base64.DEFAULT); }
// 新增方法:用于调试的解密过程 public static String decryptFromBase64(String encryptedBase64, String privateKey) throws Exception { byte[] encryptedBytes = Base64.decode(encryptedBase64, Base64.DEFAULT); byte[] decryptedBytes = decryptByPrivateKey(encryptedBytes, privateKey); return new String(decryptedBytes, “UTF-8”); }
/**
-
Des解密
-
@param data
-
@param key
-
@param iv */ public static String desEncrypt(String data, String key, String iv) throws Exception { try { byte[] encrypted1 = Base64.decode(data, Base64.DEFAULT);
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec); byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original); return originalString;
} catch (Exception e) { e.printStackTrace(); return null; } }
/**
-
加密
-
@param data
-
@param key
-
@param iv
-
@throws Exception */ public static String encrypt(String data, String key, String iv) throws Exception { try { Cipher cipher = Cipher.getInstance(“AES/CBC/NoPadding”); //"算法/模式/补码方式"NoPadding PkcsPadding int blockSize = cipher.getBlockSize();
byte[] dataBytes = data.getBytes(); int plaintextLength = dataBytes.length; if (plaintextLength % blockSize != 0) { plaintextLength = plaintextLength + (blockSize - (plaintextLength % blockSize)); } byte[] plaintext = new byte[plaintextLength]; System.arraycopy(dataBytes, 0, plaintext, 0, dataBytes.length); SecretKeySpec keyspec = new SecretKeySpec(key.getBytes(), "AES"); IvParameterSpec ivspec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec); byte[] encrypted = cipher.doFinal(plaintext); return Base64.encodeToString(encrypted, Base64.DEFAULT);
} catch (Exception e) { e.printStackTrace(); return null; } } }
更多关于这是Android 加密解密方法,参考文档的写法加密出来的数据无法使用。如何把这个方法改写成HarmonyOS 鸿蒙Next代码?的实战教程也可以访问 https://www.itying.com/category-93-b0.html
楼主把你写的鸿蒙加解密代码发一下看看呢?
更多关于这是Android 加密解密方法,参考文档的写法加密出来的数据无法使用。如何把这个方法改写成HarmonyOS 鸿蒙Next代码?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
import { cryptoFramework } from “@kit.CryptoArchitectureKit”;
import { buffer, util } from “@kit.ArkTS”;
import Logger from “./Logger”;
import { BusinessError } from “@kit.BasicServicesKit”;
export class EncryptUtil {
private static stringToUint8Array(str: string) { let arr: number[] = []; for (let i = 0, j = str.length; i < j; ++i) { arr.push(str.charCodeAt(i)); } let tmpArray = new Uint8Array(arr); return tmpArray; }
async encryptMessageCallback(pubKey: string, planText: string): Promise<string> { let rsaGenerator: cryptoFramework.AsyKeyGenerator; rsaGenerator = cryptoFramework.createAsyKeyGenerator(“RSA1024|PRIMES_2”); let cipher = cryptoFramework.createCipher(“RSA1024|NoPadding”); let base64 = new util.Base64Helper(); let key = base64.decodeSync(pubKey); let blob: cryptoFramework.DataBlob = { data: key }; let encryptedSegments: Uint8Array[] = []; let resultStr: string = “”; let encryptedPromises: Promise<cryptoFramework.DataBlob | undefined>[] = []; const blockSize = 128; let dataByte = EncryptUtil.stringToUint8Array(planText); let keyPairPubKey: cryptoFramework.PubKey; await rsaGenerator.convertKey(blob, null) .then(keyPair => { keyPairPubKey = keyPair.pubKey; return; }); await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPairPubKey!!, null).then(() => { return; }); for (let i = 0; i < dataByte.length; i += blockSize) { let chunk: Uint8Array; if (i + blockSize < dataByte.length) { chunk = dataByte.subarray(i, i + blockSize); } else { chunk = dataByte.subarray(i, dataByte.length); const paddingLength = blockSize - chunk.length; let zeros: Uint8Array = new Uint8Array(paddingLength).fill(0); let paddedChunk: Uint8Array = new Uint8Array(blockSize); paddedChunk.set(chunk); paddedChunk.set(zeros, chunk.length); chunk = paddedChunk; } let input: cryptoFramework.DataBlob = { data: chunk }; const encryptionPromise = new Promise<cryptoFramework.DataBlob | undefined>((resolve, reject) => { cipher.doFinal(input, (err, datas) => { if (err) { Logger.error(‘加密失败’, JSON.stringify(err)); reject(err); } else { encryptedSegments.push(datas.data); if ((i + blockSize) >= dataByte.length) { resolve({ data: datas.data }); } else { resolve(undefined); } } }); }); encryptedPromises.push(encryptionPromise); } await Promise.all(encryptedPromises).then(() => { if ((i + blockSize) >= dataByte.length) { const concatenatedData = encryptedSegments.reduce((total, segment) => { const tmp = new Uint8Array(total.length + segment.length); tmp.set(total, 0); tmp.set(segment, total.length); return tmp; }, new Uint8Array()); let finalEncryptedData = new Uint8Array(concatenatedData); Logger.info(‘加密完成后数据’, base64.encodeToStringSync(finalEncryptedData)); resultStr = base64.encodeToStringSync(finalEncryptedData); return; } }).catch((error: BusinessError) => { Logger.error(‘加密过程中发生错误’, JSON.stringify(error)); return ‘加密失败’; }); }
return resultStr; }
/**
- 使用RSA非对称密钥(PKCS1模式)加密
- @param message 要加密的明文数据
- @returns 加密后的字符串,base64编码 */ async encryptRSA(message: string, pubKeyStr: string) { // 服务器下发RSA公钥字符串(base64编码) // 初始化Base64工具实例 let base64Helper = new util.Base64Helper(); // 公钥转换为Uint8Array,然后包装为DataBlob类型 let pubKeyBlob: cryptoFramework.DataBlob = { data: base64Helper.decodeSync(pubKeyStr) }; // 创建RSA key生成器 let rsaGenerator = cryptoFramework.createAsyKeyGenerator(‘RSA1024’); // 将公钥包装数据pubKeyBlob转换成密钥对类型KeyPair let keyPair = await rsaGenerator.convertKey(pubKeyBlob, null); // 创建 Cipher对象 let cipher = cryptoFramework.createCipher(‘RSA1024|PKCS1’); // 初始化加密模式,指定密钥keyPair.pubKey await cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, keyPair.pubKey, null); // 包装要加密的明文 let plainTextBlob: cryptoFramework.DataBlob = { data: new Uint8Array(buffer.from(message, ‘utf-8’).buffer) }; // 传入明文,获取加密后的数据 let encryptBlob = await cipher.doFinal(plainTextBlob); // 返回加密后的字符串 return base64Helper.encodeToStringSync(encryptBlob.data); }
async getSign(parm1: string, publicKey: string): Promise<string> { let sign: string = ‘’; let signStr: string = parm1; let keyStr: string = publicKey; //根据模和指数获取rsa的公钥 let nIn = BigInt(keyStr); let eIn = BigInt(publicKey); let rsaCommSpec: cryptoFramework.RSACommonParamsSpec = { n: nIn, algName: “RSA”, specType: cryptoFramework.AsyKeySpecType.COMMON_PARAMS_SPEC }; let rsaPubKeySpec: cryptoFramework.RSAPubKeySpec = { params: rsaCommSpec, pk: eIn, algName: “RSA”, specType: cryptoFramework.AsyKeySpecType.PUBLIC_KEY_SPEC }; //获取pubkey let rsaGeneratorSpec = cryptoFramework.createAsyKeyGeneratorBySpec(rsaPubKeySpec); let pubKey = rsaGeneratorSpec.generatePubKeySync(); //创建MD5 const md = cryptoFramework.createMd(‘MD5’); await md.update({ data: new Uint8Array(buffer.from(signStr, ‘utf-8’).buffer) }); const mdResult = await md.digest(); //在加密 let cipher = cryptoFramework.createCipher(“RSA|ECB|PKCS1”); cipher.initSync(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); let input: cryptoFramework.DataBlob = { data: mdResult.data }; let dataBlob = cipher.doFinalSync(input); //在转成base64 const base64 = new util.Base64Helper(); return sign = encodeURIComponent(base64.encodeToStringSync(dataBlob.data)); } }
楼主你可以下载一个DevEco CodeGenie,安装到IDE中,然后选的Deepseek对话,描述需要使用是加密算法及想要的效果,看看有没有帮助
下载地址:https://developer.huawei.com/consumer/cn/download/deveco-codegenie
在HarmonyOS中,加密解密可以使用Security
模块提供的API。以下是一个简单的示例,展示如何在HarmonyOS中实现AES加密解密:
import security from '@ohos.security';
// 加密
function encryptAES(data: string, key: string, iv: string): Uint8Array {
const cipher = security.crypto.createCipher('AES-CBC', key);
cipher.setAutoPadding(true);
cipher.setIV(iv);
const encrypted = cipher.update(data);
return encrypted.concat(cipher.final());
}
// 解密
function decryptAES(encryptedData: Uint8Array, key: string, iv: string): string {
const decipher = security.crypto.createDecipher('AES-CBC', key);
decipher.setAutoPadding(true);
decipher.setIV(iv);
const decrypted = decipher.update(encryptedData);
return decrypted.concat(decipher.final()).toString();
}
// 使用示例
const key = '1234567890123456'; // 16字节密钥
const iv = '1234567890123456'; // 16字节初始向量
const data = 'Hello, HarmonyOS!';
const encrypted = encryptAES(data, key, iv);
const decrypted = decryptAES(encrypted, key, iv);
console.log('Decrypted:', decrypted);
在这个示例中,我们使用了@ohos.security
模块中的createCipher
和createDecipher
方法来创建加密和解密对象,并通过setIV
方法设置初始向量。加密和解密的数据类型为Uint8Array
。
确保密钥和初始向量长度符合AES算法的要求(16字节)。通过这种方式,你可以在HarmonyOS中实现与Android类似的加密解密功能。