将字节数组转换回公钥

时间:2016-03-08 12:49:57

标签: java security byte public-key

我将公钥转换为字节数组。我想将其转换回公钥。我遵循了这个link,但收到了错误:

Operation failed: javax.crypto.spec.SecretKeySpec incompatible with java.security.PublicKey

由于我知道它是公钥,是否可以将其转换为Publickey而不是SecretKey

修改

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

我传递的关键材料 3082010a0282010100ab7f161c0042496ccd6c6d4dadb919973435357776003acf54b7af1e440afb80b64a8755f8002cfeba6b184540a2d66086d74648346d75b8d71812b205387c0f6583bc4d7dc7ec114f3b176b7957c422e7d03fc6267fa2a6f89b9bee9e60a1d7c2d833e5a5f4bb0b1434f4e795a41100f8aa214900df8b65089f98135b1c67b701675abdbc7d5721aac9d14a7f081fcec80b64e8a0ecc8295353c795328abf70e1b42e7bb8b7f4e8ac8c810cdb66e3d21126eba8da7d0ca34142cb76f91f013da809e9c1b7ae64c54130fbc21d80e9c2cb06c5c8d7cce8946a9ac99b1c2815c3612a29a82d73a1f99374fe30e54951662a6eda29c6fc411335d5dc7426b0f6050203010001

使用RSAPublicKeySpec 将其转换为公钥后获得的密钥材料 30820122300D06092A864886F70D01010105000382010F003082010A0282010100AB7F161C0042496CCD6C6D4DADB919973435357776003ACF54B7AF1E440AFB80B64A8755F8002CFEBA6B184540A2D66086D74648346D75B8D71812B205387C0F6583BC4D7DC7EC114F3B176B7957C422E7D03FC6267FA2A6F89B9BEE9E60A1D7C2D833E5A5F4BB0B1434F4E795A41100F8AA214900DF8B65089F98135B1C67B701675ABDBC7D5721AAC9D14A7F081FCEC80B64E8A0ECC8295353C795328ABF70E1B42E7BB8B7F4E8AC8C810CDB66E3D21126EBA8DA7D0CA34142CB76F91F013DA809E9C1B7AE64C54130FBC21D80E9C2CB06C5C8D7CCE8946A9AC99B1C2815C3612A29A82D73A1F99374FE30E54951662A6EDA29C6FC411335D5DC7426B0F6050203010001

显然,验证将失败,因为密钥材料是错误的!我不明白为什么它会被改变。

但是当我使用java.security.PublicKey(匿名内部类)直接创建公钥时,密钥材料不会被更改。但是当我通过验证时,我得到错误的算法类型错误(我通过RSA作为算法)

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;
}

1 个答案:

答案 0 :(得分:2)

取自Here

//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);