Example usage for java.security.interfaces RSAPublicKey getPublicExponent

List of usage examples for java.security.interfaces RSAPublicKey getPublicExponent

Introduction

In this page you can find the example usage for java.security.interfaces RSAPublicKey getPublicExponent.

Prototype

public BigInteger getPublicExponent();

Source Link

Document

Returns the public exponent.

Usage

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(//  w w  w.  j a  v  a  2  s  . com
            "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:org.keycloak.jose.jwk.JWKBuilder.java

public JWK rsa(Key key, X509Certificate certificate) {
    RSAPublicKey rsaKey = (RSAPublicKey) key;

    RSAPublicJWK k = new RSAPublicJWK();

    String kid = this.kid != null ? this.kid : KeyUtils.createKeyId(key);
    k.setKeyId(kid);/*from  ww  w  .  j ava 2s  . c o m*/
    k.setKeyType(KeyType.RSA);
    k.setAlgorithm(algorithm);
    k.setPublicKeyUse(DEFAULT_PUBLIC_KEY_USE);
    k.setModulus(Base64Url.encode(toIntegerBytes(rsaKey.getModulus())));
    k.setPublicExponent(Base64Url.encode(toIntegerBytes(rsaKey.getPublicExponent())));

    if (certificate != null) {
        k.setX509CertificateChain(new String[] { PemUtils.encodeCertificate(certificate) });
    }

    return k;
}

From source file:com.hyeb.front.controller.CommonController.java

/**
 * /*from w ww .  j  a  va  2s . c o  m*/
 */
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
    Assert.notNull(request);
    KeyPair keyPair = RSAUtils.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    HttpSession session = request.getSession();
    session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);

    Map<String, String> data = new HashMap<String, String>();
    data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    return data;
}

From source file:mitm.common.security.certificate.GenerateKeyPairs.java

private void writeKeyPair(KeyPair keyPair) throws IOException {
    System.out.println("Keypair:");

    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

    System.out.println("Modulus:");
    System.out.println(bigIntToString(privateKey.getModulus()));

    System.out.println();//from  w  ww.  j av  a 2s  . c o  m
    System.out.println("Private exponent:");
    System.out.println(bigIntToString(privateKey.getPrivateExponent()));

    System.out.println();
    System.out.println("Public exponent:");
    System.out.println(bigIntToString(publicKey.getPublicExponent()));

    System.out.println();
    System.out.println("Encoded public key:");
    System.out.println(bytesToHex(keyPair.getPublic().getEncoded()));

    System.out.println();
    System.out.println("Encoded private key:");
    System.out.println(bytesToHex(keyPair.getPrivate().getEncoded()));

    System.out.println();
    System.out.println("Serial number:");
    System.out.println(bigIntToString(serialNumberGenerator.generate()));
}

From source file:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception {

    KeyPairGenerator keyGen = null;

    if (signatureAlgorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {//from w ww.ja  v  a 2 s  .c o m
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }

    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();

    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(),
            expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;

    String alias = UUID.randomUUID().toString();

    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());

    PublicKey publicKey = keyPair.getPublic();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, Use.SIGNATURE);
    jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);

    return jsonObject;
}

From source file:com.ibm.mobilefirstplatform.clientsdk.android.security.mca.internal.certificate.DefaultJSONSigner.java

@Override
public String sign(KeyPair keyPair, JSONObject json) throws Exception {

    if (keyPair == null || json == null) {
        throw new IllegalArgumentException("parameter cannot be null");
    }/*w  ww. ja v a  2  s  . co  m*/

    RSAPublicKey publicKey = ((RSAPublicKey) keyPair.getPublic());
    PrivateKey privateKey = keyPair.getPrivate();

    // create CSR Header (based on public key)
    JSONObject jwsHeaderJson = new JSONObject();
    jwsHeaderJson.put(ALG, "RS256");

    JSONObject publicKeyDataJson = new JSONObject();
    publicKeyDataJson.put(ALG, "RSA");

    String mod = encodeUrlSafe(publicKey.getModulus().toByteArray());
    publicKeyDataJson.put("mod", mod);

    String exp = encodeUrlSafe(publicKey.getPublicExponent().toByteArray());
    publicKeyDataJson.put("exp", exp);

    jwsHeaderJson.put("jpk", publicKeyDataJson);

    String jwsHeader = jwsHeaderJson.toString();
    String payload = json.toString();

    // concatenate JWS Header and payload.
    String csrHeaderAndPayload = encodeUrlSafe(jwsHeader.getBytes()) + "." + encodeUrlSafe(payload.getBytes());

    // create CSR Signature
    String jwsSignature = encodeUrlSafe(signCsrData(csrHeaderAndPayload, privateKey));

    // Concatenate them all, and return the result.
    return csrHeaderAndPayload + "." + jwsSignature;
}

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {// w w w.java2 s.  co  m
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java

public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor,
        OutputProcessorChain outputProcessorChain, PublicKey publicKey)
        throws XMLStreamException, XMLSecurityException {

    if (publicKey == null) {
        throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing");
    }// ww  w . j a  va  2 s . c  o  m

    String algorithm = publicKey.getAlgorithm();

    abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue, true, null);

    if ("RSA".equals(algorithm)) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Modulus);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(rsaPublicKey.getPublicExponent().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Exponent);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_RSAKeyValue);
    } else if ("DSA".equals(algorithm)) {
        DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey;
        BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE)
                .divide(dsaPublicKey.getParams().getQ());
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getP().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_P);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getQ().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Q);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' })
                        .encodeToString(dsaPublicKey.getParams().getG().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_G);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_Y);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray()));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_J);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig_DSAKeyValue);
    } else if ("EC".equals(algorithm)) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;

        List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1);
        attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI,
                "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey)));
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_NamedCurve);
        abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey, false, null);
        abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain,
                new Base64(76, new byte[] { '\n' }).encodeToString(
                        ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve())));
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_PublicKey);
        abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
                XMLSecurityConstants.TAG_dsig11_ECKeyValue);
    }

    abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain,
            XMLSecurityConstants.TAG_dsig_KeyValue);
}

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   w  w  w . j av  a  2 s. c  om
    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())));
}