org.bouncycastle.util.BigIntegers Java Examples

The following examples show how to use org.bouncycastle.util.BigIntegers. 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: OutboundHandshake.java    From red5-client with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the servers handshake bytes
 */
@Override
protected void createHandshakeBytes() {
    log.trace("createHandshakeBytes");
    BigInteger bi = new BigInteger((Constants.HANDSHAKE_SIZE * 8), random);
    handshakeBytes = BigIntegers.asUnsignedByteArray(bi);
    // prevent AOOB error that can occur, sometimes
    if (handshakeBytes.length < Constants.HANDSHAKE_SIZE) {
        // resize the handshake bytes
        ByteBuffer b = ByteBuffer.allocate(Constants.HANDSHAKE_SIZE);
        b.put(handshakeBytes);
        b.put((byte) 0x13);
        b.flip();
        handshakeBytes = b.array();
    }
}
 
Example #2
Source File: EthereumIESEncryptionEngine.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
public byte[] processBlock(byte[] in, int inOff, int inLen) throws InvalidCipherTextException {

    // Compute the common value and convert to byte array.
    agree.init(privParam);
    BigInteger z = agree.calculateAgreement(pubParam);
    byte[] Z = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

    // Create input to KDF.
    if (V.length != 0) {
      byte[] VZ = Arrays.concatenate(V, Z);
      Arrays.fill(Z, (byte) 0);
      Z = VZ;
    }

    try {
      // Initialise the KDF.
      KDFParameters kdfParam = new KDFParameters(Z, param.getDerivationV());
      kdf.init(kdfParam);

      return forEncryption ? encryptBlock(in, inOff, inLen) : decryptBlock(in, inOff, inLen);
    } finally {
      Arrays.fill(Z, (byte) 0);
    }
  }
 
Example #3
Source File: GMUtil.java    From xipki with Apache License 2.0 6 votes vote down vote up
public static byte[] getSM2Z(byte[] userID, ASN1ObjectIdentifier curveOid,
    BigInteger pubPointX, BigInteger pubPointY) {
  SM3Digest digest = new SM3Digest();

  addUserId(digest, userID);

  X9ECParameters ecParams = GMNamedCurves.getByOID(curveOid);
  addFieldElement(digest, ecParams.getCurve().getA());
  addFieldElement(digest, ecParams.getCurve().getB());
  addFieldElement(digest, ecParams.getG().getAffineXCoord());
  addFieldElement(digest, ecParams.getG().getAffineYCoord());

  int fieldSize = (ecParams.getCurve().getFieldSize() + 7) / 8;
  byte[] bytes = BigIntegers.asUnsignedByteArray(fieldSize, pubPointX);
  digest.update(bytes, 0, fieldSize);

  bytes = BigIntegers.asUnsignedByteArray(fieldSize, pubPointY);
  digest.update(bytes, 0, fieldSize);

  byte[] result = new byte[digest.getDigestSize()];
  digest.doFinal(result, 0);
  return result;
}
 
Example #4
Source File: ECPrivateKeyImportCompact.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }


    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);
    BigInteger d = BigIntegers.fromUnsignedByteArray(data, fieldLength, fieldLength);

    return ECKeyFactories.privateKeyFactory()
            .createECPrivateKey(x, y, d, curveName);
}
 
Example #5
Source File: ECPublicKeyImportX963.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@Override
public Optional<ECPublicKey> importKey(String curveName, byte[] data) {
    int fieldLength = ECAssistant.fieldLength(curveName);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }

    if (!checkType(data[0])) {
        logger.warn("-- importKey() - bad data type: 0x{}", Integer.toHexString(data[0]));
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data, 1, fieldLength);
    BigInteger y = BigIntegers.fromUnsignedByteArray(data, 1 + fieldLength, fieldLength);

    return ECKeyFactories.publicKeyFactory()
            .createECPublicKey(x, y, curveName);
}
 
Example #6
Source File: ECPointsCompact.java    From InflatableDonkey with MIT License 6 votes vote down vote up
@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 #7
Source File: SRPAssistant.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public static byte[] padded(BigInteger n, int length) {
    // org.bouncycastle.crypto.agreement.srp.SRP6Util#getPadded() with overflow check
    byte[] byteArray = BigIntegers.asUnsignedByteArray(n);

    if (byteArray.length > length) {
        throw new IllegalArgumentException("BigInteger overflows specified length");
    }

    if (byteArray.length < length) {
        byte[] tmp = new byte[length];
        System.arraycopy(byteArray, 0, tmp, length - byteArray.length, byteArray.length);
        byteArray = tmp;
    }
    return byteArray;
}
 
Example #8
Source File: KeyUtils.java    From aerogear-unifiedpush-server with Apache License 2.0 5 votes vote down vote up
public static PrivateKey loadPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPrivateKey = Base64Encoder.decode(privateKey);
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER);

    return keyFactory.generatePrivate(privateKeySpec);
}
 
Example #9
Source File: RTMPHandshake.java    From red5-server-common with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the public key for a given key pair.
 * 
 * @param keyPair key pair
 * @return public key
 */
protected byte[] getPublicKey(KeyPair keyPair) {
    DHPublicKey incomingPublicKey = (DHPublicKey) keyPair.getPublic();
    BigInteger dhY = incomingPublicKey.getY();
    if (log.isDebugEnabled()) {
        log.debug("Public key: {}", Hex.encodeHexString(BigIntegers.asUnsignedByteArray(dhY)));
    }
    return Arrays.copyOfRange(BigIntegers.asUnsignedByteArray(dhY), 0, KEY_LENGTH);
}
 
Example #10
Source File: ECPrivateKeyImport.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public Optional<ECPrivateKey> importKey(String curveName, byte[] data) {
    int fieldLength = ECAssistant.fieldLength(curveName);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }

    BigInteger d = BigIntegers.fromUnsignedByteArray(data, 0, fieldLength);

    return ECKeyFactories.privateKeyFactory()
            .createECPrivateKey(d, curveName);
}
 
Example #11
Source File: ECPublicKeyImportCompact.java    From InflatableDonkey with MIT License 5 votes vote down vote up
@Override
public Optional<ECPublicKey> importKey(String curveName, byte[] data) {
    X9ECParameters x9ECParameters = ECAssistant.x9ECParameters(curveName);
    int fieldLength = ECAssistant.fieldLength(x9ECParameters);
    if (fieldLength(data.length) != fieldLength) {
        logger.warn("-- importKey() - bad data length: {} curve: {} data:0x{}",
                data.length, curveName, Hex.toHexString(data));
    }

    BigInteger x = BigIntegers.fromUnsignedByteArray(data);
    BigInteger y = ECPointsCompact.y(x9ECParameters.getCurve(), x);

    return ECKeyFactories.publicKeyFactory()
            .createECPublicKey(x, y, curveName);
}
 
Example #12
Source File: DSSSignatureUtils.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Converts an ASN.1 value to a XML Signature Value.
 *
 * The JAVA JCE ECDSA/DSA Signature algorithm creates ASN.1 encoded (r,s) value pairs; the XML Signature requires
 * the
 * core BigInteger values.
 *
 * @param binaries
 *            the ASN1 signature value
 * @return the decode bytes
 * @throws IOException
 * @see <A HREF="http://www.w3.org/TR/xmldsig-core/#dsa-sha1">6.4.1 DSA</A>
 * @see <A HREF="ftp://ftp.rfc-editor.org/in-notes/rfc4050.txt">3.3. ECDSA Signatures</A>
 */
private static byte[] convertASN1toXMLDSIG(byte[] binaries) {

	try (ByteArrayOutputStream buffer = new ByteArrayOutputStream(); ASN1InputStream is = new ASN1InputStream(binaries)) {

		ASN1Sequence seq = (ASN1Sequence) is.readObject();
		if (seq.size() != 2) {
			throw new IllegalArgumentException("ASN1 Sequence size should be 2 !");
		}

		ASN1Integer r = (ASN1Integer) seq.getObjectAt(0);
		ASN1Integer s = (ASN1Integer) seq.getObjectAt(1);

		byte[] rBytes = BigIntegers.asUnsignedByteArray(r.getValue());
		int rSize = rBytes.length;
		byte[] sBytes = BigIntegers.asUnsignedByteArray(s.getValue());
		int sSize = sBytes.length;
		int max = Math.max(rSize, sSize);
		max = max % 2 == 0 ? max : max + 1;
		leftPad(buffer, max, rBytes);
		buffer.write(rBytes);
		leftPad(buffer, max, sBytes);
		buffer.write(sBytes);

		return buffer.toByteArray();
	} catch (Exception e) {
		throw new DSSException("Unable to convert to xmlDsig : " + e.getMessage(), e);
	}
}
 
Example #13
Source File: Utils.java    From org.openhab.ui.habot with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Load the private key from a URL-safe base64 encoded string
 *
 * @param encodedPrivateKey
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey loadPrivateKey(String encodedPrivateKey)
        throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    byte[] decodedPrivateKey = base64Decode(encodedPrivateKey);
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECNamedCurveParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);

    return keyFactory.generatePrivate(privateKeySpec);
}
 
Example #14
Source File: ECIESUtil.java    From nuls-v2 with MIT License 5 votes vote down vote up
private static byte[] deriveSharedSecret(byte[] priKeyA, ECPublicKeyParameters pubKeyParaB) {
    ECPrivateKeyParameters priKeyParaA = new ECPrivateKeyParameters(new BigInteger(1, priKeyA), CURVE);
    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
    agreement.init(priKeyParaA);
    BigInteger result = agreement.calculateAgreement(pubKeyParaB);
    byte[] sharedSecret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), result);
    return sharedSecret;
}
 
Example #15
Source File: ECIESUtil.java    From nuls-v2 with MIT License 5 votes vote down vote up
private static byte[] deriveSharedSecret(ECPrivateKeyParameters priKeyParaA, byte[] pubKeyB) {
    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
    agreement.init(priKeyParaA);
    ECPublicKeyParameters pubKeyParaB = new ECPublicKeyParameters(CURVE.getCurve().decodePoint(pubKeyB), CURVE);
    BigInteger result = agreement.calculateAgreement(pubKeyParaB);
    byte[] sharedSecret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), result);
    return sharedSecret;
}
 
Example #16
Source File: ShareSecretTest.java    From nuls-v2 with MIT License 5 votes vote down vote up
@Test
public void test() {
    ECPrivateKeyParameters privKeyA = new ECPrivateKeyParameters(
            new BigInteger(1, HexUtil.decode("8653b44d4acebec2cd64a015b2e509c70c9049a692e71b08fe7f52cc1fa5595f")), CURVE);
    ECDHBasicAgreement agreement = new ECDHBasicAgreement();
    agreement.init(privKeyA);
    ECPublicKeyParameters pubKeyB = new ECPublicKeyParameters(
            CURVE.getCurve().decodePoint(HexUtil.decode("02fd82681e79fbe293aef1a48c6c9b1252591340bb46de1444ad5de400ff84a433")), CURVE);
    BigInteger result = agreement.calculateAgreement(pubKeyB);
    byte[] sharedSecret = BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), result);
    System.out.println(HexUtil.encode(sharedSecret));
    // sharedSecret hex string: 692c40fdbe605b9966beee978ab290e7a35056dffe9ed092a87e62fce468791d
}
 
Example #17
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #18
Source File: RLPxConnectionFactory.java    From cava with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example #19
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 #20
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 5 votes vote down vote up
private static EthereumIESEncryptionEngine forDecryption(
    SecretKey privateKey,
    PublicKey ephemeralPublicKey,
    Bytes iv,
    Bytes commonMac) {
  CipherParameters pubParam = new ECPublicKeyParameters(ephemeralPublicKey.asEcPoint(), CURVE);
  CipherParameters privParam = new ECPrivateKeyParameters(privateKey.bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agreement = new ECDHBasicAgreement();
  agreement.init(privParam);
  byte[] agreementValue =
      BigIntegers.asUnsignedByteArray(agreement.getFieldSize(), agreement.calculateAgreement(pubParam));

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(agreementValue, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agreement,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(false, privParam, pubParam, cipherParameters);
  return engine;
}
 
Example #21
Source File: RLPxConnectionFactory.java    From incubator-tuweni with Apache License 2.0 4 votes vote down vote up
private static EthereumIESEncryptionEngine forEncryption(
    PublicKey pubKey,
    Bytes iv,
    Bytes commonMac,
    KeyPair ephemeralKeyPair) {
  CipherParameters pubParam = new ECPublicKeyParameters(pubKey.asEcPoint(), CURVE);
  CipherParameters privParam =
      new ECPrivateKeyParameters(ephemeralKeyPair.secretKey().bytes().toUnsignedBigInteger(), CURVE);

  BasicAgreement agree = new ECDHBasicAgreement();
  agree.init(privParam);
  BigInteger z = agree.calculateAgreement(pubParam);
  byte[] zbytes = BigIntegers.asUnsignedByteArray(agree.getFieldSize(), z);

  IESWithCipherParameters iesWithCipherParameters = new IESWithCipherParameters(new byte[0], new byte[0], 128, 128);

  // Initialise the KDF.
  EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction kdf =
      new EthereumIESEncryptionEngine.ECIESHandshakeKDFFunction(1, new SHA256Digest());
  kdf.init(new KDFParameters(zbytes, iesWithCipherParameters.getDerivationV()));
  EthereumIESEncryptionEngine engine = new EthereumIESEncryptionEngine(
      agree,
      kdf,
      new HMac(new SHA256Digest()),
      commonMac.toArrayUnsafe(),
      new BufferedBlockCipher(new SICBlockCipher(new AESEngine())));
  ParametersWithIV cipherParameters = new ParametersWithIV(iesWithCipherParameters, iv.toArrayUnsafe());
  engine.init(true, privParam, pubParam, cipherParameters);

  return engine;
}
 
Example #22
Source File: ECPrivateKey.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public byte[] dEncoded() {
    return BigIntegers.asUnsignedByteArray(publicKey.point().fieldLength(), d);
}
 
Example #23
Source File: ECAssistant.java    From InflatableDonkey with MIT License 4 votes vote down vote up
public static byte[] encodedField(int length, BigInteger i) {
    return BigIntegers.asUnsignedByteArray(length, i);
}
 
Example #24
Source File: CertificateRequest.java    From jqm with Apache License 2.0 4 votes vote down vote up
private void generateX509() throws Exception
{
    SecureRandom random = new SecureRandom();
    X500Name dnName = new X500Name(Subject);
    Calendar endValidity = Calendar.getInstance();
    endValidity.add(Calendar.YEAR, validityYear);

    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());

    X509v3CertificateBuilder gen = new X509v3CertificateBuilder(
            authorityCertificate == null ? dnName : authorityCertificate.getSubject(),
            BigIntegers.createRandomInRange(BigInteger.ZERO, BigInteger.valueOf(Long.MAX_VALUE), random), new Date(),
            endValidity.getTime(), dnName, publicKeyInfo);

    // Public key ID
    DigestCalculator digCalc = new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
    X509ExtensionUtils x509ExtensionUtils = new X509ExtensionUtils(digCalc);
    gen.addExtension(Extension.subjectKeyIdentifier, false, x509ExtensionUtils.createSubjectKeyIdentifier(publicKeyInfo));

    // EKU
    gen.addExtension(Extension.extendedKeyUsage, false, new ExtendedKeyUsage(EKU));

    // Basic constraints (is CA?)
    if (authorityCertificate == null)
    {
        gen.addExtension(Extension.basicConstraints, true, new BasicConstraints(true));
    }

    // Key usage
    gen.addExtension(Extension.keyUsage, true, new KeyUsage(keyUsage));

    // Subject Alt names ?

    // Authority
    if (authorityCertificate != null)
    {
        gen.addExtension(Extension.authorityKeyIdentifier, false,
                new AuthorityKeyIdentifier(authorityCertificate.getSubjectPublicKeyInfo()));
    }

    // Signer
    ContentSigner signer = new JcaContentSignerBuilder("SHA512WithRSAEncryption").setProvider(Constants.JCA_PROVIDER)
            .build(authorityKey == null ? privateKey : authorityKey);

    // Go
    holder = gen.build(signer);
}
 
Example #25
Source File: ECPointUtil.java    From besu with Apache License 2.0 4 votes vote down vote up
public static Bytes getEncodedBytes(final ECPoint ecPoint) {
  final Bytes xBytes = Bytes32.wrap(BigIntegers.asUnsignedByteArray(32, ecPoint.getAffineX()));
  final Bytes yBytes = Bytes32.wrap(BigIntegers.asUnsignedByteArray(32, ecPoint.getAffineY()));
  return Bytes.concatenate(xBytes, yBytes);
}
 
Example #26
Source File: Utils.java    From webpush-java with MIT License 3 votes vote down vote up
/**
 * Load the private key from a byte array
 *
 * @param decodedPrivateKey
 * @return
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PrivateKey loadPrivateKey(byte[] decodedPrivateKey) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    BigInteger s = BigIntegers.fromUnsignedByteArray(decodedPrivateKey);
    ECParameterSpec parameterSpec = ECNamedCurveTable.getParameterSpec(CURVE);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(s, parameterSpec);
    KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM, PROVIDER_NAME);

    return keyFactory.generatePrivate(privateKeySpec);
}