Android Native加密解密:AES和RSA示例,高效处理byte[]数组
在Android开发中,你可以使用JNI(Java Native Interface)来在Native层的C++代码中进行加密和解密操作。JNI允许你在Java和C++之间进行相互调用。\n\n关于加密和解密算法,Android提供了许多可用的选项。以下是一些常用的加密算法示例:\n\n1. AES(Advanced Encryption Standard)对称加密算法:\n - 你可以使用javax.crypto包中的Cipher类来进行AES加密和解密操作。\n - 以下是一个示例代码:\n\njava\nimport javax.crypto.Cipher;\nimport javax.crypto.spec.SecretKeySpec;\n\npublic class EncryptionUtils {\n private static final String AES_ALGORITHM = \"AES\";\n\n public static byte[] encrypt(byte[] data, byte[] key) throws Exception {\n SecretKeySpec secretKeySpec = new SecretKeySpec(key, AES_ALGORITHM);\n Cipher cipher = Cipher.getInstance(AES_ALGORITHM);\n cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);\n return cipher.doFinal(data);\n }\n\n public static byte[] decrypt(byte[] encryptedData, byte[] key) throws Exception {\n SecretKeySpec secretKeySpec = new SecretKeySpec(key, AES_ALGORITHM);\n Cipher cipher = Cipher.getInstance(AES_ALGORITHM);\n cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);\n return cipher.doFinal(encryptedData);\n }\n}\n\n\n2. RSA(Rivest-Shamir-Adleman)非对称加密算法:\n - 你可以使用java.security包中的KeyPairGenerator和Cipher类来进行RSA加密和解密操作。\n - 以下是一个示例代码:\n\njava\nimport java.security.KeyPair;\nimport java.security.KeyPairGenerator;\nimport java.security.PrivateKey;\nimport java.security.PublicKey;\nimport javax.crypto.Cipher;\n\npublic class EncryptionUtils {\n private static final String RSA_ALGORITHM = \"RSA\";\n\n public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception {\n Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);\n cipher.init(Cipher.ENCRYPT_MODE, publicKey);\n return cipher.doFinal(data);\n }\n\n public static byte[] decrypt(byte[] encryptedData, PrivateKey privateKey) throws Exception {\n Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);\n cipher.init(Cipher.DECRYPT_MODE, privateKey);\n return cipher.doFinal(encryptedData);\n }\n\n public static KeyPair generateKeyPair() throws Exception {\n KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);\n keyPairGenerator.initialize(2048);\n return keyPairGenerator.generateKeyPair();\n }\n}\n\n\n这些示例代码演示了在Java层进行加密和解密操作。你可以在JNI中调用这些Java方法,将byte数组传递到Native层进行加密和解密操作。在JNI中,你可以使用GetByteArrayElements和ReleaseByteArrayElements方法来获取和释放byte数组的指针,以便在C++代码中进行处理。\n\n请注意,以上示例代码仅用于演示目的,实际使用时需要根据具体需求进行适当的修改和扩展。
原文地址: https://www.cveoy.top/t/topic/p9vj 著作权归作者所有。请勿转载和采集!