org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey Java Examples

The following examples show how to use org.bouncycastle.jcajce.provider.asymmetric.ec.BCECPrivateKey. 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: BlockDataGenerator.java    From besu with Apache License 2.0 6 votes vote down vote up
private SECP256K1.KeyPair generateKeyPair() {
  final java.security.KeyPair rawKeyPair = keyPairGenerator.generateKeyPair();
  final BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  final BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  final BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  final byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  final BigInteger publicKeyValue =
      new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new SECP256K1.KeyPair(
      SECP256K1.PrivateKey.create(privateKeyValue), SECP256K1.PublicKey.create(publicKeyValue));
}
 
Example #2
Source File: ECKeyPair.java    From web3sdk with Apache License 2.0 6 votes vote down vote up
/**
 * create ECKeyPair from KeyPair
 *
 * @param keyPair
 * @return
 */
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    ECKeyPair ecKeyPair = new ECKeyPair(privateKeyValue, publicKeyValue);
    return ecKeyPair;
}
 
Example #3
Source File: CryptoUtil.java    From julongchain with Apache License 2.0 6 votes vote down vote up
/**
 * 从pem私钥文件中获取sk
 * @return
 */
public static byte[] getPrivateKey(String filePath)throws Exception{
    File inFile = new File(filePath);
    long fileLen = inFile.length();
    Reader reader = null;
    PemObject pemObject = null;
    reader = new FileReader(inFile);
    char[] content = new char[(int) fileLen];
    reader.read(content);
    String str = new String(content);
    String privateKeyPEM = str.replace("-----BEGIN PRIVATE KEY-----\n", "")
            .replace("-----END PRIVATE KEY-----", "").replace("\n", "");
    Security.addProvider(new BouncyCastleProvider());
    KeyFactory keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(privateKeyPEM) );
    BCECPrivateKey priKey = (BCECPrivateKey)keyf.generatePrivate(priPKCS8);
    return priKey.getD().toByteArray();
}
 
Example #4
Source File: SECP256K1.java    From cava with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair.
 *
 * Entropy for the generation is drawn from {@link SecureRandom}.
 *
 * @return A new keypair.
 */
public static KeyPair random() {
  java.security.KeyPair rawKeyPair = Parameters.KEY_PAIR_GENERATOR.generateKeyPair();
  BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(SecretKey.fromInteger(privateKeyValue), PublicKey.fromInteger(publicKeyValue));
}
 
Example #5
Source File: Wallet.java    From blockchain-java with Apache License 2.0 6 votes vote down vote up
/**
 * 初始化钱包
 */
private void initWallet() {
    try {
        KeyPair keyPair = newECKeyPair();
        BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
        BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

        byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);

        this.setPrivateKey(privateKey);
        this.setPublicKey(publicKeyBytes);
    } catch (Exception e) {
        log.error("Fail to init wallet ! ", e);
        throw new RuntimeException("Fail to init wallet ! ", e);
    }
}
 
Example #6
Source File: SM2UtilTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testGenerateBCECKeyPair() {
    try {
        KeyPair keyPair = SM2Util.generateKeyPair();
        ECPrivateKeyParameters priKey = BCECUtil.convertPrivateKeyToParameters((BCECPrivateKey) keyPair.getPrivate());
        ECPublicKeyParameters pubKey = BCECUtil.convertPublicKeyToParameters((BCECPublicKey) keyPair.getPublic());

        byte[] sign = SM2Util.sign(priKey, WITH_ID, SRC_DATA);
        boolean flag = SM2Util.verify(pubKey, WITH_ID, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }

        sign = SM2Util.sign(priKey, SRC_DATA);
        flag = SM2Util.verify(pubKey, SRC_DATA, sign);
        if (!flag) {
            Assert.fail("verify failed");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #7
Source File: BCECUtilTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testECPrivateKeyPKCS8() {
    try {
        AsymmetricCipherKeyPair keyPair = SM2Util.generateKeyPairParameter();
        ECPrivateKeyParameters priKeyParams = (ECPrivateKeyParameters) keyPair.getPrivate();
        ECPublicKeyParameters pubKeyParams = (ECPublicKeyParameters) keyPair.getPublic();
        byte[] pkcs8Bytes = BCECUtil.convertECPrivateKeyToPKCS8(priKeyParams, pubKeyParams);
        BCECPrivateKey priKey = BCECUtil.convertPKCS8ToECPrivateKey(pkcs8Bytes);

        byte[] sign = SM2Util.sign(priKey, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA);
        System.out.println("SM2 sign with withId result:\n" + ByteUtils.toHexString(sign));
        boolean flag = SM2Util.verify(pubKeyParams, GMBaseTest.WITH_ID, GMBaseTest.SRC_DATA, sign);
        if (!flag) {
            Assert.fail("[withId] verify failed");
        }
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}
 
Example #8
Source File: SM2PrivateKeyTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testEncoded() throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException {
    KeyPair keyPair = SM2Util.generateKeyPair();
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();
    SM2PublicKey sm2PublicKey = new SM2PublicKey(publicKey.getAlgorithm(), publicKey);
    SM2PrivateKey sm2PrivateKey1 = new SM2PrivateKey(privateKey, publicKey);
    SM2PrivateKey sm2PrivateKey2 = new SM2PrivateKey(privateKey, sm2PublicKey);
    String nativePriDER = ByteUtils.toHexString(privateKey.getEncoded());
    String sm2PriDER1 = ByteUtils.toHexString(sm2PrivateKey1.getEncoded());
    String sm2PriDER2 = ByteUtils.toHexString(sm2PrivateKey2.getEncoded());
    if (nativePriDER.equalsIgnoreCase(sm2PriDER1)) {
        Assert.fail();
    }
    if (!sm2PriDER1.equalsIgnoreCase(sm2PriDER2)) {
        Assert.fail();
    }
    System.out.println("Native EC Private Key DER:\n" + nativePriDER.toUpperCase());
    System.out.println("SM2 EC Private Key DER:\n" + sm2PriDER1.toUpperCase());
}
 
Example #9
Source File: SM2X509CertMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testMakeCertificate() {
    try {
        KeyPair subKP = SM2Util.generateKeyPair();
        X500Name subDN = buildSubjectDN();
        SM2PublicKey sm2SubPub = new SM2PublicKey(subKP.getPublic().getAlgorithm(),
            (BCECPublicKey) subKP.getPublic());
        byte[] csr = CommonUtil.createCSR(subDN, sm2SubPub, subKP.getPrivate(),
            SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2).getEncoded();
        savePriKey("target/test.sm2.pri", (BCECPrivateKey) subKP.getPrivate(),
            (BCECPublicKey) subKP.getPublic());
        SM2X509CertMaker certMaker = buildCertMaker();
        X509Certificate cert = certMaker.makeSSLEndEntityCert(csr);
        FileUtil.writeFile("target/test.sm2.cer", cert.getEncoded());
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #10
Source File: SM2PfxMakerTest.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
@Test
public void testPfxSign() {
    //先生成一个pfx
    testMakePfx();

    try {
        byte[] pkcs12 = FileUtil.readFile(TEST_PFX_FILENAME);
        BCECPublicKey publicKey = SM2CertUtil.getPublicKeyFromPfx(pkcs12, TEST_PFX_PASSWD);
        BCECPrivateKey privateKey = SM2CertUtil.getPrivateKeyFromPfx(pkcs12, TEST_PFX_PASSWD);

        String srcData = "1234567890123456789012345678901234567890";
        byte[] sign = SM2Util.sign(privateKey, srcData.getBytes());
        boolean flag = SM2Util.verify(publicKey, srcData.getBytes(), sign);
        if (!flag) {
            Assert.fail();
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #11
Source File: SM2CertUtil.java    From gmhelper with Apache License 2.0 6 votes vote down vote up
public static BCECPrivateKey getPrivateKeyFromPfx(byte[] pfxDER, String passwd) throws Exception {
    InputDecryptorProvider inputDecryptorProvider = new JcePKCSPBEInputDecryptorProviderBuilder()
        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(passwd.toCharArray());
    PKCS12PfxPdu pfx = new PKCS12PfxPdu(pfxDER);

    ContentInfo[] infos = pfx.getContentInfos();
    if (infos.length != 2) {
        throw new Exception("Only support one pair ContentInfo");
    }

    for (int i = 0; i != infos.length; i++) {
        if (!infos[i].getContentType().equals(PKCSObjectIdentifiers.encryptedData)) {
            PKCS12SafeBagFactory dataFact = new PKCS12SafeBagFactory(infos[i]);
            PKCS12SafeBag[] bags = dataFact.getSafeBags();
            PKCS8EncryptedPrivateKeyInfo encInfo = (PKCS8EncryptedPrivateKeyInfo) bags[0].getBagValue();
            PrivateKeyInfo info = encInfo.decryptPrivateKeyInfo(inputDecryptorProvider);
            BCECPrivateKey privateKey = BCECUtil.convertPKCS8ToECPrivateKey(info.getEncoded());
            return privateKey;
        }
    }

    throw new Exception("Not found Private Key in this pfx");
}
 
Example #12
Source File: Account.java    From ontology-java-sdk with GNU Lesser General Public License v3.0 6 votes vote down vote up
public byte[] serializePrivateKey() throws Exception {
    switch (this.keyType) {
        case ECDSA:
        case SM2:
            BCECPrivateKey pri = (BCECPrivateKey) this.privateKey;
            String curveName = Curve.valueOf(pri.getParameters().getCurve()).toString();
            byte[] d = new byte[32];
            if (pri.getD().toByteArray().length == 33) {
                System.arraycopy(pri.getD().toByteArray(), 1, d, 0, 32);
            } else if (pri.getD().toByteArray().length == 31){
                d[0] = 0;
                System.arraycopy(pri.getD().toByteArray(), 0, d, 1, 31);
            } else {
                return pri.getD().toByteArray();
            }
            return d;
        default:
            // should not reach here
            throw new Exception(ErrorCode.UnknownKeyType);
    }
}
 
Example #13
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new keypair.
 *
 * Entropy for the generation is drawn from {@link SecureRandom}.
 *
 * @return A new keypair.
 */
public static KeyPair random() {
  java.security.KeyPair rawKeyPair = Parameters.KEY_PAIR_GENERATOR.generateKeyPair();
  BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(SecretKey.fromInteger(privateKeyValue), PublicKey.fromInteger(publicKeyValue));
}
 
Example #14
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 6 votes vote down vote up
/**
 * 从本地导入私钥
 * 
 * @param path
 * @return
 */
public BigInteger importPrivateKey(String path) {
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		byte[] dest = new byte[32];
		System.arraycopy(decode, 36, dest, 0, 32);
		System.out.println(Util.bytesToHexString(dest));
		PrivateKey key = SecureUtil.generatePrivateKey("SM2", decode);
		System.out.println("[importPrivateKey]alg:" + key.getAlgorithm());
		System.out.println("privatekey:" + ((BCECPrivateKey) key).getD());
		BigInteger b = ((BCECPrivateKey) key).getD();
		ECPoint g2 = ((BCECPrivateKey) key).getParameters().getG();
		System.out.println("[importPrivateKey]x:" + Util.bytesToHexString(g2.getXCoord().getEncoded()));
		System.out.println("[importPrivateKey]y:" + Util.bytesToHexString(g2.getYCoord().getEncoded()));
		System.out.println(Util.bytesToHexString(b.toByteArray()));
		return b;
	} catch (Exception e) {
		e.printStackTrace();
	}
	return null;
}
 
Example #15
Source File: SECP256K1.java    From besu with Apache License 2.0 6 votes vote down vote up
public static KeyPair generate() {
  final java.security.KeyPair rawKeyPair = KEY_PAIR_GENERATOR.generateKeyPair();
  final BCECPrivateKey privateKey = (BCECPrivateKey) rawKeyPair.getPrivate();
  final BCECPublicKey publicKey = (BCECPublicKey) rawKeyPair.getPublic();

  final BigInteger privateKeyValue = privateKey.getD();

  // Ethereum does not use encoded public keys like bitcoin - see
  // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
  // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
  final byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
  final BigInteger publicKeyValue =
      new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

  return new KeyPair(PrivateKey.create(privateKeyValue), PublicKey.create(publicKeyValue));
}
 
Example #16
Source File: ECKeyPair.java    From blockchain with Apache License 2.0 5 votes vote down vote up
public ECKeyPair(PrivateKey privateKey, PublicKey publicKey) {
    this.privateKey = privateKey;
    this.publicKey = publicKey;
    // 生成 BigInteger 形式的公钥和私钥
    BCECPrivateKey bcecPrivateKey = (BCECPrivateKey) this.privateKey;
    BCECPublicKey bcecPublicKey = (BCECPublicKey) this.publicKey;
    // 分别计算公钥和私钥的值
    BigInteger privateKeyValue = bcecPrivateKey.getD();
    byte[] publicKeyBytes = bcecPublicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue = new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));
    this.privateKeyValue = privateKeyValue;
    this.publicKeyValue = publicKeyValue;
}
 
Example #17
Source File: BCECUtil.java    From littleca with Apache License 2.0 5 votes vote down vote up
/**
 * openssl i2d_ECPrivateKey函数生成的DER编码的ecc私钥是:PKCS1标准的、带有EC_GROUP、带有公钥的,
 * 这个工具函数的主要目的就是为了使Java程序能够“识别”openssl生成的ECC私钥
 *
 * @param encodedKey
 * @return
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws InvalidKeySpecException
 */
public static ECPrivateKeyParameters convertPkcs1DerToEcPriKey(byte[] encodedKey)
    throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PKCS8EncodedKeySpec peks = new PKCS8EncodedKeySpec(encodedKey);
    KeyFactory kf = KeyFactory.getInstance(ALGO_NAME_EC, BouncyCastleProvider.PROVIDER_NAME);
    BCECPrivateKey privateKey = (BCECPrivateKey) kf.generatePrivate(peks);
    ECParameterSpec ecParameterSpec = privateKey.getParameters();
    ECDomainParameters ecDomainParameters = new ECDomainParameters(ecParameterSpec.getCurve(),
        ecParameterSpec.getG(), ecParameterSpec.getN(), ecParameterSpec.getH());
    ECPrivateKeyParameters priKey = new ECPrivateKeyParameters(privateKey.getD(),
        ecDomainParameters);
    return priKey;
}
 
Example #18
Source File: Sm2KeyPairImpl.java    From littleca with Apache License 2.0 5 votes vote down vote up
public Sm2KeyPairImpl() {
	  try {
		  KeyPairGenerator g = KeyPairGenerator.getInstance("EC", "BC");
		  //参见 SM2P256V1Curve GMObjectIdentifiers
		  g.initialize(new ECNamedCurveGenParameterSpec("sm2p256v1"));
		  KeyPair p = g.generateKeyPair();
	
		  PrivateKey privKey = p.getPrivate();
		  PublicKey pubKey = p.getPublic();
		  publicKey=new Sm2PublicKeyImpl( (BCECPublicKey) pubKey);
		  privateKey=new Sm2PrivateKeyImpl((BCECPrivateKey) privKey);
	} catch (Exception e) {
		throw new RuntimeException(e);
	}
}
 
Example #19
Source File: Sm2KeyPairImpl.java    From littleca with Apache License 2.0 5 votes vote down vote up
public Sm2KeyPairImpl(boolean selfgen) {
	SecureRandom random = new SecureRandom();
	ECKeyGenerationParameters keyGenerationParams = new ECKeyGenerationParameters(DOMAIN_PARAMS, random);
	ECKeyPairGenerator keyGen = new ECKeyPairGenerator();
	keyGen.init(keyGenerationParams);
	AsymmetricCipherKeyPair keyPair = keyGen.generateKeyPair();
	ECPrivateKeyParameters priKey = (ECPrivateKeyParameters) keyPair.getPrivate();
	ECPublicKeyParameters pubKey = (ECPublicKeyParameters) keyPair.getPublic();
	ECDomainParameters domainParams = priKey.getParameters();
	ECParameterSpec spec = new ECParameterSpec(domainParams.getCurve(), domainParams.getG(), domainParams.getN(),
			domainParams.getH());
	BCECPublicKey bcecPublicKey = new BCECPublicKey(ALGO_NAME_EC, pubKey, spec, BouncyCastleProvider.CONFIGURATION);
	publicKey = new Sm2PublicKeyImpl(bcecPublicKey);
	privateKey = new Sm2PrivateKeyImpl(new BCECPrivateKey(ALGO_NAME_EC, priKey, bcecPublicKey, spec, BouncyCastleProvider.CONFIGURATION));
}
 
Example #20
Source File: Blockchain.java    From blockchain-java with Apache License 2.0 5 votes vote down vote up
/**
 * 进行交易签名
 *
 * @param tx         交易数据
 * @param privateKey 私钥
 */
public void signTransaction(Transaction tx, BCECPrivateKey privateKey) throws Exception {
    // 先来找到这笔新的交易中,交易输入所引用的前面的多笔交易的数据
    Map<String, Transaction> prevTxMap = Maps.newHashMap();
    for (TXInput txInput : tx.getInputs()) {
        Transaction prevTx = this.findTransaction(txInput.getTxId());
        prevTxMap.put(Hex.encodeHexString(txInput.getTxId()), prevTx);
    }
    tx.sign(privateKey, prevTxMap);
}
 
Example #21
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Produce a string rendering of the ECKey INCLUDING the private key.
 * Unless you absolutely need the private key it is better for security reasons to just use toString().
 *
 * @return -
 */
public String toStringWithPrivate() {
    StringBuilder b = new StringBuilder();
    b.append(toString());
    if (privKey != null && privKey instanceof BCECPrivateKey) {
        b.append(" priv:").append(Hex.toHexString(((BCECPrivateKey) privKey).getD().toByteArray()));
    }
    return b.toString();
}
 
Example #22
Source File: ECKeyPair.java    From etherscan-explorer with GNU General Public License v3.0 5 votes vote down vote up
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    return new ECKeyPair(privateKeyValue, publicKeyValue);
}
 
Example #23
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Decrypt cipher by AES in SIC(also know as CTR) mode
 *
 * @param cipher -proper cipher
 * @return decrypted cipher, equal length to the cipher.
 * @deprecated should not use EC private scalar value as an AES key
 */
public byte[] decryptAES(byte[] cipher) {

    if (privKey == null) {
        throw new MissingPrivateKeyException();
    }
    if (!(privKey instanceof BCECPrivateKey)) {
        throw new UnsupportedOperationException("Cannot use the private key as an AES key");
    }


    AESFastEngine engine = new AESFastEngine();
    SICBlockCipher ctrEngine = new SICBlockCipher(engine);

    KeyParameter key = new KeyParameter(BigIntegers.asUnsignedByteArray(((BCECPrivateKey) privKey).getD()));
    ParametersWithIV params = new ParametersWithIV(key, new byte[16]);

    ctrEngine.init(false, params);

    int i = 0;
    byte[] out = new byte[cipher.length];
    while (i < cipher.length) {
        ctrEngine.processBlock(cipher, i, out, i);
        i += engine.getBlockSize();
        if (cipher.length - i < engine.getBlockSize())
            break;
    }

    // process left bytes
    if (cipher.length - i > 0) {
        byte[] tmpBlock = new byte[16];
        System.arraycopy(cipher, i, tmpBlock, 0, cipher.length - i);
        ctrEngine.processBlock(tmpBlock, 0, tmpBlock, 0);
        System.arraycopy(tmpBlock, 0, out, i, cipher.length - i);
    }

    return out;
}
 
Example #24
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Gets the private key in the form of an integer field element. The public key is derived by performing EC
 * point addition this number of times (i.e. point multiplying).
 *
 * @return -
 * @throws IllegalStateException if the private key bytes are not available.
 */
public BigInteger getPrivKey() {
    if (privKey == null) {
        throw new MissingPrivateKeyException();
    } else if (privKey instanceof BCECPrivateKey) {
        return ((BCECPrivateKey) privKey).getD();
    } else {
        throw new MissingPrivateKeyException();
    }
}
 
Example #25
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a 32 byte array containing the private key, or null if the key is encrypted or public only
 *
 * @return -
 */
public byte[] getPrivKeyBytes() {
    if (privKey == null) {
        return null;
    } else if (privKey instanceof BCECPrivateKey) {
        return ByteUtil.bigIntegerToBytes(((BCECPrivateKey) privKey).getD(), 32);
    } else {
        return null;
    }
}
 
Example #26
Source File: MspValidateTest.java    From julongchain with Apache License 2.0 5 votes vote down vote up
@Test
public void base64() throws NoSuchAlgorithmException, InvalidKeySpecException, IOException, CryptoException, CspException {
    Security.addProvider(new BouncyCastleProvider());
    String sk = "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgTchUuHEAckzfS16v\n" +
            "8hz4Rt9G+41OifbzAr9jM+JGxiygCgYIKoEcz1UBgi2hRANCAASDw0oz+lq1H8QM\n" +
            "8YaZSikOsCdbLR+sUd+hpzvDF1wmS3zVNqtKnTRzD3bVgR4AFljtBVmbXNmJdrno\n" +
            "C8r6EmyE";
    KeyFactory keyf = keyf = KeyFactory.getInstance("EC");
    PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64.decode(sk));
    BCECPrivateKey priKey = (BCECPrivateKey) keyf.generatePrivate(priPKCS8);
    System.out.println("16进制私钥:" + priKey.getD().toString(16));

    String cert_path = MspValidateTest.class.getResource("/szca/testsm2.pem").getPath();
    byte[] idBytes = FileUtils.readFileBytes(cert_path);
    Certificate certificate = Certificate.getInstance(new PemReader(new InputStreamReader(new ByteArrayInputStream(idBytes))).readPemObject().getContent());
    byte[] pb = certificate.getTBSCertificate().getSubjectPublicKeyInfo().getPublicKeyData().getBytes();
    byte[] publickey = certificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes();

    System.out.println(certificate.getSubject());
    System.out.println("tbs 公钥" + Hex.toHexString(pb));
    System.out.println("公钥:" + Hex.toHexString(publickey));
    System.out.println("公钥长度:" + publickey.length);


    SM2 sm2 = new SM2();
    byte[] v = sm2.sign(priKey.getD().toByteArray(), "123".getBytes());
    System.out.println(sm2.verify(publickey, v, "123".getBytes()));

}
 
Example #27
Source File: SM2Pkcs12MakerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPkcs12Sign() {
    //先生成一个pkcs12
    testMakePkcs12();

    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        try (InputStream is = Files.newInputStream(Paths.get(TEST_P12_FILENAME),
                                  StandardOpenOption.READ)) {
            ks.load(is, TEST_P12_PASSWD);
        }

        PrivateKey privateKey = (BCECPrivateKey) ks.getKey("User Key", TEST_P12_PASSWD);
        X509Certificate cert = (X509Certificate) ks.getCertificate("User Key");

        byte[] srcData = "1234567890123456789012345678901234567890".getBytes();

        // create signature
        Signature sign = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        sign.initSign(privateKey);
        sign.update(srcData);
        byte[] signatureValue = sign.sign();

        // verify signature
        Signature verify = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        verify.initVerify(cert);
        verify.update(srcData);
        boolean sigValid = verify.verify(signatureValue);
        Assert.assertTrue("signature validation result", sigValid);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example #28
Source File: ECKeyPair.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    return new ECKeyPair(privateKeyValue, publicKeyValue);
}
 
Example #29
Source File: ECCDecrypt.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * create BCECPrivateKey from privateKey
 *
 * @param privateKey
 * @return
 */
private BCECPrivateKey createBCECPrivateKey(BigInteger privateKey) {
    // Handle secret key
    ECPrivateKeySpec secretKeySpec =
            new ECPrivateKeySpec(privateKey, ECCParams.ecNamedCurveSpec);
    BCECPrivateKey bcecPrivateKey =
            new BCECPrivateKey("ECDSA", secretKeySpec, BouncyCastleProvider.CONFIGURATION);
    return bcecPrivateKey;
}
 
Example #30
Source File: ECKeyPair.java    From web3j with Apache License 2.0 5 votes vote down vote up
public static ECKeyPair create(KeyPair keyPair) {
    BCECPrivateKey privateKey = (BCECPrivateKey) keyPair.getPrivate();
    BCECPublicKey publicKey = (BCECPublicKey) keyPair.getPublic();

    BigInteger privateKeyValue = privateKey.getD();

    // Ethereum does not use encoded public keys like bitcoin - see
    // https://en.bitcoin.it/wiki/Elliptic_Curve_Digital_Signature_Algorithm for details
    // Additionally, as the first bit is a constant prefix (0x04) we ignore this value
    byte[] publicKeyBytes = publicKey.getQ().getEncoded(false);
    BigInteger publicKeyValue =
            new BigInteger(1, Arrays.copyOfRange(publicKeyBytes, 1, publicKeyBytes.length));

    return new ECKeyPair(privateKeyValue, publicKeyValue);
}