Java源码示例:org.fisco.bcos.web3j.crypto.Keys
示例1
@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));
}
示例2
/**
* 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));
}
示例3
@Test
public void checkPubCorrect() throws IOException {
String defaultUserPrivateKey = "SzK9KCjpyVCW0T9K9r/MSlmcpkeckYKVn/D1X7fzzp18MM7yHhUHQugTxKXVJJY5XWOb4zZ79IXMBu77zmXsr0mCRnATZTUqFfWLX6tUBIw=";
String defaultPub = "0xc5d877bff9923af55f248fb48b8907dc7d00cac3ba19b4259aebefe325510af7bd0a75e9a8e8234aa7aa58bc70510ee4bef02201a86006196da4e771c47b71b4";
String defaultAddress = "0xf1585b8d0e08a0a00fff662e24d67ba95a438256";
Credentials credential = GenCredential.create(defaultUserPrivateKey);
System.out.println("private: ");
System.out.println(credential.getEcKeyPair().getPrivateKey());
System.out.println(Numeric.toHexStringNoPrefix(credential.getEcKeyPair().getPrivateKey()));
System.out.println("pub: ");
System.out.println(credential.getEcKeyPair().getPublicKey());
System.out.println("address: ");
System.out.println(credential.getAddress());
System.out.println(Keys.getAddress(credential.getEcKeyPair().getPublicKey()));
}
示例4
@Test
public void checkPubCorrect() throws IOException {
String defaultUserPrivateKeyAfterAes = "SzK9KCjpyVCW0T9K9r/MSlmcpkeckYKVn/D1X7fzzp18MM7yHhUHQugTxKXVJJY5XWOb4zZ79IXMBu77zmXsr0mCRnATZTUqFfWLX6tUBIw=";
String defaultPub = "0xc5d877bff9923af55f248fb48b8907dc7d00cac3ba19b4259aebefe325510af7bd0a75e9a8e8234aa7aa58bc70510ee4bef02201a86006196da4e771c47b71b4";
String defaultAddress = "0xf1585b8d0e08a0a00fff662e24d67ba95a438256";
String defaultUserPrivateKey = aesUtils.aesDecrypt(defaultUserPrivateKeyAfterAes);
System.out.println("decrypt aes");
System.out.println(defaultUserPrivateKey);
Credentials credential = GenCredential.create(defaultUserPrivateKey);
System.out.println("private: ");
System.out.println(credential.getEcKeyPair().getPrivateKey());
System.out.println(Numeric.toHexStringNoPrefix(credential.getEcKeyPair().getPrivateKey()));
System.out.println("pub: ");
System.out.println(credential.getEcKeyPair().getPublicKey());
System.out.println("address: ");
System.out.println(credential.getAddress());
System.out.println(Keys.getAddress(credential.getEcKeyPair().getPublicKey()));
}
示例5
/**
* 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);
}
}
示例6
/**
* 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;
}
示例7
/**
* init ecdsa key pair
* @return ECKeyPair ecdsa
*/
private ECKeyPair createECDSAKeyPair() {
try {
ECKeyPair keyPair = Keys.createEcKeyPair();
return keyPair;
} catch (Exception e) {
log.error("KeyPairUtils create keypair of ECDSA failed, error msg:" + e.getMessage());
return null;
}
}
示例8
/**
* create BCECPublicKey from publicKey and privateKey
*
* @param publicKey
* @return
*/
private BCECPublicKey createBCECPublicKey(BigInteger publicKey) {
// Handle public key.
String publicKeyValue =
Numeric.toHexStringNoPrefixZeroPadded(publicKey, Keys.PUBLIC_KEY_LENGTH_IN_HEX);
String prePublicKeyStr = publicKeyValue.substring(0, 64);
String postPublicKeyStr = publicKeyValue.substring(64);
SecP256K1Curve secP256K1Curve = new SecP256K1Curve();
SecP256K1Point secP256K1Point =
(SecP256K1Point)
secP256K1Curve.createPoint(
new BigInteger(prePublicKeyStr, 16),
new BigInteger(postPublicKeyStr, 16));
SecP256K1Point secP256K1PointG =
(SecP256K1Point)
secP256K1Curve.createPoint(ECCParams.POINTG_PRE, ECCParams.POINTG_POST);
ECDomainParameters domainParameters =
new ECDomainParameters(secP256K1Curve, secP256K1PointG, ECCParams.FACTOR_N);
ECPublicKeyParameters publicKeyParameters =
new ECPublicKeyParameters(secP256K1Point, domainParameters);
BCECPublicKey bcecPublicKey =
new BCECPublicKey(
"ECDSA",
publicKeyParameters,
ECCParams.ecNamedCurveSpec,
BouncyCastleProvider.CONFIGURATION);
return bcecPublicKey;
}
示例9
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;
}
}
示例10
public static void main(String[] args) throws Exception {
// init the Service
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Service service = context.getBean(Service.class);
service.setGroupId(Integer.parseInt(args[0]));
service.run(); // run the daemon service
// init the client keys
keyPair = Keys.createEcKeyPair();
credentials = GenCredential.create(keyPair.getPrivateKey().toString(16));
logger.info("-----> start test !");
logger.info("init AOMP ChannelEthereumService");
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
channelEthereumService.setTimeout(5 * 1000);
try {
web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
} catch (Exception e) {
System.out.println("\nPlease provide groupID in the first paramters");
System.exit(0);
}
if (args.length > 1) {
if ("deploy".equals(args[1])) {
deployTableTest();
} else {
String[] params = new String[args.length - 1];
for (int i = 0; i < params.length; i++) params[i] = args[i + 1];
testTableTest(params);
}
} else {
System.out.println(
"\nPlease choose follow commands:\n deploy, create, insert, select, update or remove");
}
System.exit(0);
}
示例11
public static void main(String[] args) throws Exception {
// init the Service
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Service service = context.getBean(Service.class);
service.setGroupId(Integer.parseInt(args[0]));
service.run(); // run the daemon service
// init the client keys
keyPair = Keys.createEcKeyPair();
credentials = Credentials.create(keyPair);
logger.info("-----> start test !");
logger.info("init AOMP ChannelEthereumService");
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
try {
web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
} catch (Exception e) {
System.out.println("\nPlease provide groupID in the first paramters");
System.exit(0);
}
if (args.length > 1) {
if ("deploy".equals(args[1])) {
deployOk();
} else {
String[] params = new String[args.length - 1];
for (int i = 0; i < params.length; i++) params[i] = args[i + 1];
testOk(params);
}
} else {
System.out.println("\nPlease choose follow commands:\n deploy, trans or get");
}
System.exit(0);
}
示例12
public static void main(String[] args) throws Exception {
// init the Service
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Service service = context.getBean(Service.class);
service.setGroupId(Integer.parseInt(args[0]));
service.run(); // run the daemon service
// init the client keys
keyPair = Keys.createEcKeyPair();
credentials = Credentials.create(keyPair);
logger.info("-----> start test !");
logger.info("init AOMP ChannelEthereumService");
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
try {
web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
} catch (Exception e) {
System.out.println("\nPlease provide groupID in the first paramters");
System.exit(0);
}
if (args.length > 1) {
if ("deploy".equals(args[1])) {
deploymixContract();
} else {
String[] params = new String[args.length - 1];
for (int i = 0; i < params.length; i++) params[i] = args[i + 1];
testMixContract(params);
}
} else {
System.out.println(
"\nPlease choose follow commands:\n deploy, create, insert, select, update or remove");
}
System.exit(0);
}
示例13
public static void main(String[] args) throws Exception {
// init the Service
ApplicationContext context =
new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
Service service = context.getBean(Service.class);
service.setGroupId(Integer.parseInt(args[0]));
service.run(); // run the daemon service
// init the client keys
keyPair = Keys.createEcKeyPair();
credentials = GenCredential.create(keyPair.getPrivateKey().toString(16));
logger.info("-----> start test !");
logger.info("init AOMP ChannelEthereumService");
ChannelEthereumService channelEthereumService = new ChannelEthereumService();
channelEthereumService.setChannelService(service);
channelEthereumService.setTimeout(5 * 1000);
try {
web3j = Web3j.build(channelEthereumService, Integer.parseInt(args[0]));
} catch (Exception e) {
System.out.println("\nPlease provide groupID in the first parameters");
System.exit(0);
}
if (args.length > 1) {
if ("deploy".equals(args[1])) {
deployTableTest();
} else {
String[] params = new String[args.length - 1];
for (int i = 0; i < params.length; i++) params[i] = args[i + 1];
testTableTest(params);
}
} else {
System.out.println(
"\nPlease choose follow commands:\n deploy, create, insert, select, update or remove");
}
System.exit(0);
}
示例14
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;
}
示例15
public String verifySignedMessage(String message, String signatureData) throws SignatureException {
Sign.SignatureData signatureData1 = Tools.stringToSignatureData(signatureData);
try {
return "0x" + Keys.getAddress(Sign.signedMessageToKey(message.getBytes(), signatureData1));
} catch (SignatureException e) {
throw e;
}
}
示例16
public static String getAddress(PublicKey key) {
String publicKey = getPublicKeyString(key);
return Keys.getAddress(publicKey);
}
示例17
/**
* get address from public key
* 2019/11/27 support guomi
* @param publicKey
* @return
*/
public static String getAddressByPublicKey(String publicKey) {
String address = "0x" + Keys.getAddress(publicKey);
return address;
}