Ruby Ruby RSA 如何实现 Java 的这段代码

shadow · 2012年08月17日 · 最后由 luikore 回复于 2012年08月17日 · 5523 次阅读

String publickey = "TUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFEQ0JpUUtCZ1FDSmovRFYrN3QyM0dRZXNXRVpOYzd3cUtZQ2NpYnI1aGdWZlVpcEpxeEpEK3dveTBLY28yWnk5QURpT3lkVU9EcXJLUnUzNmFqQ3ROMU5tVlJUR0JkQzRaWGk3MUpTczY5VDJoaUxGaEtSSW5yaDNtZnVoUTc2SUJxNlQvMzlqZmFXNU0wOTZBQVlaSWNrN21xczNLdlRhUllHN2FZbHo3cGpyV0drcUNzNmNRSURBUUFC" ;
PublicKey key = Security.generatePublicKey(new String(Base64.decode(publickey)));
verified = Security. verify(key, signedData, signature);

Security.generatePublicKey 如下


public static PublicKey generatePublicKey(String encodedPublicKey) {
        try {
            byte[] decodedKey = Base64.decode(encodedPublicKey);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
            return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            Log.e(TAG, "Invalid key specification.");
            throw new IllegalArgumentException(e);
        } catch (Base64DecoderException e) {
            Log.e(TAG, "Base64 decoding failed.");
            throw new IllegalArgumentException(e);
        }
    }

查看了一些资料 keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));有些不明了了

KEY_FACTORY_ALGORITHM = RSA

你这个 publickey 用 base64 算了两次,然后还得解两次,坑爹啊

require 'openssl'
require 'base64'
publickey = Base64.decode64 "TUlHZk1BMEdDU3FHU0liM0RRRUJBUVVBQTRHTkFEQ0JpUUtCZ1FDSmovRFYrN3QyM0dRZXNXRVpOYzd3cUtZQ2NpYnI1aGdWZlVpcEpxeEpEK3dveTBLY28yWnk5QURpT3lkVU9EcXJLUnUzNmFqQ3ROMU5tVlJUR0JkQzRaWGk3MUpTczY5VDJoaUxGaEtSSW5yaDNtZnVoUTc2SUJxNlQvMzlqZmFXNU0wOTZBQVlaSWNrN21xczNLdlRhUllHN2FZbHo3cGpyV0drcUNzNmNRSURBUUFC"
pkey = OpenSSL::PKey::RSA.new Base64.decode64 publickey
# 你的 java 代码在验证时用的摘要方法是什么就不知道了, md5, sha1, sha256 都试试
digester = OpenSSL::Digest::MD5.new
puts pkey.verify(digester, signature, data)
需要 登录 后方可回复, 如果你还没有账号请 注册新账号