1.在电脑上生成公钥和私钥
openssl genrsa -out private.pem 2048
openssl rsa -in private.pem -pubout -out public.pem
2.把公钥和私钥复制到手机/sdcard/ 目录下
function base64Bytes(bytes) {return android.util.Base64.encodeToString(bytes, android.util.Base64.NO_WRAP);
}
function pemToKey(pem, type) {const factory = java.security.KeyFactory.getInstance("RSA");const clean = pem.replace(/-----[^-]+-----|\s/g, ""); const der = android.util.Base64.decode(clean, 0);const spec = type === "public"? new java.security.spec.X509EncodedKeySpec(der) : new java.security.spec.PKCS8EncodedKeySpec(der); return type === "public"? factory.generatePublic(spec): factory.generatePrivate(spec);
}
const pubKey ={toKeySpec:function(){return pemToKey(files.read("/sdcard/public.pem"), "public");}}
const priKey ={toKeySpec:function(){return pemToKey(files.read("/sdcard/private.pem"), "private");}}
const cipher = $crypto.encrypt(JSON.stringify({code:21,data:"test"}), pubKey, "RSA",{output: "base64"});
log(cipher)
const plain = $crypto.decrypt(cipher, priKey, "RSA", {input:"base64",output: "string"});
console.log(plain);
3.与php对接
public function testjiami(Request $request){$password = $request->input('password');$privateKey = openssl_pkey_get_private(file_get_contents('/www/wwwroot/nbcolorvision.com/storage/keys/private.pem'));$publicKey = file_get_contents('/www/wwwroot/nbcolorvision.com/storage/keys/public.pem');$plain = '{"code":21,"data":"test","fdgdfg":"dsaadfdasfasfasf","dsadasdas":"sdfsaddasdasd"}';$plain = str_pad($plain, 256, "a");openssl_private_encrypt($plain, $cipherRaw, $privateKey,OPENSSL_NO_PADDING); $cipherBase64 = base64_encode($cipherRaw); openssl_private_decrypt(base64_decode($password), $decrypted, $privateKey,OPENSSL_NO_PADDING);$decrypted = rtrim($decrypted, "\0");$decrypted = ltrim($decrypted, "\0");$plain = preg_replace('/a+$/', '', $plain);return['plain' => $plain,'cipherBase64' => $cipherBase64,'decrypted' => $decrypted,] ;}