Example usage for java.math BigInteger toByteArray

List of usage examples for java.math BigInteger toByteArray

Introduction

In this page you can find the example usage for java.math BigInteger toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Document

Returns a byte array containing the two's-complement representation of this BigInteger.

Usage

From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java

private BigInteger getSecureRandomeInt() {
    final SecureRandom secureRandom = new SecureRandom();
    final BigInteger bigInt = BigInteger.valueOf(secureRandom.nextInt());
    return new BigInteger(1, bigInt.toByteArray());
}

From source file:mx.bigdata.sat.cfdi.TFDv1_v32.java

private TimbreFiscalDigital createStamp(UUID uuid, Date date) {
    ObjectFactory of = new ObjectFactory();
    TimbreFiscalDigital tfd = of.createTimbreFiscalDigital();
    tfd.setVersion("1.0");
    tfd.setFechaTimbrado(date);/*from w ww  .ja va2 s  .  co m*/
    tfd.setSelloCFD(document.getSello());
    tfd.setUUID(uuid.toString().toUpperCase()); ///-----------------CAMBIADO A MAYUSCULAS
    BigInteger bi = cert.getSerialNumber();
    tfd.setNoCertificadoSAT(new String(bi.toByteArray()));
    return tfd;
}

From source file:test.unit.be.fedict.hsm.entity.KeyStoreSingletonBeanTest.java

@Test
public void testSignature() throws Exception {
    EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("test");
    EntityManager entityManager = entityManagerFactory.createEntityManager();

    EntityTransaction entityTransaction = entityManager.getTransaction();
    entityTransaction.begin();//from ww w. ja v a2  s .  c o  m

    KeyStoreEntity keyStoreEntity = new KeyStoreEntity("test", KeyStoreType.PKCS12,
            KeyStoreSingletonBeanTest.class.getResource("/keystore.p12").toURI().getPath(), "secret");
    entityManager.persist(keyStoreEntity);

    KeyStoreSingletonBean keyStoreSingletonBean = new KeyStoreSingletonBean();

    Field entityManagerField = KeyStoreSingletonBean.class.getDeclaredField("entityManager");
    entityManagerField.setAccessible(true);
    entityManagerField.set(keyStoreSingletonBean, entityManager);

    KeyStoreLoaderBean keyStoreLoaderBean = new KeyStoreLoaderBean();
    Field keyStoreLoaderField = KeyStoreSingletonBean.class.getDeclaredField("keyStoreLoader");
    keyStoreLoaderField.setAccessible(true);
    keyStoreLoaderField.set(keyStoreSingletonBean, keyStoreLoaderBean);

    keyStoreSingletonBean.loadKeys();

    keyStoreSingletonBean.newKeyStore(keyStoreEntity.getId());

    byte[] toBeSigned = "hello world".getBytes();
    MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
    messageDigest.update(toBeSigned);
    byte[] digestValue = messageDigest.digest();
    LOG.debug("digest value: " + new String(Hex.encodeHex(digestValue)));
    byte[] signatureValue = keyStoreSingletonBean.sign(keyStoreEntity.getId(), "alias", "SHA-1", digestValue);

    assertNotNull(signatureValue);
    LOG.debug("signature size: " + signatureValue.length);

    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(KeyStoreSingletonBeanTest.class.getResourceAsStream("/keystore.p12"), "secret".toCharArray());
    RSAPublicKey publicKey = (RSAPublicKey) keyStore.getCertificate("alias").getPublicKey();

    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger originalBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(originalBigInteger.toByteArray())));

    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);
}

From source file:com.cellngine.crypto.RSACipher.java

private byte[] encode(final BigInteger modulus, final BigInteger exponent) {
    final byte[] modulusEnc = modulus.toByteArray();
    final byte[] exponentEnc = exponent.toByteArray();
    final ByteBuffer buffer = ByteBuffer.allocate(2 * 4 + modulusEnc.length + exponentEnc.length);
    buffer.putInt(modulusEnc.length);//from  w  w  w. ja v a 2s.com
    buffer.put(modulusEnc);
    buffer.putInt(exponentEnc.length);
    buffer.put(exponentEnc);
    return buffer.array();
}

From source file:mx.bigdata.sat.cfd.CFDv2.java

public void sellar(PrivateKey key, X509Certificate cert) throws Exception {
    cert.checkValidity();//from w w  w  . ja  v a2  s.co m
    String signature = getSignature(key);
    document.setSello(signature);
    byte[] bytes = cert.getEncoded();
    Base64 b64 = new Base64(-1);
    String certStr = b64.encodeToString(bytes);
    document.setCertificado(certStr);
    BigInteger bi = cert.getSerialNumber();
    document.setNoCertificado(new String(bi.toByteArray()));
}

From source file:Base64.java

/**
 * Returns a byte-array representation of a <code>BigInteger</code> without sign bit.
 *
 * @param bigInt <code>BigInteger</code> to be converted
 * @return a byte array representation of the BigInteger parameter
 *//*from w  w w  .  ja  v a 2  s  . c o  m*/
static byte[] toIntegerBytes(BigInteger bigInt) {
    int bitlen = bigInt.bitLength();
    // round bitlen
    bitlen = ((bitlen + 7) >> 3) << 3;
    byte[] bigBytes = bigInt.toByteArray();

    if (((bigInt.bitLength() % 8) != 0) && (((bigInt.bitLength() / 8) + 1) == (bitlen / 8))) {
        return bigBytes;
    }
    // set up params for copying everything but sign bit
    int startSrc = 0;
    int len = bigBytes.length;

    // if bigInt is exactly byte-aligned, just skip signbit in copy
    if ((bigInt.bitLength() % 8) == 0) {
        startSrc = 1;
        len--;
    }
    int startDst = bitlen / 8 - len; // to pad w/ nulls as per spec
    byte[] resizedBytes = new byte[bitlen / 8];
    System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, len);
    return resizedBytes;
}

From source file:com.swdouglass.joid.DiffieHellman.java

/**
 * Returns the shared secret SHA-1 hashed and XOR 'encrypted'.
 *
 * @param otherPublic the other party's public modulus; cannot be null.
 * @param secret the key to XOR encrypt with.
 * @return the encrypted secret.//www  .  j  a v a  2s.co m
 * @throws IllegalArgumentException if <code>otherPublic</code> is null.
 * @throws RuntimeException if length of <code>secret</code> is
 * incorrect. Big TODO here to make this error reporting better.
 */
public byte[] xorSecret(BigInteger otherPublic, byte[] secret) throws NoSuchAlgorithmException {
    if (otherPublic == null) {
        throw new IllegalArgumentException("otherPublic cannot be null");
    }

    BigInteger shared = getSharedSecret(otherPublic);
    byte[] hashed;
    if (secret.length == 32) {
        hashed = Crypto.sha256(shared.toByteArray());
    } else {
        hashed = Crypto.sha1(shared.toByteArray());
    }

    if (secret.length != hashed.length) {
        log.warn("invalid secret byte[] length: secret=" + secret.length + ", hashed=" + hashed.length);
        throw new RuntimeException("nyi");
    }

    byte[] result = new byte[secret.length];
    for (int i = 0; i < result.length; i++) {
        result[i] = (byte) (hashed[i] ^ secret[i]);
    }
    return result;
}

From source file:org.apache.hama.util.Bytes.java

/**
 * Split passed range. Expensive operation relatively. Uses BigInteger math.
 * // www  . ja  va  2s.  c o m
 * @param a Beginning of range
 * @param b End of range
 * @param num Number of times to split range. Pass 1 if you want to split the
 *          range in two; i.e. one split.
 * @return Array of dividing values
 */
public static byte[][] split(final byte[] a, final byte[] b, final int num) {
    byte[] aPadded;
    byte[] bPadded;
    if (a.length < b.length) {
        aPadded = padTail(a, b.length - a.length);
        bPadded = b;
    } else if (b.length < a.length) {
        aPadded = a;
        bPadded = padTail(b, a.length - b.length);
    } else {
        aPadded = a;
        bPadded = b;
    }
    if (compareTo(aPadded, bPadded) >= 0) {
        throw new IllegalArgumentException("b <= a");
    }
    if (num <= 0) {
        throw new IllegalArgumentException("num cannot be < 0");
    }
    byte[] prependHeader = { 1, 0 };
    BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
    BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
    BigInteger diffBI = stopBI.subtract(startBI);
    BigInteger splitsBI = BigInteger.valueOf(num + 1);
    if (diffBI.compareTo(splitsBI) < 0) {
        return null;
    }
    BigInteger intervalBI;
    try {
        intervalBI = diffBI.divide(splitsBI);
    } catch (Exception e) {
        LOG.error("Exception caught during division", e);
        return null;
    }

    byte[][] result = new byte[num + 2][];
    result[0] = a;

    for (int i = 1; i <= num; i++) {
        BigInteger curBI = startBI.add(intervalBI.multiply(BigInteger.valueOf(i)));
        byte[] padded = curBI.toByteArray();
        if (padded[1] == 0)
            padded = tail(padded, padded.length - 2);
        else
            padded = tail(padded, padded.length - 1);
        result[i] = padded;
    }
    result[num + 1] = b;
    return result;
}

From source file:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testPKCS1viaPKCS11() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();//  www  .  j  av a  2 s  .  c o m
    PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true);
    configWriter.println("name=SmartCard");
    configWriter.println("library=/usr/lib/libbeidpkcs11.so.0");
    configWriter.println("slotListIndex=2");

    SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath());
    Security.addProvider(provider);
    KeyStore keyStore = KeyStore.getInstance("PKCS11", provider);
    keyStore.load(null, null);
    PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null);
    PrivateKey privateKey = privateKeyEntry.getPrivateKey();
    Signature signature = Signature.getInstance("SHA1withRSA");
    signature.initSign(privateKey);
    byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    byte[] signatureValue = signature.sign();

    X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate();
    RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(),
            publicKey.getModulus());
    LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));

    // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj)
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

public String keyPairToJson(KeyPair keyPair) throws U2FException {
    ECPrivateKey privateKey = (ECPrivateKey) keyPair.getPrivate();
    ECPublicKey publicKey = (ECPublicKey) keyPair.getPublic();

    BigInteger x = publicKey.getQ().getAffineXCoord().toBigInteger();
    BigInteger y = publicKey.getQ().getAffineYCoord().toBigInteger();
    BigInteger d = privateKey.getD();

    try {/*from  w w w  . j ava  2 s.  com*/
        JSONObject jsonPrivateKey = new JSONObject();
        jsonPrivateKey.put("d", Utils.encodeHexString(d.toByteArray()));

        JSONObject jsonPublicKey = new JSONObject();
        jsonPublicKey.put("x", Utils.encodeHexString(x.toByteArray()));
        jsonPublicKey.put("y", Utils.encodeHexString(y.toByteArray()));

        JSONObject jsonKeyPair = new JSONObject();
        jsonKeyPair.put("privateKey", jsonPrivateKey);
        jsonKeyPair.put("publicKey", jsonPublicKey);

        String keyPairJson = jsonKeyPair.toString();

        if (BuildConfig.DEBUG)
            Log.d(TAG, "JSON key pair: " + keyPairJson);

        return keyPairJson;
    } catch (JSONException ex) {
        throw new U2FException("Failed to serialize key pair to JSON", ex);
    }
}