org.bouncycastle.math.ec.ECPoint Java Examples
The following examples show how to use
org.bouncycastle.math.ec.ECPoint.
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: BouncyCastleCrypto.java From fabric-api with Apache License 2.0 | 6 votes |
@Override public byte[] getPublicKeyAtOffset(byte[] publicKey, byte[] offset) { BigInteger offsetInt = new BigInteger(publicKey); boolean invert = false; if (offsetInt.compareTo(BigInteger.ZERO) < 0) { invert = true; offsetInt = offsetInt.abs(); } ECPoint oG = curve.getG().multiply(offsetInt); if (invert) { oG = oG.negate(); } return oG.add(curve.getCurve().decodePoint(publicKey)).getEncoded(true); }
Example #2
Source File: SM2Tool.java From ID-SDK with Apache License 2.0 | 6 votes |
/** * 签名 * * @param M * 签名信息 * @param IDA * 签名方唯一标识 * @param keyPair * 签名方密钥对 * @return 签名 */ public Signature sign(String M, String IDA, SM2KeyPair keyPair) { byte[] ZA = ZA(IDA, keyPair.getPublicKey()); byte[] M_ = Util.join(ZA, M.getBytes()); System.out.println("[sign]M_" + Util.bytesToHexString(M_)); BigInteger e = new BigInteger(1, sm3hash(M_)); byte[] digests = sm3hash(M_); System.out.println("[sign]最终摘要:" + Util.bytesToHexString(digests)); BigInteger k; BigInteger r; do { k = random(n); ECPoint p1 = G.multiply(k).normalize(); BigInteger x1 = p1.getXCoord().toBigInteger(); r = e.add(x1); r = r.mod(n); } while (r.equals(BigInteger.ZERO) || r.add(k).equals(n)); BigInteger s = ((keyPair.getPrivateKey().add(BigInteger.ONE).modInverse(n)) .multiply((k.subtract(r.multiply(keyPair.getPrivateKey()))).mod(n))).mod(n); return new Signature(r, s); }
Example #3
Source File: Ts3Crypt.java From ts3j with Apache License 2.0 | 6 votes |
public static byte[] getSharedSecret(byte[] omega, LocalIdentity identity) { ECPoint publicKeyPoint = Ts3Crypt.decodePublicKey(omega); ECPoint p = publicKeyPoint.multiply(identity.getPrivateKey()).normalize(); byte[] keyArr = p.getAffineXCoord().toBigInteger().toByteArray(); byte[] sharedSecret; if (keyArr.length == 32) sharedSecret = Ts3Crypt.hash128(keyArr); else if (keyArr.length > 32) sharedSecret = Ts3Crypt.hash128(keyArr, keyArr.length - 32, 32); else { byte[] keyArrExt = new byte[32]; System.arraycopy(keyArr, 0, keyArrExt, 32 - keyArr.length, keyArr.length); sharedSecret = Ts3Crypt.hash128(keyArrExt); } return sharedSecret; }
Example #4
Source File: ECPointsCompact.java From InflatableDonkey with MIT License | 6 votes |
@Deprecated public static ECPoint decompressFPPoint(ECCurve curve, BigInteger X) { // See Andrey Jivsov https://www.ietf.org/archive/id/draft-jivsov-ecc-compact-05.txt. ECFieldElement x = curve.fromBigInteger(X); ECFieldElement rhs = x.square().add(curve.getA()).multiply(x).add(curve.getB()); // y' = sqrt( C(x) ), where y'>0 ECFieldElement yTilde = rhs.sqrt(); if (yTilde == null) { throw new IllegalArgumentException("invalid point compression"); } // y = min(y',p-y') BigInteger yT = yTilde.toBigInteger(); BigInteger yTn = yTilde.negate().toBigInteger(); BigInteger y = yT.compareTo(yTn) == -1 ? yT : yTn; // Q=(x,y) is the canonical representation of the point ECPoint Q = curve.createPoint(X, y); return Q; }
Example #5
Source File: SM2Algorithm.java From web3sdk with Apache License 2.0 | 6 votes |
public static byte[] encrypt(String pbkX, String pbkY, byte[] data) { byte[] t = null; ECPoint c1 = null; BigInteger x2 = null; BigInteger y2 = null; BigInteger x1 = new BigInteger(pbkX, 16); BigInteger y1 = new BigInteger(pbkY, 16); while (isEmpty(t)) { BigInteger k = generateRand(32); c1 = calculateC1(k); ECPoint s = calculateS(x1, y1, k); x2 = calculateX2(s); y2 = calculateY2(s); if (x2.toByteArray().length >= 32 && y2.toByteArray().length >= 32) { t = kdf(x2, y2, data.length); } } byte[] c2 = calculateC2(data, t); byte[] c3 = calculateC3(x2, data, y2); // // 调试用(旧标准) // byte[] c = getC(c1, c2, c3); byte[] c = getC(c1, c3, c2); return c; }
Example #6
Source File: EOSFormatter.java From eosio-java with MIT License | 6 votes |
/** * * Copyright 2011 Google Inc. * Copyright 2014 Andreas Schildbach * Copyright 2014-2016 the * libsecp256k1 contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by * applicable law or agreed to in writing, software * distributed under the License is * distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. * See the License for the specific language governing permissions and * * limitations under the License. * <p> * The method was modified to match what we need * <p> * Decompress a compressed public key (x co-ord and low-bit of y-coord). */ private static ECPoint decompressKey(BigInteger xBN, boolean yBit, AlgorithmEmployed keyType) { ECCurve.Fp curve; switch (keyType) { case SECP256R1: curve = (ECCurve.Fp) ecParamsR1.getCurve(); break; default: curve = (ECCurve.Fp) ecParamsK1.getCurve(); break; } X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(curve)); compEnc[0] = (byte) (yBit ? COMPRESSED_PUBLIC_KEY_BYTE_INDICATOR_NEGATIVE_Y : COMPRESSED_PUBLIC_KEY_BYTE_INDICATOR_POSITIVE_Y); return curve.decodePoint(compEnc); }
Example #7
Source File: SM2Algorithm.java From web3sdk with Apache License 2.0 | 6 votes |
/** * 计算Za * * @param userId * @param publicKey * @return * @date 2015年12月4日 * @author fisco-bcos */ private static byte[] sm2GetZ(byte[] userId, ECPoint publicKey) { SM3Digest sm3 = new SM3Digest(); int BitsLength = userId.length << 3; sm3.update((byte) (BitsLength >> 8 & 0xFF)); sm3.update((byte) (BitsLength & 0xFF)); sm3BlockUpdate(sm3, userId); sm3BlockUpdate(sm3, getEncoded(a)); sm3BlockUpdate(sm3, getEncoded(b)); sm3BlockUpdate(sm3, getEncoded(gx)); sm3BlockUpdate(sm3, getEncoded(gy)); ECPoint ecPoint = publicKey.normalize(); sm3BlockUpdate(sm3, getEncoded(ecPoint.getAffineXCoord().toBigInteger())); sm3BlockUpdate(sm3, getEncoded(ecPoint.getAffineYCoord().toBigInteger())); byte[] md = new byte[sm3.getDigestSize()]; sm3.doFinal(md, 0); return md; }
Example #8
Source File: SM2Util.java From chain33-sdk-java with BSD 2-Clause "Simplified" License | 6 votes |
/** * 判断生成的公钥是否合法 * * @param publicKey * @return */ private static boolean checkPublicKey(ECPoint publicKey) { if (!publicKey.isInfinity()) { BigInteger x = publicKey.getXCoord().toBigInteger(); BigInteger y = publicKey.getYCoord().toBigInteger(); if (between(x, new BigInteger("0"), p) && between(y, new BigInteger("0"), p)) { BigInteger xResult = x.pow(3).add(a.multiply(x)).add(b).mod(p); BigInteger yResult = y.pow(2).mod(p); if (yResult.equals(xResult) && publicKey.multiply(n).isInfinity()) { return true; } } } return false; }
Example #9
Source File: RFC6637KDF.java From InflatableDonkey with MIT License | 6 votes |
public byte[] apply(ECPoint S, byte[] fingerprint) throws IOException { // RFC Sections 7, 8 byte[] ZB = S.getAffineXCoord().getEncoded(); Digest digest = digestFactory.get(); digest.update((byte) 0x00); // 00 digest.update((byte) 0x00); // 00 digest.update((byte) 0x00); // 00 digest.update((byte) 0x01); // 01 digest.update(ZB, 0, ZB.length); // ZB // Params digest.update(formattedOid, 0, formattedOid.length); // curve_OID_len || curve_OID digest.update(publicKeyAlgID); // public_key_alg_ID digest.update((byte) 0x03); // 03 digest.update((byte) 0x01); // 01 digest.update(kdfHashID); // KDF_hash_ID digest.update(symAlgID); // KEK_alg_ID for AESKeyWrap digest.update(ANONYMOUS_SENDER, 0, ANONYMOUS_SENDER.length); // "Anonymous Sender " digest.update(fingerprint, 0, fingerprint.length); // recipient_fingerprint byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return hash; }
Example #10
Source File: ECPointsCompact.java From InflatableDonkey with MIT License | 6 votes |
@Deprecated public static ECPoint decodeFPPoint(ECCurve curve, byte[] data) { // Patched org.bouncycastle.math.ec.ECCurve#decodePoint code. int expectedLength = (curve.getFieldSize() + 7) / 8; if (expectedLength != data.length) { throw new IllegalArgumentException("incorrect data length for compact encoding"); } BigInteger X = BigIntegers.fromUnsignedByteArray(data, 0, expectedLength); ECPoint p = decompressFPPoint(curve, X); if (!satisfiesCofactor(curve, p)) { throw new IllegalArgumentException("invalid point"); } return p; }
Example #11
Source File: EcCurveBc.java From protect with MIT License | 6 votes |
/** * Uses BC's scalar multiplication implementation */ @Override public EcPoint multiply(final EcPoint p, final BigInteger n) { final ECPoint bcP = createECPoint(p); final ECPoint product = bcP.multiply(n).normalize(); if (product.getAffineXCoord() == null) { // Point at infinity return EcPoint.pointAtInfinity; } else { return new EcPoint(product.getAffineXCoord().toBigInteger(), product.getAffineYCoord().toBigInteger()); } }
Example #12
Source File: SECP256K1.java From incubator-tuweni with Apache License 2.0 | 5 votes |
/** * Create the public key from a secret key. * * @param secretKey The secret key. * @return The associated public key. */ public static PublicKey fromSecretKey(SecretKey secretKey) { BigInteger privKey = secretKey.bytes().toUnsignedBigInteger(); /* * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group * order, but that could change in future versions. */ if (privKey.bitLength() > Parameters.CURVE_ORDER.bitLength()) { privKey = privKey.mod(Parameters.CURVE_ORDER); } ECPoint point = new FixedPointCombMultiplier().multiply(Parameters.CURVE.getG(), privKey); return PublicKey.fromBytes(Bytes.wrap(Arrays.copyOfRange(point.getEncoded(false), 1, 65))); }
Example #13
Source File: SECP256K1.java From besu with Apache License 2.0 | 5 votes |
/** Decompress a compressed public key (x co-ord and low-bit of y-coord). */ private static ECPoint decompressKey(final BigInteger xBN, final boolean yBit) { final X9IntegerConverter x9 = new X9IntegerConverter(); final byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte) (yBit ? 0x03 : 0x02); // TODO: Find a better way to handle an invalid point compression here. // Currently ECCurve#decodePoint throws an IllegalArgumentException. return CURVE.getCurve().decodePoint(compEnc); }
Example #14
Source File: ECDomainParameters.java From web3sdk with Apache License 2.0 | 5 votes |
public ECDomainParameters(ECCurve curve, ECPoint G, BigInteger n, BigInteger h, byte[] seed) { this.curve = curve; this.G = G.normalize(); this.n = n; this.h = h; this.seed = seed; }
Example #15
Source File: SM2Algorithm.java From web3sdk with Apache License 2.0 | 5 votes |
private static byte[] getC(ECPoint c1, byte[] c3, byte[] c2) { byte[] c = new byte[64 + c3.length + c2.length]; ECPoint ecPoint = c1.normalize(); byte[] c1xBuf = padding(ecPoint.getAffineXCoord().toBigInteger().toByteArray()); byte[] c1yBuf = padding(ecPoint.getAffineYCoord().toBigInteger().toByteArray()); System.arraycopy(c1xBuf, 0, c, 0, 32); System.arraycopy(c1yBuf, 0, c, 32, 32); System.arraycopy(c3, 0, c, 64, c3.length); System.arraycopy(c2, 0, c, 64 + c3.length, c2.length); return c; }
Example #16
Source File: ECKey.java From nuls-v2 with MIT License | 5 votes |
private static ECPoint getPointWithCompression(ECPoint point, boolean compressed) { if (point.isCompressed() == compressed) { return point; } point = point.normalize(); BigInteger x = point.getAffineXCoord().toBigInteger(); BigInteger y = point.getAffineYCoord().toBigInteger(); return CURVE.getCurve().createPoint(x, y, compressed); }
Example #17
Source File: SM2.java From protools with Apache License 2.0 | 5 votes |
/** * 密钥确认最后一步 * * @param entity 传输实体 */ public void keyExchange_4(TransportEntity entity) { byte[] xV = V.getXCoord().toBigInteger().toByteArray(); byte[] yV = V.getYCoord().toBigInteger().toByteArray(); ECPoint RA = curve.decodePoint(entity.R).normalize(); byte[] s2 = sm3hash(new byte[]{0x03}, yV, sm3hash(xV, entity.Z, this.Z, RA.getXCoord().toBigInteger().toByteArray(), RA.getYCoord().toBigInteger().toByteArray(), this.RA.getXCoord().toBigInteger().toByteArray(), this.RA.getYCoord().toBigInteger().toByteArray())); if (Arrays.equals(entity.S, s2)) { System.out.println("A->B 密钥确认成功"); } else { System.out.println("A->B 密钥确认失败"); } }
Example #18
Source File: KeyUtils.java From aerogear-unifiedpush-server with Apache License 2.0 | 5 votes |
/** * Returns the base64 encoded public key as a PublicKey object */ public static PublicKey getUserPublicKey(WebPushRegistration registration) throws NoSuchAlgorithmException, InvalidKeySpecException { KeyFactory kf = KeyFactory.getInstance("ECDH", PROVIDER); ECNamedCurveParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1"); ECPoint point = ecSpec.getCurve().decodePoint(registration.getKeyAsBytes()); ECPublicKeySpec pubSpec = new ECPublicKeySpec(point, ecSpec); return kf.generatePublic(pubSpec); }
Example #19
Source File: SM2Tool.java From ID-SDK with Apache License 2.0 | 5 votes |
/** * 从本地导入公钥 * @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 #20
Source File: ECCurvePoint.java From InflatableDonkey with MIT License | 5 votes |
public static Optional<ECCurvePoint> create(BigInteger x, BigInteger y, String curveName) { X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName); ECPoint Q = x9ECParameters.getCurve() .createPoint(x, y); if (!Q.isValid()) { logger.warn("-- create() - bad Q: {} curve: {}", Q, curveName); return Optional.empty(); } ECCurvePoint point = new ECCurvePoint(Q, curveName, x9ECParameters); return Optional.of(point); }
Example #21
Source File: Ts3Crypt.java From ts3j with Apache License 2.0 | 5 votes |
public static boolean verifySignature(ECPoint publicKey, byte[] data, byte[] signature) { DSADigestSigner signer = new DSADigestSigner(new ECDSASigner(), new SHA256Digest()); ECPublicKeyParameters signingKey = new ECPublicKeyParameters(publicKey, getDomainParameters()); signer.init(false, signingKey); signer.update(data, 0, data.length); return signer.verifySignature(signature); }
Example #22
Source File: Sign.java From client-sdk-java with Apache License 2.0 | 5 votes |
/** Decompress a compressed public key (x co-ord and low-bit of y-coord). */ private static ECPoint decompressKey(BigInteger xBN, boolean yBit) { X9IntegerConverter x9 = new X9IntegerConverter(); byte[] compEnc = x9.integerToBytes(xBN, 1 + x9.getByteLength(CURVE.getCurve())); compEnc[0] = (byte)(yBit ? 0x03 : 0x02); return CURVE.getCurve().decodePoint(compEnc); }
Example #23
Source File: Sign.java From client-sdk-java with Apache License 2.0 | 5 votes |
/** * 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 #24
Source File: SECP256K1.java From cava with Apache License 2.0 | 5 votes |
/** * Create the public key from a secret key. * * @param secretKey The secret key. * @return The associated public key. */ public static PublicKey fromSecretKey(SecretKey secretKey) { BigInteger privKey = secretKey.bytes().toUnsignedBigInteger(); /* * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group * order, but that could change in future versions. */ if (privKey.bitLength() > Parameters.CURVE_ORDER.bitLength()) { privKey = privKey.mod(Parameters.CURVE_ORDER); } ECPoint point = new FixedPointCombMultiplier().multiply(Parameters.CURVE.getG(), privKey); return PublicKey.fromBytes(Bytes.wrap(Arrays.copyOfRange(point.getEncoded(false), 1, 65))); }
Example #25
Source File: ECC.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
public static int compare(ECPoint a, ECPoint b) { if (a == b) { return 0; } int result = a.getXCoord().toBigInteger().compareTo(b.getXCoord().toBigInteger()); if (result != 0) { return result; } return a.getYCoord().toBigInteger().compareTo(b.getYCoord().toBigInteger()); }
Example #26
Source File: Sign.java From web3j with Apache License 2.0 | 5 votes |
/** * Returns public key point from the given private key. * * @param privKey the private key to derive the public key from * @return ECPoint public key */ public static ECPoint publicPointFromPrivate(BigInteger privKey) { /* * TODO: FixedPointCombMultiplier currently doesn't support scalars longer than the group * order, but that could change in future versions. */ if (privKey.bitLength() > CURVE.getN().bitLength()) { privKey = privKey.mod(CURVE.getN()); } return new FixedPointCombMultiplier().multiply(CURVE.getG(), privKey); }
Example #27
Source File: Program.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
public static byte[][] sortPublicKeys(byte[]... publicKeys){ publicKeys = Arrays.stream(publicKeys).sorted((o1, o2) -> { if (KeyType.fromPubkey(o1).getLabel() != KeyType.fromPubkey(o2).getLabel()) { return KeyType.fromPubkey(o1).getLabel() >= KeyType.fromPubkey(o2).getLabel() ? 1 : -1; } switch (KeyType.fromPubkey(o1)) { case SM2: byte[] p = new byte[33]; System.arraycopy(o1, 2, p, 0, p.length); o1 = p; byte[] p2 = new byte[33]; System.arraycopy(o2, 2, p2, 0, p2.length); o2 = p2; ECPoint smPk1 = ECC.sm2p256v1.getCurve().decodePoint(o1); ECPoint smPk2 = ECC.sm2p256v1.getCurve().decodePoint(o2); return ECC.compare(smPk1, smPk2); case ECDSA: ECPoint pk1 = ECC.secp256r1.getCurve().decodePoint(o1); ECPoint pk2 = ECC.secp256r1.getCurve().decodePoint(o2); return ECC.compare(pk1, pk2); case EDDSA: //TODO return Helper.toHexString(o1).compareTo(Helper.toHexString(o1)); default: return Helper.toHexString(o1).compareTo(Helper.toHexString(o1)); } }).toArray(byte[][]::new); return publicKeys; }
Example #28
Source File: Vote.java From ontology-java-sdk with GNU Lesser General Public License v3.0 | 5 votes |
@Override protected void deserializeExclusiveData(BinaryReader reader) throws IOException { try { int len = reader.readInt(); pubKeys = new ECPoint[len]; for (int i = 0; i < len; i++) { pubKeys[i] = ECC.secp256r1.getCurve().createPoint( new BigInteger(1, reader.readVarBytes()), new BigInteger(1, reader.readVarBytes())); } account = reader.readSerializable(Address.class); } catch (Exception e) { } }
Example #29
Source File: SM2Utils.java From nuls with MIT License | 5 votes |
public static byte[] encrypt(byte[] publicKey, byte[] data) throws IOException { if (publicKey == null || publicKey.length == 0) { return null; } if (data == null || data.length == 0) { return null; } byte[] source = new byte[data.length]; System.arraycopy(data, 0, source, 0, data.length); Cipher cipher = new Cipher(); SM2 sm2 = SM2.Instance(); ECPoint userKey = sm2.ecc_curve.decodePoint(publicKey); ECPoint c1 = cipher.initEnc(sm2, userKey); cipher.encrypt(source); byte[] c3 = new byte[32]; cipher.dofinal(c3); DERInteger x = new DERInteger(c1.getX().toBigInteger()); DERInteger y = new DERInteger(c1.getY().toBigInteger()); DEROctetString derDig = new DEROctetString(c3); DEROctetString derEnc = new DEROctetString(source); ASN1EncodableVector v = new ASN1EncodableVector(); v.add(x); v.add(y); v.add(derDig); v.add(derEnc); DERSequence seq = new DERSequence(v); ByteArrayOutputStream bos = new ByteArrayOutputStream(); DEROutputStream dos = new DEROutputStream(bos); dos.writeObject(seq); return bos.toByteArray(); }
Example #30
Source File: TrustAddressGenerator.java From alpha-wallet-android with MIT License | 5 votes |
public static String preimageToAddress(byte[] preimage) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException { Security.addProvider(new BouncyCastleProvider()); // get the hash of the preimage text Keccak.Digest256 digest = new Keccak.Digest256(); digest.update(preimage); byte[] hash = digest.digest(); // use the hash to derive a new address BigInteger keyDerivationFactor = new BigInteger(Numeric.toHexStringNoPrefix(hash), 16); ECPoint donatePKPoint = extractPublicKey(decodeKey(masterPubKey)); ECPoint digestPKPoint = donatePKPoint.multiply(keyDerivationFactor); return getAddress(digestPKPoint); }