autojs RSA加密(使用public.pem、private.pem)

发布于:2025-08-31 ⋅ 阅读:(27) ⋅ 点赞:(0)

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);
}
// 工具:PEM → Key
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");
    }}

// let message =files.readBytes("/sdcard/res1.jpg") ;
// 加密 / 解密测试
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){
        // $key = openssl_pkey_get_private("/www/wwwroot/nbcolorvision.com/storage/keys/private.pem");
       
        $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);                   // base64
        
            openssl_private_decrypt(base64_decode($password), $decrypted, $privateKey,OPENSSL_NO_PADDING);
            $decrypted = rtrim($decrypted, "\0");
            $decrypted = ltrim($decrypted, "\0");
            // $plain = rtrim($plain, "\0");
      
            $plain = preg_replace('/a+$/', '', $plain);
          
       
        return[
            'plain'         => $plain,
            'cipherBase64'  => $cipherBase64,
            'decrypted'     => $decrypted,
        ] ;
        

    }

网站公告

今日签到

点亮在社区的每一天
去签到