密钥格式需要在Crypt RSA中使用


Key format need to use in Crypt RSA

我用这个Java函数来创建密钥对。

      KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyAlgorithm);
        keyGen.initialize(numBits);
        KeyPair keyPair = keyGen.genKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey  publicKey  = keyPair.getPublic();
        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes  = publicKey.getEncoded();

我得到了这个作为公钥(类似于这个。无法粘贴到此处):

0��0
    *�H��

我想知道这是哪个格式的键? pem/der ?

我想在我的 rsa php 代码中使用此密钥。我是否需要转换为任何特定格式?

$keyData =file_get_contents($configValues['metPubKey']); //'metPubKey 'variable contain file path
    $rsa = new Crypt_RSA();
        try{
            $rsa->loadKey($keyData); // public key
            // $rsa->setPublicKeyFormat(CRYPT_RSA_PUBLIC_FORMAT_XML);
            //$rsa->setHash('md5');
            $encryptedToken = base64_encode($rsa->encrypt($token));
            print_r("after : '"".$encryptedToken."'"");
        }catch(Exception $e){
            // print_r($e);
            die;
        }

它不会引发任何异常。但是出于我的好奇心,在使用相同的数据运行相同的代码时,每次都会创建不同的令牌。我只是想确认一下。

php 中还有其他方法可以使用 RSA 公钥加密数据吗?

不幸的是,

Java在处理二进制原始数据时非常笨拙...但是,由于领先的PKCS填充连接了一些随机内容,以防止重放攻击和/或对加密数据的统计分析,因此您每次都会获得不同的令牌

仅供参考,您要加密对称密钥并使用此类密钥对大型二进制数据进行编码/解码。不要直接使用 RSA 对最终数据进行编码/解码!