Java Code Examples for org.bouncycastle.math.ec.ECPoint#getEncoded()

The following examples show how to use org.bouncycastle.math.ec.ECPoint#getEncoded() . 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: Sign.java    From web3sdk with Apache License 2.0 5 votes vote down vote up
/**
 * Returns public key from the given private key.
 *
 * @param privKey the private key to derive the public key from
 * @return BigInteger encoded public key
 */
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
    ECPoint point = publicPointFromPrivate(privKey);

    byte[] encoded = point.getEncoded(false);
    return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix
}
 
Example 2
Source File: Sign.java    From web3j with Apache License 2.0 5 votes vote down vote up
/**
 * Returns public key from the given private key.
 *
 * @param privKey the private key to derive the public key from
 * @return BigInteger encoded public key
 */
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
    ECPoint point = publicPointFromPrivate(privKey);

    byte[] encoded = point.getEncoded(false);
    return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length)); // remove prefix
}
 
Example 3
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * 导出公钥到本地
 * 
 * @param publicKey
 * @param path
 */
public void exportPublicKey(ECPoint publicKey, String path) {
	File file = new File(path);
	try {
		if (!file.exists())
			file.createNewFile();
		byte buffer[] = publicKey.getEncoded(false);
		FileOutputStream fos = new FileOutputStream(file);
		fos.write(buffer);
		fos.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
 
Example 4
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 5 votes vote down vote up
/**
 * 从本地导入公钥
 * @param path
 * @return
 */
public ECPoint importPublicKey(String path) {
	File file = new File(path);
	try {
		if (!file.exists())
			return null;
		FileInputStream fis = new FileInputStream(file);
		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		byte buffer[] = new byte[16];
		int size;
		while ((size = fis.read(buffer)) != -1) {
			baos.write(buffer, 0, size);
		}
		fis.close();
		byte[] decode = readPemFile(new BufferedReader(new InputStreamReader(new FileInputStream(file))));
		PublicKey pub = SecureUtil.generatePublicKey("SM2", decode);
		System.out.println(pub.getClass());
		ECPoint point = ((BCECPublicKey)pub).getQ();
		byte[] qBytes = point.getEncoded(false);
		System.out.println("[importpubkey]test_point:" + Util.bytesToHexString(qBytes));
		return curve.decodePoint(qBytes);
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 5
Source File: Sign.java    From client-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Returns public key from the given private key.
 *
 * @param privKey the private key to derive the public key from
 * @return BigInteger encoded public key
 */
public static BigInteger publicKeyFromPrivate(BigInteger privKey) {
    ECPoint point = publicPointFromPrivate(privKey);

    byte[] encoded = point.getEncoded(false);
    return new BigInteger(1, Arrays.copyOfRange(encoded, 1, encoded.length));  // remove prefix
}
 
Example 6
Source File: SM2.java    From julongchain with Apache License 2.0 5 votes vote down vote up
/**
 * sm2密钥对生成
 *
 * @return
 */
public SM2KeyPair generateKeyPair() {
    ECKeyGenerationParameters ecKeyGenerationParameters = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom());
    ECKeyPairGenerator keyPairGenerator = new ECKeyPairGenerator();
    keyPairGenerator.init(ecKeyGenerationParameters);
    AsymmetricCipherKeyPair kp = keyPairGenerator.generateKeyPair();
    ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters) kp.getPrivate();
    ECPublicKeyParameters ecpub = (ECPublicKeyParameters) kp.getPublic();
    BigInteger privateKey = ecpriv.getD();
    ECPoint publicKey = ecpub.getQ();
    return new SM2KeyPair(publicKey.getEncoded(false), privateKey.toByteArray());
}
 
Example 7
Source File: SM2.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * 导出公钥到本地
 *
 * @param publicKey
 * @param path
 */
public void exportPublicKey(ECPoint publicKey, String path) {
    File file = new File(path);
    try {
        if (!file.exists()) {
            file.createNewFile();
        }
        byte buffer[] = publicKey.getEncoded(false);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(buffer);
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
 
Example 8
Source File: Utils.java    From webpush-java with MIT License 5 votes vote down vote up
/**
 * Load a public key from the private key.
 *
 * @param privateKey
 * @return
 */
public static ECPublicKey loadPublicKey(ECPrivateKey privateKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);
    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPoint Q = ecSpec.getG().multiply(privateKey.getD());
    byte[] publicDerBytes = Q.getEncoded(false);
    ECPoint point = ecSpec.getCurve().decodePoint(publicDerBytes);
    ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec);

    return (ECPublicKey) keyFactory.generatePublic(pubSpec);
}
 
Example 9
Source File: SM2Util.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 公钥加密
 * 
 * @param input
 *            加密原文
 * @param publicKey
 *            公钥
 * @return
 */
public static byte[] encrypt(String input, ECPoint publicKey) {

	byte[] inputBuffer = input.getBytes();
	byte[] C1Buffer;
	ECPoint kpb;
	byte[] t;
	do {
		/* 1 产生随机数k,k属于[1, n-1] */
		BigInteger k = random(n);

		/* 2 计算椭圆曲线点C1 = [k]G = (x1, y1) */
		ECPoint C1 = G.multiply(k);
		C1Buffer = C1.getEncoded(false);

		/*
		 * 3 计算椭圆曲线点 S = [h]Pb
		 */
		BigInteger h = ecc_bc_spec.getH();
		if (h != null) {
			ECPoint S = publicKey.multiply(h);
			if (S.isInfinity())
				throw new IllegalStateException();
		}

		/* 4 计算 [k]PB = (x2, y2) */
		kpb = publicKey.multiply(k).normalize();

		/* 5 计算 t = KDF(x2||y2, klen) */
		byte[] kpbBytes = kpb.getEncoded(false);
		t = KDF(kpbBytes, inputBuffer.length);
	} while (allZero(t));

	/* 6 计算C2=M^t */
	byte[] C2 = new byte[inputBuffer.length];
	for (int i = 0; i < inputBuffer.length; i++) {
		C2[i] = (byte) (inputBuffer[i] ^ t[i]);
	}

	/* 7 计算C3 = Hash(x2 || M || y2) */
	byte[] C3 = sm3hash(kpb.getXCoord().toBigInteger().toByteArray(), inputBuffer,
			kpb.getYCoord().toBigInteger().toByteArray());

	/* 8 输出密文 C=C1 || C2 || C3 */

	byte[] encryptResult = new byte[C1Buffer.length + C2.length + C3.length];

	System.arraycopy(C1Buffer, 0, encryptResult, 0, C1Buffer.length);
	System.arraycopy(C2, 0, encryptResult, C1Buffer.length, C2.length);
	System.arraycopy(C3, 0, encryptResult, C1Buffer.length + C2.length, C3.length);

	return encryptResult;
}
 
Example 10
Source File: SM2.java    From protools with Apache License 2.0 4 votes vote down vote up
/**
 * 私钥解密
 *
 * @param encryptData 密文数据字节数组
 * @param privateKey  解密私钥
 * @return
 */
public String decrypt(byte[] encryptData, BigInteger privateKey) {

    byte[] C1Byte = new byte[65];
    System.arraycopy(encryptData, 0, C1Byte, 0, C1Byte.length);

    ECPoint C1 = curve.decodePoint(C1Byte).normalize();

    /*
     * 计算椭圆曲线点 S = [h]C1 是否为无穷点
     */
    BigInteger h = ecc_bc_spec.getH();
    if (h != null) {
        ECPoint S = C1.multiply(h);
        if (S.isInfinity()) {
            throw new IllegalStateException();
        }
    }
    /* 计算[dB]C1 = (x2, y2) */
    ECPoint dBC1 = C1.multiply(privateKey).normalize();

    /* 计算t = KDF(x2 || y2, klen) */
    byte[] dBC1Bytes = dBC1.getEncoded(false);
    int klen = encryptData.length - 65 - DIGEST_LENGTH;
    byte[] t = KDF(dBC1Bytes, klen);
    // DerivationFunction kdf = new KDF1BytesGenerator(new
    // ShortenedDigest(new SHA256Digest(), DIGEST_LENGTH));
    // if (debug)
    // System.out.println("klen = " + klen);
    // kdf.init(new ISO18033KDFParameters(dBC1Bytes));
    // kdf.generateBytes(t, 0, t.length);

    if (allZero(t)) {
        System.err.println("all zero");
        throw new IllegalStateException();
    }

    /* 5 计算M'=C2^t */
    byte[] M = new byte[klen];
    for (int i = 0; i < M.length; i++) {
        M[i] = (byte) (encryptData[C1Byte.length + i] ^ t[i]);
    }
    /* 6 计算 u = Hash(x2 || M' || y2) 判断 u == C3是否成立 */
    byte[] C3 = new byte[DIGEST_LENGTH];

    System.arraycopy(encryptData, encryptData.length - DIGEST_LENGTH, C3, 0, DIGEST_LENGTH);
    byte[] u = sm3hash(dBC1.getXCoord().toBigInteger().toByteArray(), M,
            dBC1.getYCoord().toBigInteger().toByteArray());
    if (Arrays.equals(u, C3)) {
        try {
            return new String(M, "UTF8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    } else {
        return null;
    }

}
 
Example 11
Source File: SM2.java    From protools with Apache License 2.0 4 votes vote down vote up
/**
 * 公钥加密
 *
 * @param input     加密原文
 * @param publicKey 公钥
 * @return
 */
public byte[] encrypt(String input, ECPoint publicKey) {

    byte[] inputBuffer = input.getBytes();

    byte[] C1Buffer;
    ECPoint kpb;
    byte[] t;
    do {
        /* 1 产生随机数k,k属于[1, n-1] */
        BigInteger k = random(n);

        /* 2 计算椭圆曲线点C1 = [k]G = (x1, y1) */
        ECPoint C1 = G.multiply(k);
        C1Buffer = C1.getEncoded(false);

        /*
         * 3 计算椭圆曲线点 S = [h]Pb
         */
        BigInteger h = ecc_bc_spec.getH();
        if (h != null) {
            ECPoint S = publicKey.multiply(h);
            if (S.isInfinity()) {
                throw new IllegalStateException();
            }
        }

        /* 4 计算 [k]PB = (x2, y2) */
        kpb = publicKey.multiply(k).normalize();

        /* 5 计算 t = KDF(x2||y2, klen) */
        byte[] kpbBytes = kpb.getEncoded(false);
        t = KDF(kpbBytes, inputBuffer.length);
        // DerivationFunction kdf = new KDF1BytesGenerator(new
        // ShortenedDigest(new SHA256Digest(), DIGEST_LENGTH));
        //
        // t = new byte[inputBuffer.length];
        // kdf.init(new ISO18033KDFParameters(kpbBytes));
        // kdf.generateBytes(t, 0, t.length);
    } while (allZero(t));

    /* 6 计算C2=M^t */
    byte[] C2 = new byte[inputBuffer.length];
    for (int i = 0; i < inputBuffer.length; i++) {
        C2[i] = (byte) (inputBuffer[i] ^ t[i]);
    }

    /* 7 计算C3 = Hash(x2 || M || y2) */
    byte[] C3 = sm3hash(kpb.getXCoord().toBigInteger().toByteArray(), inputBuffer,
            kpb.getYCoord().toBigInteger().toByteArray());

    /* 8 输出密文 C=C1 || C2 || C3 */

    byte[] encryptResult = new byte[C1Buffer.length + C2.length + C3.length];

    System.arraycopy(C1Buffer, 0, encryptResult, 0, C1Buffer.length);
    System.arraycopy(C2, 0, encryptResult, C1Buffer.length, C2.length);
    System.arraycopy(C3, 0, encryptResult, C1Buffer.length + C2.length, C3.length);

    return encryptResult;
}
 
Example 12
Source File: ECKey.java    From nuls-v2 with MIT License 4 votes vote down vote up
/**
 * Returns public key bytes from the given private key. To convert a byte array into a BigInteger,
 * use {@code new BigInteger(1, bytes);}
 */
public static byte[] publicKeyFromPrivate(BigInteger privKey, boolean compressed) {
    ECPoint point = publicPointFromPrivate(privKey);
    return point.getEncoded(compressed);
}
 
Example 13
Source File: SM2Util.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 4 votes vote down vote up
/**
 * 私钥解密
 * 
 * @param encryptData
 *            密文数据字节数组
 * @param privateKey
 *            解密私钥
 * @return
 */
public static String decrypt(byte[] encryptData, BigInteger privateKey) {
	byte[] C1Byte = new byte[65];
	System.arraycopy(encryptData, 0, C1Byte, 0, C1Byte.length);

	ECPoint C1 = curve.decodePoint(C1Byte).normalize();

	/*
	 * 计算椭圆曲线点 S = [h]C1 是否为无穷点
	 */
	BigInteger h = ecc_bc_spec.getH();
	if (h != null) {
		ECPoint S = C1.multiply(h);
		if (S.isInfinity())
			throw new IllegalStateException();
	}
	/* 计算[dB]C1 = (x2, y2) */
	ECPoint dBC1 = C1.multiply(privateKey).normalize();

	/* 计算t = KDF(x2 || y2, klen) */
	byte[] dBC1Bytes = dBC1.getEncoded(false);
	int klen = encryptData.length - 65 - DIGEST_LENGTH;
	byte[] t = KDF(dBC1Bytes, klen);

	if (allZero(t)) {
		System.err.println("all zero");
		throw new IllegalStateException();
	}

	/* 5 计算M'=C2^t */
	byte[] M = new byte[klen];
	for (int i = 0; i < M.length; i++) {
		M[i] = (byte) (encryptData[C1Byte.length + i] ^ t[i]);
	}

	/* 6 计算 u = Hash(x2 || M' || y2) 判断 u == C3是否成立 */
	byte[] C3 = new byte[DIGEST_LENGTH];

	System.arraycopy(encryptData, encryptData.length - DIGEST_LENGTH, C3, 0, DIGEST_LENGTH);
	byte[] u = sm3hash(dBC1.getXCoord().toBigInteger().toByteArray(), M,
			dBC1.getYCoord().toBigInteger().toByteArray());
	if (Arrays.equals(u, C3)) {
		try {
			return new String(M, "UTF8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	} else {
		return null;
	}
}
 
Example 14
Source File: SECP256K1.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
/**
 * Given the components of a signature and a selector value, recover and return the public key that generated the
 * signature according to the algorithm in SEC1v2 section 4.1.6.
 *
 * <p>
 * The recovery id is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because
 * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the
 * signature, or you must be willing to try each recovery id in turn until you find one that outputs the key you are
 * expecting.
 *
 * <p>
 * If this method returns null it means recovery was not possible and recovery id should be iterated.
 *
 * <p>
 * Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the output is
 * null OR a key that is not the one you expect, you try again with the next recovery id.
 *
 * @param v Which possible key to recover.
 * @param r The R component of the signature.
 * @param s The S component of the signature.
 * @param messageHash Hash of the data that was signed.
 * @return A ECKey containing only the public part, or {@code null} if recovery wasn't possible.
 */
@Nullable
private static BigInteger recoverFromSignature(int v, BigInteger r, BigInteger s, Bytes32 messageHash) {
  assert (v == 0 || v == 1);
  assert (r.signum() >= 0);
  assert (s.signum() >= 0);
  assert (messageHash != null);

  // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
  // So it's encoded in the recovery id (v).
  ECPoint R = decompressKey(r, (v & 1) == 1);
  // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).
  if (R == null || !R.multiply(Parameters.CURVE_ORDER).isInfinity()) {
    return null;
  }

  // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
  BigInteger e = messageHash.toUnsignedBigInteger();
  // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating v)
  // 1.6.1. Compute a candidate public key as:
  //   Q = mi(r) * (sR - eG)
  //
  // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
  //   Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
  // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
  // In the above equation ** is point multiplication and + is point addition (the EC group
  // operator).
  //
  // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
  // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
  BigInteger eInv = BigInteger.ZERO.subtract(e).mod(Parameters.CURVE_ORDER);
  BigInteger rInv = r.modInverse(Parameters.CURVE_ORDER);
  BigInteger srInv = rInv.multiply(s).mod(Parameters.CURVE_ORDER);
  BigInteger eInvrInv = rInv.multiply(eInv).mod(Parameters.CURVE_ORDER);
  ECPoint q = ECAlgorithms.sumOfTwoMultiplies(Parameters.CURVE.getG(), eInvrInv, R, srInv);

  if (q.isInfinity()) {
    return null;
  }

  byte[] qBytes = q.getEncoded(false);
  // We remove the prefix
  return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length));
}
 
Example 15
Source File: SECP256K1.java    From cava with Apache License 2.0 4 votes vote down vote up
/**
 * Given the components of a signature and a selector value, recover and return the public key that generated the
 * signature according to the algorithm in SEC1v2 section 4.1.6.
 *
 * <p>
 * The recovery id is an index from 0 to 3 which indicates which of the 4 possible keys is the correct one. Because
 * the key recovery operation yields multiple potential keys, the correct key must either be stored alongside the
 * signature, or you must be willing to try each recovery id in turn until you find one that outputs the key you are
 * expecting.
 *
 * <p>
 * If this method returns null it means recovery was not possible and recovery id should be iterated.
 *
 * <p>
 * Given the above two points, a correct usage of this method is inside a for loop from 0 to 3, and if the output is
 * null OR a key that is not the one you expect, you try again with the next recovery id.
 *
 * @param v Which possible key to recover.
 * @param r The R component of the signature.
 * @param s The S component of the signature.
 * @param messageHash Hash of the data that was signed.
 * @return A ECKey containing only the public part, or {@code null} if recovery wasn't possible.
 */
@Nullable
private static BigInteger recoverFromSignature(int v, BigInteger r, BigInteger s, Bytes32 messageHash) {
  assert (v == 0 || v == 1);
  assert (r.signum() >= 0);
  assert (s.signum() >= 0);
  assert (messageHash != null);

  // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
  // So it's encoded in the recovery id (v).
  ECPoint R = decompressKey(r, (v & 1) == 1);
  // 1.4. If nR != point at infinity, then do another iteration of Step 1 (callers responsibility).
  if (R == null || !R.multiply(Parameters.CURVE_ORDER).isInfinity()) {
    return null;
  }

  // 1.5. Compute e from M using Steps 2 and 3 of ECDSA signature verification.
  BigInteger e = messageHash.toUnsignedBigInteger();
  // 1.6. For k from 1 to 2 do the following. (loop is outside this function via iterating v)
  // 1.6.1. Compute a candidate public key as:
  //   Q = mi(r) * (sR - eG)
  //
  // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
  //   Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
  // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
  // In the above equation ** is point multiplication and + is point addition (the EC group
  // operator).
  //
  // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
  // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
  BigInteger eInv = BigInteger.ZERO.subtract(e).mod(Parameters.CURVE_ORDER);
  BigInteger rInv = r.modInverse(Parameters.CURVE_ORDER);
  BigInteger srInv = rInv.multiply(s).mod(Parameters.CURVE_ORDER);
  BigInteger eInvrInv = rInv.multiply(eInv).mod(Parameters.CURVE_ORDER);
  ECPoint q = ECAlgorithms.sumOfTwoMultiplies(Parameters.CURVE.getG(), eInvrInv, R, srInv);

  if (q.isInfinity()) {
    return null;
  }

  byte[] qBytes = q.getEncoded(false);
  // We remove the prefix
  return new BigInteger(1, Arrays.copyOfRange(qBytes, 1, qBytes.length));
}
 
Example 16
Source File: Signature.java    From etherjar with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @return public key derived from current v,R,S and message
 */
// implementation is based on BitcoinJ ECKey code
// see https://github.com/bitcoinj/bitcoinj/blob/master/core/src/main/java/org/bitcoinj/core/ECKey.java
public byte[] ecrecover() {
    int recId = getRecId();
    SecP256K1Curve curve = (SecP256K1Curve)ecParams.getCurve();
    BigInteger n = ecParams.getN();

    // Let x = r + jn
    BigInteger i = BigInteger.valueOf((long)recId / 2);
    BigInteger x = r.add(i.multiply(n));

    if (x.compareTo(curve.getQ()) >= 0) {
        // Cannot have point co-ordinates larger than this as everything takes place modulo Q.
        return null;
    }

    // Compressed keys require you to know an extra bit of data about the y-coord as there are two possibilities.
    // So it's encoded in the recId.
    ECPoint R = decompressKey(x, (recId & 1) == 1);
    if (!R.multiply(n).isInfinity()) {
        // If nR != point at infinity, then recId (i.e. v) is invalid
        return null;
    }

    //
    // Compute a candidate public key as:
    // Q = mi(r) * (sR - eG)
    //
    // Where mi(x) is the modular multiplicative inverse. We transform this into the following:
    // Q = (mi(r) * s ** R) + (mi(r) * -e ** G)
    // Where -e is the modular additive inverse of e, that is z such that z + e = 0 (mod n).
    // In the above equation, ** is point multiplication and + is point addition (the EC group operator).
    //
    // We can find the additive inverse by subtracting e from zero then taking the mod. For example the additive
    // inverse of 3 modulo 11 is 8 because 3 + 8 mod 11 = 0, and -3 mod 11 = 8.
    //
    BigInteger e = new BigInteger(1, message);
    BigInteger eInv = BigInteger.ZERO.subtract(e).mod(n);
    BigInteger rInv = r.modInverse(n);
    BigInteger srInv = rInv.multiply(s).mod(n);
    BigInteger eInvrInv = rInv.multiply(eInv).mod(n);

    ECPoint q = ECAlgorithms.sumOfTwoMultiplies(ecParams.getG(), eInvrInv, R, srInv);

    // For Ethereum we don't use first byte of the key
    byte[] full = q.getEncoded(false);
    byte[] ethereum = new byte[full.length - 1];
    System.arraycopy(full, 1, ethereum, 0, ethereum.length);
    return ethereum;
}
 
Example 17
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 4 votes vote down vote up
/**
 * 私钥解密
 * 
 * @param encryptData
 *            密文数据字节数组
 * @param privateKey
 *            解密私钥
 * @return
 */
public String decrypt(byte[] encryptData, BigInteger privateKey) {

	if (debug)
		System.out.println("encryptData length: " + encryptData.length);

	byte[] C1Byte = new byte[65];
	System.arraycopy(encryptData, 0, C1Byte, 0, C1Byte.length);

	ECPoint C1 = curve.decodePoint(C1Byte).normalize();

	/*
	 * 计算椭圆曲线点 S = [h]C1 是否为无穷点
	 */
	BigInteger h = ecc_bc_spec.getH();
	if (h != null) {
		ECPoint S = C1.multiply(h);
		if (S.isInfinity())
			throw new IllegalStateException();
	}
	/* 计算[dB]C1 = (x2, y2) */
	ECPoint dBC1 = C1.multiply(privateKey).normalize();

	/* 计算t = KDF(x2 || y2, klen) */
	byte[] dBC1Bytes = dBC1.getEncoded(false);
	int klen = encryptData.length - 65 - DIGEST_LENGTH;
	byte[] t = KDF(dBC1Bytes, klen);
	if (allZero(t)) {
		System.err.println("all zero");
		throw new IllegalStateException();
	}

	/* 5 计算M'=C2^t */
	byte[] M = new byte[klen];
	for (int i = 0; i < M.length; i++) {
		M[i] = (byte) (encryptData[C1Byte.length + i] ^ t[i]);
	}
	if (debug)
		printHexString(M);

	/* 6 计算 u = Hash(x2 || M' || y2) 判断 u == C3是否成立 */
	byte[] C3 = new byte[DIGEST_LENGTH];

	if (debug)
		try {
			System.out.println("M = " + new String(M, "UTF8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	System.arraycopy(encryptData, encryptData.length - DIGEST_LENGTH, C3, 0, DIGEST_LENGTH);
	byte[] u = sm3hash(dBC1.getXCoord().toBigInteger().toByteArray(), M,
			dBC1.getYCoord().toBigInteger().toByteArray());
	if (Arrays.equals(u, C3)) {
		if (debug)
			System.out.println("解密成功");
		try {
			return new String(M, "UTF8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	} else {
		if (debug) {
			System.out.print("u = ");
			printHexString(u);
			System.out.print("C3 = ");
			printHexString(C3);
			System.err.println("解密验证失败");
		}
		return null;
	}

}
 
Example 18
Source File: SM2Tool.java    From ID-SDK with Apache License 2.0 4 votes vote down vote up
/**
 * 公钥加密
 * 
 * @param input
 *            加密原文
 * @param publicKey
 *            公钥
 * @return
 */
public byte[] encrypt(String input, ECPoint publicKey) {
	byte[] inputBuffer = input.getBytes();
	if (debug)
		printHexString(inputBuffer);

	byte[] C1Buffer;
	ECPoint kpb;
	byte[] t;
	do {
		/* 1 产生随机数k,k属于[1, n-1] */
		BigInteger k = random(n);
		if (debug) {
			System.out.print("k: ");
			printHexString(k.toByteArray());
		}

		/* 2 计算椭圆曲线点C1 = [k]G = (x1, y1) */
		ECPoint C1 = G.multiply(k);
		C1Buffer = C1.getEncoded(false);
		if (debug) {
			System.out.print("C1: ");
			printHexString(C1Buffer);
		}

		/*
		 * 3 计算椭圆曲线点 S = [h]Pb
		 */
		BigInteger h = ecc_bc_spec.getH();
		if (h != null) {
			ECPoint S = publicKey.multiply(h);
			if (S.isInfinity())
				throw new IllegalStateException();
		}

		/* 4 计算 [k]PB = (x2, y2) */
		kpb = publicKey.multiply(k).normalize();

		/* 5 计算 t = KDF(x2||y2, klen) */
		byte[] kpbBytes = kpb.getEncoded(false);
		t = KDF(kpbBytes, inputBuffer.length);
	} while (allZero(t));

	/* 6 计算C2=M^t */
	byte[] C2 = new byte[inputBuffer.length];
	for (int i = 0; i < inputBuffer.length; i++) {
		C2[i] = (byte) (inputBuffer[i] ^ t[i]);
	}

	/* 7 计算C3 = Hash(x2 || M || y2) */
	byte[] C3 = sm3hash(kpb.getXCoord().toBigInteger().toByteArray(), inputBuffer,
			kpb.getYCoord().toBigInteger().toByteArray());

	/* 8 输出密文 C=C1 || C2 || C3 */

	byte[] encryptResult = new byte[C1Buffer.length + C2.length + C3.length];

	System.arraycopy(C1Buffer, 0, encryptResult, 0, C1Buffer.length);
	System.arraycopy(C2, 0, encryptResult, C1Buffer.length, C2.length);
	System.arraycopy(C3, 0, encryptResult, C1Buffer.length + C2.length, C3.length);

	if (debug) {
		System.out.print("密文: ");
		printHexString(encryptResult);
	}

	return encryptResult;
}
 
Example 19
Source File: SecP256K1KeyGenerator.java    From nem.core with MIT License 4 votes vote down vote up
@Override
public PublicKey derivePublicKey(final PrivateKey privateKey) {
	final ECPoint point = SecP256K1Curve.secp256k1().getParams().getG().multiply(privateKey.getRaw());
	return new PublicKey(point.getEncoded(true));
}
 
Example 20
Source File: ECKey.java    From javasdk with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Compute the encoded X, Y coordinates of a public point.
 * <p>
 * This is the encoded public key without the leading byte.
 *
 * @param pubPoint a public point
 * @return 64-byte X,Y point pair
 */
public static byte[] pubBytesWithoutFormat(ECPoint pubPoint) {
    final byte[] pubBytes = pubPoint.getEncoded(/* uncompressed */ false);
    return Arrays.copyOfRange(pubBytes, 1, pubBytes.length);
}