Java Code Examples for org.bouncycastle.util.BigIntegers#asUnsignedByteArray()

The following examples show how to use org.bouncycastle.util.BigIntegers#asUnsignedByteArray() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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 14
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 15
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);
}