Web3j

java.lang.ClassCastException:org.bouncycastle 在使用 web3j 創建錢包時出錯

  • December 18, 2018

我正在使用 web3j 創建帳戶。

String walletFileName = WalletUtils.generateFullNewWalletFile("
<password>",new File("some/path"));

但收到此錯誤:

java.lang.ClassCastException: org.bouncycastle.jce.provider.JCEECPrivateKey cannot be cast to org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey

我在 pom.xml 中的設置如下:

<dependency>
   <groupId>org.web3j</groupId>
   <artifactId>core</artifactId>
   <version>3.4.0</version>
</dependency>
<dependency>
   <groupId>org.bouncycastle</groupId>
   <artifactId>bcprov-jdk15on</artifactId>
   <version>1.54</version>
</dependency>

請讓我知道我哪裡出錯了。

你的程式碼似乎沒問題,我剛剛創建了一個項目,我可以執行它:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>io.gjeanmart.sandbox.web3j</groupId>
   <artifactId>Web3jCreateWallet</artifactId>
   <version>0.0.1-SNAPSHOT</version>

   <properties>
       <maven.compiler.target>1.8</maven.compiler.target>
       <maven.compiler.source>1.8</maven.compiler.source>
   </properties>

   <dependencies>
       <dependency>
           <groupId>org.web3j</groupId>
           <artifactId>core</artifactId>
           <version>3.4.0</version>
       </dependency>
   </dependencies>

</project>

PS:您實際上不需要添加bouncycastle作為依賴項,因為它是由 web3j:core 直接拉取的。

在此處輸入圖像描述

TestCreateWallet.java

package io.gjeanmart.stackexchange.web3j.test;

import java.io.File;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import org.junit.Test;
import org.web3j.crypto.CipherException;
import org.web3j.crypto.WalletUtils;

public class TestCreateWallet {

   @Test
   public void createWallet() throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException, CipherException, IOException {

       String folder = "/tmp/wallet/";
       String password = "secr3t";

       File folderFile = new File(folder);
       folderFile.mkdirs();

       String walletFileName = WalletUtils.generateFullNewWalletFile(password, folderFile);
       System.out.println("Wallet generated: " + walletFileName);
   }

}

結果:

錢包生成:UTC–2018-12-18T16-41-35.32000000Z–cdf77e5fbee401d12f394f4f47f883407e883bd1.json

程式碼:

Github 上提供的程式碼

引用自:https://ethereum.stackexchange.com/questions/64254