我想将我的私钥保存在 json 文件(十六进制格式)中,然后将其作为 PrivateKey 读取。Here Keys生成函数public void generateKeyPair() { try { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("ECDSA", "BC"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); ECGenParameterSpec ecSpec = new ECGenParameterSpec("secp256k1"); keyGen.initialize(ecSpec,random); KeyPair keyPair = keyGen.generateKeyPair(); privateKey = keyPair.getPrivate(); publicKey = keyPair.getPublic(); } catch (Exception e) { throw new RuntimeException(e); }}这就是我将它保存到 json 文件中的方式 a.generateKeyPair(); byte[] enc_key = a.privateKey.getEncoded(); StringBuilder key_builder = new StringBuilder(); for(byte b : enc_key){ key_builder.append(String.format( "%02X",b)); } String serialized_key = key_builder.toString(); account.privateKey=serialized_key; try (Writer writer = new FileWriter("Output.json")) { Gson gson = new GsonBuilder().create(); gson.toJson(account, writer); } catch (IOException e) { e.printStackTrace(); }并从文件中读取它 Gson gson = new GsonBuilder().create(); try (Reader read1 = new FileReader("Output.json")) { account=gson.fromJson(read1,account.getClass()); byte[] encoded_key=account.privateKey.getBytes(); a.privateKey = getPrivateKey(encoded_key); public static PrivateKey getPrivateKey(byte[] privkey) throws NoSuchAlgorithmException, InvalidKeySpecException { Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privkey); KeyFactory kf = null; try { kf = KeyFactory.getInstance("ECDSA", "BC"); } catch (NoSuchProviderException e) { e.printStackTrace(); }
1 回答
精慕HU
TA贡献1845条经验 获得超8个赞
您忘记对私钥进行十六进制解码。仅仅表演是getBytes
不行的。
编码字节以 SEQUENCE, tag 开头0x30
。这在十六进制中当然是"30"
or,在 ASCII:: 中0x33, 0x30
:这些是getBytes
. 现在解码器查看具有位值的第一个字节0b001_10011
。最后 5 位对标签值进行编码,即 16 + 2 + 1 = 19。因此是特定错误。
添加回答
举报
0/150
提交
取消