将字节数组转换回公钥 [英] convert byte array back to Public key

查看:313
本文介绍了将字节数组转换回公钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将公共密钥转换为字节数组。我想将其转换回公钥。我遵循了这个链接但出现错误:

I've a Public key converted to byte array. I want to convert it back to Public key. I followed this link but getting an error :

操作失败:javax.crypto.spec.SecretKeySpec与java.security.PublicKey

由于我知道这是一个公共密钥,有什么可以将其转换为 Publickey 的方法 SecretKey

Since I know that it is a public key, is there any to convert it to Publickey instead of SecretKey.

EDIT

EDIT

我已经使用 RSAPublicKeySPec 创建了一个公钥。现在,没有错误,但签名验证失败,因为当我看到新创建的公钥的密钥材料时,它与我通过的内容不同。

I have created a public key using RSAPublicKeySPec. Now there is no error but the signature verification fails because when I see the key material of the newly created public key, it is different from what I passed.

我通过的关键材料

使用RSAPublicKeySpec将其转换为公钥后得到的密钥材料
30820122300D06092A864886F70D01010105000382010F003082010A0282010100AB7F161C004249 6CCD6C6D4DADB919973435357776003ACF54B7AF1E440AFB80B64A8755F8002CFEBA6B184540A2D66086D74648346D75B8D71812B205387C0F6583BC4D7DC7EC114F3B176B7957C422E7D03FC6267FA2A6F89B9BEE9E60A1D7C2D833E5A5F4BB0B1434F4E795A41100F8AA214900DF8B65089F98135B1C67B701675ABDBC7D5721AAC9D14A7F081FCEC80B64E8A0ECC8295353C795328ABF70E1B42E7BB8B7F4E8AC8C810CDB66E3D21126EBA8DA7D0CA34142CB76F91F013DA809E9C1B7AE64C54130FBC21D80E9C2CB06C5C8D7CCE8946A9AC99B1C2815C3612A29A82D73A1F99374FE30E54951662A6EDA29C6FC411335D5DC7426B0F6050203010001

显然,由于主要材料是错误的验证会失败!我不明白为什么它会被改变。

Clearly, the verification will fail because the key material is wrong! I don't understand why it is getting altered.

但是当我直接使用 java.security.PublicKey (匿名内部类)创建公共密钥时,密钥材料不会改变。但是,当我通过它进行验证时,出现了错误的算法类型错误(我通过RSA作为算法)

But when I directly create a public key using java.security.PublicKey (anonymous inner class), the key material doesn't get altered. But when I pass it to verify, I get wrong algorithm type error (I passed RSA as the algorithm)

代码片段

CODE SNIPPET

    PublicKey pubKey = new PublicKey() {

        private static final long serialVersionUID = 1L;

        @Override
        public String getFormat() {

            return "PKCS1";
        }

        @Override
        public byte[] getEncoded() {

            return keyMat;
        }

        @Override
        public String getAlgorithm() {

            return "SHA256withRSA"; // tried with "RSA", getting same error
        }
    };

    return pubKey;
}


推荐答案

此处

//Takes your byte array of the key as constructor parameter
X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(myKeyBytes);

//Takes algorithm used to generate keys (DSA, RSA, DiffieHellman, etc.) as 1st parameter
//Takes security provider (SUN, BouncyCastle, etc.) as second parameter
KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");

//Creates a new PublicKey object
PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

这篇关于将字节数组转换回公钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆