org.fisco.bcos.web3j.crypto.ECKeyPair Java Examples

The following examples show how to use org.fisco.bcos.web3j.crypto.ECKeyPair. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testCNSManager() throws Exception {
    address = "0x832f299af98c215f7ada010a966b12126483cd00";
    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //生成web3sdk使用的Credentials
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
    PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

    // TablePermission
    System.out.println(permissionService.grantCNSManager(address));
    assertNotNull(permissionService.grantCNSManager(address));
    System.out.println(permissionService.listCNSManager().get(0).getAddress());
    assertTrue(permissionService.listCNSManager().size() != 0);
    System.out.println(permissionService.revokeCNSManager(address));
    assertNotNull(permissionService.revokeCNSManager(address));
}
 
Example #2
Source File: KeyPairUtils.java    From WeBASE-Sign with Apache License 2.0 6 votes vote down vote up
/**
 * get ec key pair from guomi key pair data
 * @param keyPairData common key pair
 * @return ECKeyPair
 */
private ECKeyPair genEcPairFromKeyPair(KeyPair keyPairData) {
    try {
        SM2PrivateKey vk = (SM2PrivateKey) keyPairData.getPrivate();
        SM2PublicKey pk = (SM2PublicKey) keyPairData.getPublic();
        final byte[] publicKey = pk.getEncoded();
        final byte[] privateKey = vk.getEncoded();

        BigInteger biPublic = new BigInteger(Hex.toHexString(publicKey), 16);
        BigInteger biPrivate = new BigInteger(Hex.toHexString(privateKey), 16);

        ECKeyPair keyPair = new ECKeyPair(biPrivate, biPublic);
        return keyPair;
    } catch (Exception e) {
        log.error("KeyPairUtils create ec_keypair of guomi failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #3
Source File: GenCredential.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
private static ECKeyPair genEcPairFromKeyPair(KeyPair keyPairData) {
    try {
        SM2PrivateKey vk = (SM2PrivateKey) keyPairData.getPrivate();
        SM2PublicKey pk = (SM2PublicKey) keyPairData.getPublic();
        final byte[] publicKey = pk.getEncoded();
        final byte[] privateKey = vk.getEncoded();

        BigInteger biPublic = new BigInteger(Hex.toHexString(publicKey), 16);
        BigInteger biPrivate = new BigInteger(Hex.toHexString(privateKey), 16);

        ECKeyPair keyPair = new ECKeyPair(biPrivate, biPublic);
        return keyPair;
    } catch (Exception e) {
        logger.error("create ec_keypair of guomi failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #4
Source File: KeyStoreService.java    From WeBASE-Transaction with Apache License 2.0 6 votes vote down vote up
/**
 * get KeyStoreInfo.
 * 
 * @return
 */
public KeyStoreInfo getKey() throws BaseException {
    try {
        ECKeyPair keyPair = Keys.createEcKeyPair();
        String publicKey = Numeric.toHexStringWithPrefixZeroPadded(keyPair.getPublicKey(),
                PUBLIC_KEY_LENGTH_IN_HEX);
        String privateKey = Numeric.toHexStringNoPrefix(keyPair.getPrivateKey());
        String address = "0x" + Keys.getAddress(publicKey);

        KeyStoreInfo keyStoreInfo = new KeyStoreInfo();
        keyStoreInfo.setPublicKey(publicKey);
        keyStoreInfo.setPrivateKey(privateKey);
        keyStoreInfo.setAddress(address);

        return keyStoreInfo;
    } catch (Exception e) {
        log.error("createEcKeyPair fail.");
        throw new BaseException(ConstantCode.SYSTEM_ERROR);
    }
}
 
Example #5
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testConfigManager() throws Exception {
    address = "0x832f299af98c215f7ada010a966b12126483cd00";
    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //生成web3sdk使用的Credentials
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
    PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

    // TablePermission
    System.out.println(permissionService.grantSysConfigManager(address));
    assertNotNull(permissionService.grantSysConfigManager(address));
    System.out.println(permissionService.listSysConfigManager().get(0).getAddress());
    assertTrue(permissionService.listSysConfigManager().size() != 0);
    System.out.println(permissionService.revokeSysConfigManager(address));
    assertNotNull(permissionService.revokeSysConfigManager(address));
}
 
Example #6
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testNodeManger() throws Exception {
    address = "0x832f299af98c215f7ada010a966b12126483cd00";
    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //生成web3sdk使用的Credentials
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
    PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

    // TablePermission
    System.out.println(permissionService.grantNodeManager(address));
    assertNotNull(permissionService.grantNodeManager(address));
    System.out.println(permissionService.listNodeManager().get(0).getAddress());
    assertTrue(permissionService.listNodeManager().size() != 0);
    System.out.println(permissionService.revokeNodeManager(address));
    assertNotNull(permissionService.revokeNodeManager(address));
}
 
Example #7
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
    public void testUserTableManager() throws Exception{
        String tableName = "t_test";
        address = "0xd5bba8fe456fce310f529edecef902e4b63129b1";

        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        PEMManager pem = context.getBean(PEMManager.class);
        ECKeyPair pemKeyPair = pem.getECKeyPair();
        //生成web3sdk使用的Credentials
        Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
        PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

        // TablePermission
        System.out.println(permissionService.grantUserTableManager(tableName, address));
        assertNotNull(permissionService.grantUserTableManager(tableName, address));
//        List<PermissionInfo> list = permissionService.listUserTableManager(tableName);
//        assertTrue(permissionService.listUserTableManager(tableName).size() != 0);
//        System.out.println(permissionService.revokeUserTableManager(tableName, address));
//        assertNotNull(permissionService.revokeUserTableManager(tableName, address));
    }
 
Example #8
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
    public void testDeployAndCreateManager() throws Exception{
        // 普通账户
        address = "0x832f299af98c215f7ada010a966b12126483cd00";

        context = new ClassPathXmlApplicationContext("applicationContext.xml");
        PEMManager pem = context.getBean(PEMManager.class);
        ECKeyPair pemKeyPair = pem.getECKeyPair();
        //生成web3sdk使用的Credentials
        Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
        // 链管理员账户签名的PermissionService
        PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

        // TablePermission
        System.out.println(permissionService.grantDeployAndCreateManager(address));
        System.out.println(permissionService.grantDeployAndCreateManager(address));

        assertNotNull(permissionService.grantDeployAndCreateManager(address));
        System.out.println(permissionService.listDeployAndCreateManager().get(0).getAddress());
        assertTrue(permissionService.listDeployAndCreateManager().size() != 0);
//        System.out.println(permissionService.revokeDeployAndCreateManager(address));
//        assertNotNull(permissionService.revokeDeployAndCreateManager(address));
    }
 
Example #9
Source File: PermissionServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testPermissionManager() throws Exception{
    address = "0x832f299af98c215f7ada010a966b12126483cd00";

    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //生成web3sdk使用的Credentials
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));
    PermissionService permissionService = new PermissionService(web3j, credentialsPEM);

    System.out.println(permissionService.grantPermissionManager(address));
    assertNotNull(permissionService.grantPermissionManager(address));
    System.out.println(permissionService.listPermissionManager().get(0).getAddress());
    assertTrue(permissionService.listPermissionManager().size() != 0);
    System.out.println(permissionService.revokePermissionManager(address));
    assertNotNull(permissionService.revokePermissionManager(address));
}
 
Example #10
Source File: ImportCertTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
     * address到底需不需要传入pub的开头的两位04
     * 答案: 不需要,公钥是128位的
     */
    @Test
    public void testAddress() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
        ECKeyPair key = Keys.createEcKeyPair();
        // 用byte[]穿进去获取公钥,就会可能多出一位0
        byte[] pubBytes = key.getPublicKey().toByteArray();
        System.out.println("=============原生的==============");
        System.out.println(key.getPublicKey()); //64bytes BigInteger
        System.out.println(Keys.getAddress(key.getPublicKey()));

        System.out.println("===========通过转成hex后获取地址============");
        System.out.println(Numeric.toHexStringNoPrefix(key.getPublicKey())); //Hex后显示
        System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(key.getPublicKey())));

        System.out.println("===========通过byte[]============");
        System.out.println(Numeric.toHexStringNoPrefix(pubBytes)); // BigInteget=> byte[] => hex 多一位
        System.out.println(Keys.getAddress(Numeric.toHexStringNoPrefix(pubBytes)));
        System.out.println("===============");
//        System.out.println(Keys.getAddress(pubBytes));
    }
 
Example #11
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
/**
 * create key store locally and save
 * with private key
 */
public KeyStoreInfo createKeyStoreLocally(String userName) {
    log.info("start createKeyStore. userName:{}", userName);
    checkUserNameAndTypeNotExist(userName, KeyTypes.LOCALUSER.getValue());
    // create keyPair(support guomi)
    KeyStoreInfo keyStoreInfo;
    try {
        ECKeyPair keyPair = GenCredential.createKeyPair();
        keyStoreInfo = keyPair2KeyStoreInfo(keyPair, userName);
    } catch (Exception e) {
        log.error("fail createKeyStore.", e);
        throw new FrontException("create keyInfo failed");
    }
    keyStoreInfo.setType(KeyTypes.LOCALUSER.getValue());
    String realPrivateKey = keyStoreInfo.getPrivateKey();
    keyStoreInfo.setPrivateKey(aesUtils.aesEncrypt(realPrivateKey));
    return keystoreRepository.save(keyStoreInfo);
}
 
Example #12
Source File: PrecompiledSysConfigServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemConfig() throws Exception {

    key = "tx_count_limit"; // key: tx_count_limit, tx_gas_limit
    value = "300000001";

    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //链管理员私钥加载
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));

    SystemConfigService systemConfigService = new SystemConfigService(web3j, credentialsPEM);

    System.out.println(web3j.getSystemConfigByKey(key).send().getResult());
    System.out.println(systemConfigService.setValueByKey(key, value));
    assertNotNull(systemConfigService.setValueByKey(key, value));
    System.out.println(web3j.getSystemConfigByKey(key).send().getResult());
    assertNotNull(web3j.getSystemConfigByKey(key));
}
 
Example #13
Source File: ConsensusServiceTest.java    From WeBASE-Front with Apache License 2.0 6 votes vote down vote up
@Test
public void testConsensus() throws Exception {
    nodeId = "224e6ee23e8a02d371298b9aec828f77cc2711da3a981684896715a3711885a3177b3cf7906bf9d1b84e597fad1e0049511139332c04edfe3daddba5ed60cffa";

    context = new ClassPathXmlApplicationContext("applicationContext.xml");
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    //链管理员私钥加载
    Credentials credentialsPEM = GenCredential.create(pemKeyPair.getPrivateKey().toString(16));

    ConsensusService consensusService = new ConsensusService(web3j, credentialsPEM);
    System.out.println(consensusService.addSealer(nodeId));
    assertNotNull(consensusService.addSealer(nodeId));
    System.out.println(consensusService.addObserver(nodeId));
    assertNotNull(consensusService.addObserver(nodeId));
    System.out.println(consensusService.removeNode(nodeId));
    assertNotNull(consensusService.removeNode(nodeId));
}
 
Example #14
Source File: GenCredential.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
public static Credentials create() {
    try {
        ECKeyPair keyPair = createKeyPair();
        if (keyPair == null) return null;

        Credentials credentials = Credentials.create(keyPair);
        logger.debug(
                " privateKey: {}, publicKey: {}, address: {}",
                credentials.getEcKeyPair().getPrivateKey(),
                credentials.getEcKeyPair().getPrivateKey(),
                credentials.getAddress());
        return credentials;
    } catch (Exception e) {
        System.out.println("init credential failed");
        logger.error("init credential failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #15
Source File: GenCredential.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static Credentials create(String privKey) {
    try {
        ECKeyPair keyPair = createKeyPair(privKey);
        if (keyPair == null) return null;
        Credentials credentials = Credentials.create(keyPair);
        return credentials;
    } catch (Exception e) {
        System.out.println("init credential from private key failed ");
        logger.error("init credential from private key failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #16
Source File: TestTxDecode.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static TransactionReceipt sentTx() throws Exception {
    // init the Service
    ApplicationContext context =
            new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
    Service service = context.getBean(Service.class);
    service.run();
    ECKeyPair keyPair = Keys.createEcKeyPair();
    Credentials credentials = Credentials.create(keyPair);
    ChannelEthereumService channelEthereumService = new ChannelEthereumService();
    channelEthereumService.setChannelService(service);
    service.setGroupId(1);
    Web3j web3j = Web3j.build(channelEthereumService, service.getGroupId());

    RemoteCall<TableTest> deploy =
            TableTest.deploy(
                    web3j,
                    credentials,
                    new StaticGasProvider(
                            new BigInteger("30000000"), new BigInteger("30000000")));
    TableTest tableTest = deploy.send();
    tableTest.create().send();

    String name = "fruit";
    int item_id = 1;
    String item_name = "apple";

    RemoteCall<TransactionReceipt> insert =
            tableTest.insert(name, BigInteger.valueOf(item_id), item_name);
    TransactionReceipt txReceipt = insert.send();

    return txReceipt;
}
 
Example #17
Source File: GenCredential.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static Credentials create(ECKeyPair keyPair) {
    try {
        ECKeyPair newKeyPair = createKeyPair(keyPair.getPrivateKey().toString(16));
        if (newKeyPair == null) return null;
        Credentials credentials = Credentials.create(newKeyPair);
        return credentials;
    } catch (Exception e) {
        System.out.println("init credential from private key failed ");
        logger.error("init credential from private key failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #18
Source File: GenCredential.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private static ECKeyPair createECDSAKeyPair() {
    try {
        ECKeyPair keyPair = Keys.createEcKeyPair();
        return keyPair;
    } catch (Exception e) {
        logger.error("create keypair of ECDSA failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #19
Source File: AccountTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void accountTest()
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
                InvalidKeySpecException, NoSuchProviderException {
    ApplicationContext context =
            new ClassPathXmlApplicationContext(
                    "classpath:applicationContext-keystore-sample.xml");
    // test p12
    P12Manager p12 = context.getBean(P12Manager.class);
    ECKeyPair p12KeyPair = p12.getECKeyPair();
    assertEquals(p12KeyPair.getPrivateKey().toString(16), PRIVATE_KEY);
    assertEquals(p12KeyPair.getPublicKey().toString(16), PUBLIC_KEY);

    ECPublicKey publicKey = (ECPublicKey) p12.getPublicKey();
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));
    assertEquals(publicKeyValue.toString(16), PUBLIC_KEY);

    Credentials credentials = Credentials.create(p12KeyPair);
    assertEquals(credentials.getAddress(), ADDRESS);

    // test pem
    PEMManager pem = context.getBean(PEMManager.class);
    ECKeyPair pemKeyPair = pem.getECKeyPair();
    assertEquals(pemKeyPair.getPrivateKey().toString(16), PRIVATE_KEY);
    assertEquals(pemKeyPair.getPublicKey().toString(16), PUBLIC_KEY);

    Credentials credentialsPEM = Credentials.create(pemKeyPair);
    assertEquals(credentialsPEM.getAddress(), ADDRESS);
}
 
Example #20
Source File: GenCredential.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
private static ECKeyPair createECDSAKeyPair(String privKey) {
    try {
        BigInteger bigPrivKey = new BigInteger(privKey, 16);
        ECKeyPair keyPair = ECKeyPair.create(bigPrivKey);
        return keyPair;
    } catch (Exception e) {
        logger.error("create keypair of ECDSA failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #21
Source File: SM2Sign.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public static Sign.SignatureData sign(byte[] message, ECKeyPair ecKeyPair) {
    SM3Digest sm3Digest = new SM3Digest();
    BigInteger[] rs = null;
    byte[] r = null;
    byte[] s = null;
    byte[] pub = null;
    byte v = 0;
    byte[] messageHash = sm3Digest.hash(message);

    try {
        byte[] signByte = SM2Algorithm.sign(messageHash, ecKeyPair.getPrivateKey());
        logger.debug("signData:{}", signByte);
        // System.out.println("signData:" + Hex.toHexString(signByte));
        ASN1Sequence as = (ASN1Sequence) ASN1Primitive.fromByteArray(signByte);
        rs =
                new BigInteger[] {
                    ((ASN1Integer) as.getObjectAt(0)).getValue(),
                    ((ASN1Integer) as.getObjectAt(1)).getValue()
                };

    } catch (IOException ex) {
        logger.error("SM2 Sign ERROR");
    }
    if (rs != null) {
        r = SM2Algorithm.getEncoded(rs[0]);
        s = SM2Algorithm.getEncoded(rs[1]);

        /*System.out.println("publicKey:" + Hex.toHexString(Numeric.toBytesPadded(ecKeyPair.getPublicKey(),64)));
        System.out.println("publicKeyLen:" + ecKeyPair.getPublicKey().bitLength());
        System.out.println("privateKey:" + Hex.toHexString(Numeric.toBytesPadded(ecKeyPair.getPrivateKey(),32)));
        System.out.println("privateKey:" + ecKeyPair.getPrivateKey().bitLength());*/
        pub = Numeric.toBytesPadded(ecKeyPair.getPublicKey(), 64);
        logger.debug("SM2 SignPublic:{},SM2SignPublicLen:{}", Hex.toHexString(pub), pub.length);
        logger.debug("SM2 SignR:{},SM2SignRLen{}", Hex.toHexString(r), r.length);
        logger.debug("SM2 SignS:{},SM2SignSLen{}", Hex.toHexString(s), s.length);
        // System.out.println("SM2 SignPublic:" + Hex.toHexString(pub));
    }
    return new Sign.SignatureData(v, r, s, pub);
}
 
Example #22
Source File: SM2Sign.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * The new sm2 signature algorithm with better performance
 *
 * @param message
 * @param ecKeyPair
 * @return
 */
public static Sign.SignatureData sign2(byte[] message, ECKeyPair ecKeyPair) {

    SM2Signer sm2Signer = new SM2Signer();

    ECPrivateKeyParameters eCPrivateKeyParameters =
            new ECPrivateKeyParameters(ecKeyPair.getPrivateKey(), eCDomainParameters);

    sm2Signer.initWithCache(
            true,
            new ParametersWithID(new ParametersWithRandom(eCPrivateKeyParameters), identValue));

    org.bouncycastle.crypto.digests.SM3Digest sm3Digest =
            new org.bouncycastle.crypto.digests.SM3Digest();

    byte[] md = new byte[sm3Digest.getDigestSize()];
    sm3Digest.update(message, 0, message.length);
    sm3Digest.doFinal(md, 0);

    sm2Signer.update(md, 0, md.length);

    byte[] r = null;
    byte[] s = null;
    byte[] pub = null;

    try {
        BigInteger[] bigIntegers = sm2Signer.generateSignature2();

        pub = Numeric.toBytesPadded(ecKeyPair.getPublicKey(), 64);
        r = SM2Algorithm.getEncoded(bigIntegers[0]);
        s = SM2Algorithm.getEncoded(bigIntegers[1]);
    } catch (CryptoException e) {
        throw new RuntimeException(e);
    }

    return new Sign.SignatureData((byte) 0, r, s, pub);
}
 
Example #23
Source File: GenGmAccount.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * @author: fisco-dev
 * @function: generate private/public key with GuoMi algorithm
 * @param keyFile: file name used to store private/public/account info
 */
private static void GenGuoMiKeyAndStore(String keyFile) {

    System.out.println(
            "-------------------------------------------------------------------------------");
    System.out.println(
            "==========Generate (private key, public key, account) For Guomi randomly =======");
    ECKeyPair keyPair = GenCredential.createGuomiKeyPair();
    if (keyPair != null) {
        // deduce account according to public key
        String account = deduceAccountFromPublic(keyPair.getPublicKey());
        while (account == null || keyPair == null) {
            keyPair = GenCredential.createGuomiKeyPair();
            account = deduceAccountFromPublic(keyPair.getPublicKey());
        }
        System.out.println("===Generated Account:");
        System.out.println("* public key:" + (keyPair.getPublicKey().toString(16)));
        System.out.println("* private key :" + (keyPair.getPrivateKey().toString(16)));
        System.out.println("* account    :" + account);
        // save private/public/account result
        System.out.println("");
        System.out.println("==== SAVE PRIVATE/PUBLIC/ACCOUNT INFO ===");
        KeyInfo keyInfo =
                new KeyInfo(
                        keyPair.getPublicKey().toString(16),
                        keyPair.getPrivateKey().toString(16),
                        account);
        int result = keyInfo.storeKeyInfo(keyFile);
        if (result != RetCode.success)
            System.out.println("xxx STORE PRIVATE/PUBLIC/ACCOUNT INFO FAILED xxx");
        else System.out.println("=== STORE PIVATE/PUBLIC/ACCOUNT SUCCEED ===");
        System.out.println(
                "-------------------------------------------------------------------------------");
    } else {
        System.out.println("==== generate private/public key with GuoMi algorithm failed ====");
    }
}
 
Example #24
Source File: PEMManager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public ECKeyPair getECKeyPair()
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
                InvalidKeySpecException, NoSuchProviderException {
    PrivateKey privateKey = getPrivateKey();
    PublicKey publicKey = getPublicKey();

    KeyPair keyPair = new KeyPair(publicKey, privateKey);

    return ECKeyPair.create(keyPair);
}
 
Example #25
Source File: P12Manager.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
public ECKeyPair getECKeyPair()
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException,
                InvalidKeySpecException, NoSuchProviderException {
    PrivateKey privateKey = getPrivateKey();
    PublicKey publicKey = getPublicKey();

    KeyPair keyPair = new KeyPair(publicKey, privateKey);

    return ECKeyPair.create(keyPair);
}
 
Example #26
Source File: Web3SDKConnector.java    From WeEvent with Apache License 2.0 5 votes vote down vote up
public static Credentials getCredentials(FiscoConfig fiscoConfig) {
    log.debug("begin init Credentials");

    // read OSSCA account
    String privateKey;
    if (fiscoConfig.getWeb3sdkEncryptType().equals("SM2_TYPE")) {
        log.info("SM2_TYPE");
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource resource = resolver.getResource("classpath:" + fiscoConfig.getPemKeyPath());

            PEMManager pemManager = new PEMManager();
            pemManager.load(resource.getInputStream());
            ECKeyPair pemKeyPair = pemManager.getECKeyPair();
            privateKey = pemKeyPair.getPrivateKey().toString(16);
        } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException | InvalidKeySpecException | NoSuchProviderException | CertificateException | IOException e) {
            log.error("Init OSSCA Credentials failed", e);
            return null;
        }
    } else {
        privateKey = fiscoConfig.getAccount();
    }

    Credentials credentials = GenCredential.create(privateKey);
    if (null == credentials) {
        log.error("init Credentials failed");
        return null;
    }

    log.info("init Credentials success");
    return credentials;
}
 
Example #27
Source File: KeyPairUtils.java    From WeBASE-Sign with Apache License 2.0 5 votes vote down vote up
/**
 * create ecdsa keypair from privateKey
 * @param privateKey string
 * @return ECKeyPair ecdsa
 */
private ECKeyPair createECDSAKeyPair(String privateKey) {
    try {
        BigInteger bigPrivateKey = new BigInteger(privateKey, 16);
        ECKeyPair keyPair = ECKeyPair.create(bigPrivateKey);
        return keyPair;
    } catch (Exception e) {
        log.error("KeyPairUtils create keypair of ECDSA failed, error msg:" + e.getMessage());
        return null;
    }
}
 
Example #28
Source File: KeyStoreService.java    From WeBASE-Sign with Apache License 2.0 5 votes vote down vote up
/**
 * get Key by encrypt type
 * @param encryptType 1: guomi, 0: standard
 */
public KeyStoreInfo newKeyByType(int encryptType) throws BaseException {
    try {
        // support guomi
        ECKeyPair keyPair = keyPairUtils.createKeyPairByType(encryptType);
        return keyPair2KeyStoreInfo(keyPair, encryptType);
    } catch (Exception e) {
        log.error("createEcKeyPair fail.", e);
        throw new BaseException(CodeMessageEnums.SYSTEM_ERROR);
    }
}
 
Example #29
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * convert ECKeyPair to KeyStoreInfo.
 * default aes true
 */
private KeyStoreInfo keyPair2KeyStoreInfo(ECKeyPair keyPair, String userName) {
    String publicKey = Numeric
            .toHexStringWithPrefixZeroPadded(keyPair.getPublicKey(), PUBLIC_KEY_LENGTH_IN_HEX);
    String privateKey = Numeric.toHexStringNoPrefix(keyPair.getPrivateKey());
    String address = "0x" + Keys.getAddress(keyPair.getPublicKey());
    log.debug("publicKey:{} privateKey:{} address:{}", publicKey, privateKey, address);
    KeyStoreInfo keyStoreInfo = new KeyStoreInfo();
    keyStoreInfo.setPublicKey(publicKey);
    keyStoreInfo.setAddress(address);
    keyStoreInfo.setPrivateKey(privateKey);
    keyStoreInfo.setUserName(userName);
    return keyStoreInfo;
}
 
Example #30
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * get random credential to call transaction(not execute)
 * 2019/11/26 support guomi
 */
public Credentials getCredentialsForQuery() {
    log.debug("start getCredentialsForQuery. ");
    // create keyPair(support guomi)
    KeyStoreInfo keyStoreInfo;
    try {
        ECKeyPair keyPair = GenCredential.createKeyPair();
        keyStoreInfo = keyPair2KeyStoreInfo(keyPair, "");
    } catch (Exception e) {
        log.error("fail getCredentialsForQuery.", e);
        throw new FrontException("create random Credentials for query failed");
    }
    return GenCredential.create(keyStoreInfo.getPrivateKey());
}