Java Code Examples for org.fisco.bcos.web3j.utils.Numeric#toHexStringNoPrefix()

The following examples show how to use org.fisco.bcos.web3j.utils.Numeric#toHexStringNoPrefix() . 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: UserService.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
/**
 * import pem file to import privateKey
 * @param reqImportPem
 * @return userId
 */
public Integer importPem(ReqImportPem reqImportPem) {
    PEMManager pemManager = new PEMManager();
    String privateKey;
    try {
        String pemContent = reqImportPem.getPemContent();
        pemManager.load(new ByteArrayInputStream(pemContent.getBytes()));
        privateKey = Numeric.toHexStringNoPrefix(pemManager.getECKeyPair().getPrivateKey());
    }catch (Exception e) {
        log.error("importKeyStoreFromPem error:[]", e);
        throw new NodeMgrException(ConstantCode.PEM_CONTENT_ERROR);
    }
    // pem's privateKey encoded here
    String privateKeyEncoded = NodeMgrTools.encodedBase64Str(privateKey);

    // store local and save in sign
    Integer userId = addUserInfo(reqImportPem.getGroupId(), reqImportPem.getUserName(),
            reqImportPem.getDescription(), reqImportPem.getUserType(), privateKeyEncoded);
    return userId;
}
 
Example 2
Source File: ImportCertTest.java    From WeBASE-Node-Manager with Apache License 2.0 6 votes vote down vote up
@Test
public void testPubAddress() throws IOException, CertificateException, IllegalAccessException, InstantiationException {
    /**
     * @param: nodeCert
     * 只有节点证书才是ECC椭圆曲线,获取pub的方法和区块链的一致
     * 其余的agency chain 的crt都是rsa方法,使用大素数方法计算,不一样
     */
    // need crt file
    InputStream node = new ClassPathResource("node.crt").getInputStream();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate nodeCert = (X509Certificate) cf.generateCertificate(node);
    // rsa算法的公钥和ecc的不一样
    ECPublicKeyImpl pub = (ECPublicKeyImpl) nodeCert.getPublicKey();
    byte[] pubBytes = pub.getEncodedPublicValue();
    String publicKey = Numeric.toHexStringNoPrefix(pubBytes);
    String address = Keys.getAddress(publicKey);
    byte[] addByteArray = Keys.getAddress(pubBytes);
    System.out.println("byte[] : pub ");
    System.out.println(pubBytes);
    System.out.println("====================================");
    System.out.println(publicKey); // 04e5e7efc9e8d5bed699313d5a0cd5b024b3c11811d50473b987b9429c2f6379742c88249a7a8ea64ab0e6f2b69fb8bb280454f28471e38621bea8f38be45bc42d
    System.out.println("byte[] to pub to address ");
    System.out.println(address); // f7b2c352e9a872d37a427601c162671202416dbc
    System.out.println("包含开头的04");
    System.out.println(byteToHex(addByteArray));
}
 
Example 3
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 4
Source File: CertTools.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
/**
 * getPublicKey
 * @param key
 * @return String
 */
public static String getPublicKeyString(PublicKey key) {
    //        ECPublicKeyImpl pub = (ECPublicKeyImpl) key;
    BCECPublicKey bcecPublicKey = (BCECPublicKey) key;
    byte[] bcecPubBytes = bcecPublicKey.getEncoded();
    String publicKey = Numeric.toHexStringNoPrefix(bcecPubBytes);
    publicKey = publicKey.substring(publicKey.length() - PUBLIC_KEY_IN_HEX_LENGTH); //只取后128位
    return publicKey;
}
 
Example 5
Source File: BCCertTest.java    From WeBASE-Node-Manager with Apache License 2.0 5 votes vote down vote up
@Test
public void testGmCertPublicKey() throws CertificateException {
    String crtContent = CertTools.addCertHeadAndTail(standardNodeCrt);
    InputStream is2 = new ByteArrayInputStream(crtContent.getBytes());
    CertificateFactory factory = new CertificateFactory();
    X509Certificate certificate = (X509Certificate)factory.engineGenerateCertificate(is2);
    BCECPublicKey bcecPublicKey = (BCECPublicKey) certificate.getPublicKey();
    System.out.println(bcecPublicKey.getEncoded());
    byte[] bcecPubBytes = bcecPublicKey.getEncoded();
    String publicKeyBC = Numeric.toHexStringNoPrefix(bcecPubBytes);
    publicKeyBC = publicKeyBC.substring(publicKeyBC.length() - 128); //证书byte[]为130位,只取128位,去除开头的04标记位
    System.out.println(publicKeyBC); // 3056301006072a8648ce3d020106052b8104000a034200047853896f4e4b0891c5954d5b3f77325e39720718ec8e1a5608e4e8774bddb0dcdd63a98dad6c276603173674c477f2269e7abb1e7b8b1e9b9c852c27ad7c0814

    //========== import java.security.cert.CertificateFactory;
    /** @Deprecated */
    InputStream is = new ByteArrayInputStream(crtContent.getBytes());
    java.security.cert.CertificateFactory cf = java.security.cert.CertificateFactory.getInstance("X.509");
    X509Certificate cert2 = (X509Certificate) cf.generateCertificate(is);
    PublicKey publicKeyObject = cert2.getPublicKey();
    // this.key = ECUtil.encodePoint(var1, var2.getCurve());
    ECPublicKeyImpl pub = (ECPublicKeyImpl) publicKeyObject;
    byte[] pubBytes = pub.getEncodedPublicValue();
    String publicKey = Numeric.toHexStringNoPrefix(pubBytes);
    publicKey = publicKey.substring(publicKey.length() - 128); //证书byte[]为130位,只取128位,去除开头的04标记位
    System.out.println(publicKey);// 7853896f4e4b0891c5954d5b3f77325e39720718ec8e1a5608e4e8774bddb0dcdd63a98dad6c276603173674c477f2269e7abb1e7b8b1e9b9c852c27ad7c0814

    Assert.isTrue(publicKeyBC.equals(publicKey), "public key not equal");
    Assert.isTrue(publicKeyBC.equals(CertTools.getPublicKeyString(bcecPublicKey)), "public key not equal");
}
 
Example 6
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 7
Source File: KeyStoreService.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
/**
 * import keystore info from pem file's content
 * @param pemContent
 * @param userName
 * @return
 */
public KeyStoreInfo importKeyStoreFromPem(String pemContent, String userName) {
    PEMManager pemManager = new PEMManager();
    String privateKey;
    try {
        pemManager.load(new ByteArrayInputStream(pemContent.getBytes()));
        privateKey = Numeric.toHexStringNoPrefix(pemManager.getECKeyPair().getPrivateKey());
    }catch (Exception e) {
        log.error("importKeyStoreFromPem error:[]", e);
        throw new FrontException(ConstantCode.PEM_CONTENT_ERROR);
    }
    // to store local
    return importFromPrivateKey(privateKey, userName);
}
 
Example 8
Source File: KeyStoreServiceTest.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
@Test
public void testLoadP12() throws UnrecoverableKeyException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException, CertificateException, IOException {
	P12Manager p12Manager = new P12Manager();
	p12Manager.setP12File("0x6399bda67f0ae8d1fdd997a885b8aee32a0c9696.p12");
	p12Manager.setPassword("123");
	p12Manager.load();
	// c5658bbb9b905345e7c057690ec6f50c06dada711d1086820980496b4954fbc7
	String privateKey = Numeric.toHexStringNoPrefix(p12Manager.getECKeyPair().getPrivateKey());
	System.out.println("load private key: " + privateKey);
	String address = GenCredential.create(privateKey).getAddress();
	System.out.println("address: " + address);
	Assert.assertTrue("pri error", address.equals("0x6399bda67f0ae8d1fdd997a885b8aee32a0c9696"));
}
 
Example 9
Source File: KeyStoreService.java    From WeBASE-Sign with Apache License 2.0 5 votes vote down vote up
/**
 * keyPair to keyStoreInfo.
 * 1.3.0 use AddressUtil to get address instead of using Keys.java
 * @param encryptType 1: guomi, 0: standard
 */
private KeyStoreInfo keyPair2KeyStoreInfo(ECKeyPair keyPair, int encryptType) {
    String publicKey = Numeric
            .toHexStringWithPrefixZeroPadded(keyPair.getPublicKey(), PUBLIC_KEY_LENGTH_IN_HEX);
    String privateKey = Numeric.toHexStringNoPrefix(keyPair.getPrivateKey());
    String address = "0x" + addressUtils.getAddressByType(keyPair.getPublicKey(), encryptType);
    log.debug("publicKey:{} privateKey:{} address:{}", publicKey, privateKey, address);
    KeyStoreInfo keyStoreInfo = new KeyStoreInfo();
    keyStoreInfo.setPublicKey(publicKey);
    keyStoreInfo.setPrivateKey(aesUtils.aesEncrypt(privateKey));
    keyStoreInfo.setAddress(address);
    return keyStoreInfo;
}
 
Example 10
Source File: TypeEncoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static String encodeNumeric(NumericType numericType) {
    byte[] rawValue = toByteArray(numericType);
    byte paddingValue = getPaddingValue(numericType);
    byte[] paddedRawValue = new byte[MAX_BYTE_LENGTH];
    if (paddingValue != 0) {
        for (int i = 0; i < paddedRawValue.length; i++) {
            paddedRawValue[i] = paddingValue;
        }
    }

    System.arraycopy(
            rawValue, 0, paddedRawValue, MAX_BYTE_LENGTH - rawValue.length, rawValue.length);
    return Numeric.toHexStringNoPrefix(paddedRawValue);
}
 
Example 11
Source File: TypeEncoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static String encodeBool(Bool value) {
    byte[] rawValue = new byte[MAX_BYTE_LENGTH];
    if (value.getValue()) {
        rawValue[rawValue.length - 1] = 1;
    }
    return Numeric.toHexStringNoPrefix(rawValue);
}
 
Example 12
Source File: TypeEncoder.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
static String encodeBytes(BytesType bytesType) {
    byte[] value = bytesType.getValue();
    int length = value.length;
    int mod = length % MAX_BYTE_LENGTH;

    byte[] dest;
    if (mod != 0) {
        int padding = MAX_BYTE_LENGTH - mod;
        dest = new byte[length + padding];
        System.arraycopy(value, 0, dest, 0, length);
    } else {
        dest = value;
    }
    return Numeric.toHexStringNoPrefix(dest);
}
 
Example 13
Source File: KeysTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAddressSmallPublicKey() {
    byte[] address =
            Keys.getAddress(
                    Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
    String expected = Numeric.toHexStringNoPrefix(address);

    assertThat(Keys.getAddress("0x1234"), equalTo(expected));
}
 
Example 14
Source File: KeysTest.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetAddressZeroPadded() {
    byte[] address =
            Keys.getAddress(
                    Numeric.toBytesPadded(BigInteger.valueOf(0x1234), Keys.PUBLIC_KEY_SIZE));
    String expected = Numeric.toHexStringNoPrefix(address);

    String value = "1234";
    assertThat(
            Keys.getAddress(
                    "0x"
                            + Strings.zeros(Keys.PUBLIC_KEY_LENGTH_IN_HEX - value.length())
                            + value),
            equalTo(expected));
}