Example usage for java.math BigInteger modPow

List of usage examples for java.math BigInteger modPow

Introduction

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

Prototype

public BigInteger modPow(BigInteger exponent, BigInteger m) 

Source Link

Document

Returns a BigInteger whose value is (thisexponent mod m).

Usage

From source file:com.forsrc.utils.MyRsaUtils.java

/**
 * Decrypt big integer.//  w  ww. j  a  v  a 2 s. c o  m
 *
 * @param rsaKey    the rsa key
 * @param encrypted the encrypted
 * @return the big integer
 */
public static BigInteger decrypt(RsaKey rsaKey, BigInteger encrypted) {
    // C = (encrypted^privateKey) * mod m
    return encrypted.modPow(rsaKey.getPrivateKey()/* d */, rsaKey.getN());
}

From source file:RSA.java

/** Encrypt the given plaintext message. */
public synchronized BigInteger encrypt(BigInteger message) {
    return message.modPow(e, n);
}

From source file:RSA.java

/** Decrypt the given ciphertext message. */
public synchronized BigInteger decrypt(BigInteger message) {
    return message.modPow(d, n);
}

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

/**
 * Returns the shared secret.//from   w  w w  .j a v a2  s . c o  m
 *
 * @param composite the composite number (public key) with which this
 * instance shares a secret.
 * @return the shared secret.
 */
public BigInteger getSharedSecret(BigInteger composite) {
    return composite.modPow(privateKey, modulus);
}

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  . jav a 2  s  . c  om

    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:test.be.fedict.eid.applet.PKCS11Test.java

@Test
public void testPKCS1viaPKCS11() throws Exception {
    File tmpConfigFile = File.createTempFile("pkcs11-", "conf");
    tmpConfigFile.deleteOnExit();//ww  w  .  j  ava 2  s.  c om
    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:test.be.fedict.eid.applet.RSATest.java

@Test
public void testManualEncryption() throws Exception {
    while (true) {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA",
                BouncyCastleProvider.PROVIDER_NAME);
        SecureRandom random = new SecureRandom();
        int keySize = 128;
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F0), random);
        KeyPair keyPair = keyPairGenerator.generateKeyPair();
        PrivateKey privateKey = keyPair.getPrivate();
        PublicKey publicKey = keyPair.getPublic();
        RSAPrivateCrtKey rsaPrivateKey = (RSAPrivateCrtKey) privateKey;
        LOG.debug("private key modulus: " + rsaPrivateKey.getModulus());
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        LOG.debug("public key modulus: " + rsaPublicKey.getModulus());
        LOG.debug("public key exponent: " + rsaPublicKey.getPublicExponent());
        LOG.debug("modulus size: " + rsaPublicKey.getModulus().toByteArray().length);

        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);

        int dataSize = keySize / 8 - 11;
        byte[] data1 = new byte[dataSize];
        for (int i = 0; i < data1.length; i++) {
            data1[i] = 0x00;//from   w  w w. j  av  a2 s . c  o  m
        }
        byte[] data2 = new byte[dataSize];
        for (int i = 0; i < data2.length; i++) {
            data2[i] = 0x00;
        }
        data2[data2.length - 1] = 0x07;

        byte[] signatureValue1 = cipher.doFinal(data1);

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

        cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] signatureValue2 = cipher.doFinal(data2);

        BigInteger sigBigInt1 = new BigInteger(signatureValue1);
        BigInteger sigBigInt2 = new BigInteger(signatureValue2);
        BigInteger msgBigInt1 = sigBigInt1.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        BigInteger msgBigInt2 = sigBigInt2.modPow(rsaPublicKey.getPublicExponent(), rsaPublicKey.getModulus());
        LOG.debug("msg big int: " + msgBigInt1);
        byte[] msgBytes1 = msgBigInt1.toByteArray();
        LOG.debug("original message size: " + msgBytes1.length);
        LOG.debug("original message1: " + new String(Hex.encodeHex(msgBytes1)));
        LOG.debug("original message2: " + new String(Hex.encodeHex(msgBigInt2.toByteArray())));

        LOG.debug("msg1 prime: " + msgBigInt1.isProbablePrime(100));
        LOG.debug("msg2 prime: " + msgBigInt2.isProbablePrime(100));

        // BigInteger.pow offers a very naive implementation
        LOG.debug("calculating s1^e...");
        BigInteger s1_e = sigBigInt1.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s1^e: " + s1_e);
        LOG.debug("calculating s2^e...");
        BigInteger s2_e = sigBigInt2.pow(rsaPublicKey.getPublicExponent().intValue());
        LOG.debug("s2^e: " + s2_e);

        LOG.debug("calculating GCD...");
        LOG.debug("msg1: " + msgBigInt1);
        LOG.debug("msg2: " + msgBigInt2);
        BigInteger a = s1_e.subtract(msgBigInt1);
        BigInteger b = s2_e.subtract(msgBigInt2);
        LOG.debug("a: " + a);
        LOG.debug("b: " + b);
        BigInteger candidateModulus = a.gcd(b);
        LOG.debug("candidate modulus: " + candidateModulus);
        LOG.debug("candidate modulus size: " + candidateModulus.toByteArray().length);
        BigInteger s_e = s1_e.multiply(s2_e);
        BigInteger m = msgBigInt1.multiply(msgBigInt2);
        while (false == rsaPublicKey.getModulus().equals(candidateModulus)) {
            LOG.error("incorrect candidate modulus");
            LOG.debug("modulus | candidate modulus: "
                    + candidateModulus.remainder(rsaPublicKey.getModulus()).equals(BigInteger.ZERO));
            s_e = s_e.multiply(s1_e);
            m = m.multiply(msgBigInt1);
            BigInteger n1 = s_e.subtract(m).gcd(a);
            BigInteger n2 = s_e.subtract(m).gcd(b);
            candidateModulus = n1.gcd(n2);
            // try / 2
            LOG.debug("new modulus:       " + n1);
            LOG.debug("new modulus:       " + n2);
            LOG.debug("candidate modulus: " + candidateModulus);
            LOG.debug("actual mod:        " + rsaPublicKey.getModulus());
        }
    }
}

From source file:test.integ.be.fedict.trust.Foreigner201305Test.java

@Test
public void testForeigner201305() throws Exception {
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate rootCert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/belgiumrca2.crt"));
    X509Certificate foreigner201304Cert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/foreigner201304.crt"));

    foreigner201304Cert.verify(rootCert.getPublicKey());

    X509Certificate foreigner201305Cert = (X509Certificate) certificateFactory
            .generateCertificate(Foreigner201305Test.class.getResourceAsStream("/foreigner201305.crt"));

    foreigner201305Cert.verify(rootCert.getPublicKey());

    byte[] foreigner201304SignatureValue = foreigner201304Cert.getSignature();
    byte[] foreigner201305SignatureValue = foreigner201305Cert.getSignature();
    LOG.debug("201304 signature size: " + foreigner201304SignatureValue.length);
    LOG.debug("201305 signature size: " + foreigner201305SignatureValue.length);

    RSAPublicKey rootPublicKey = (RSAPublicKey) rootCert.getPublicKey();

    BigInteger foreigner201304Signature = new BigInteger(foreigner201304SignatureValue);
    BigInteger foreigner201305Signature = new BigInteger(foreigner201305SignatureValue);

    LOG.debug("201305 signature size: " + foreigner201305Signature.toByteArray().length);

    BigInteger foreigner201304PaddedMessage = foreigner201304Signature.modPow(rootPublicKey.getPublicExponent(),
            rootPublicKey.getModulus());
    BigInteger foreigner201305PaddedMessage = foreigner201305Signature.modPow(rootPublicKey.getPublicExponent(),
            rootPublicKey.getModulus());

    LOG.debug(/*from w w  w .  j  a va  2 s  .  c o m*/
            "201304 padded message: " + new String(Hex.encodeHex(foreigner201304PaddedMessage.toByteArray())));
    LOG.debug(
            "201305 padded message: " + new String(Hex.encodeHex(foreigner201305PaddedMessage.toByteArray())));

    LOG.debug("201304 modulus size: "
            + ((RSAPublicKey) foreigner201304Cert.getPublicKey()).getModulus().toByteArray().length);
    LOG.debug("201305 modulus size: "
            + ((RSAPublicKey) foreigner201305Cert.getPublicKey()).getModulus().toByteArray().length);
    LOG.debug("201304 modulus: " + new String(
            Hex.encodeHex(((RSAPublicKey) foreigner201304Cert.getPublicKey()).getModulus().toByteArray())));
    LOG.debug("201305 modulus: " + new String(
            Hex.encodeHex(((RSAPublicKey) foreigner201305Cert.getPublicKey()).getModulus().toByteArray())));
}

From source file:eu.dety.burp.joseph.attacks.bleichenbacher_pkcs1.BleichenbacherPkcs1DecryptionAttackExecutor.java

/**
 * @param originalMessage//from w  ww . j  av  a 2 s  .  co m
 *            original message to be changed
 * @param si
 *            factor
 * @return Prepared message as byte array
 */
private byte[] prepareMsg(final BigInteger originalMessage, final BigInteger si) {
    byte[] msg;
    BigInteger tmp;

    // encrypt: si^e mod n
    tmp = si.modPow(this.pubKey.getPublicExponent(), this.pubKey.getModulus());

    // blind: c0*(si^e) mod n
    // or: m*si mod n (in case of plaintext m_Oracle)
    tmp = originalMessage.multiply(tmp);
    tmp = tmp.mod(this.pubKey.getModulus());
    // get bytes
    msg = correctSize(tmp.toByteArray(), this.blockSize, true);

    return msg;
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

private void verifySignatureAlgorithm(final String signatureAlgorithm, final PrivateKey privateKey,
        final PublicKey publicKey) throws Exception {
    Signature signature = Signature.getInstance(signatureAlgorithm);
    signature.initSign(privateKey);//from   ww  w .  jav  a 2 s  .co  m
    assertTrue(signature.getProvider() instanceof BeIDProvider);

    final byte[] toBeSigned = "hello world".getBytes();
    signature.update(toBeSigned);
    final byte[] signatureValue = signature.sign();
    assertNotNull(signatureValue);

    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean beIDResult = signature.verify(signatureValue);
    assertTrue(beIDResult);

    signature = Signature.getInstance(signatureAlgorithm);
    signature.initVerify(publicKey);
    signature.update(toBeSigned);
    final boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    LOG.debug("Padded DigestInfo: " + new String(Hex.encodeHex(messageBigInteger.toByteArray())));
}