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.commons.eid.client.JCATest.java

@Test
public void testPSSPrefix() throws Exception {
    Security.addProvider(new BeIDProvider());
    Security.addProvider(new BouncyCastleProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);/*from  www . jav a  2 s  . c om*/
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");
    PublicKey authnPublicKey = authnCertificate.getPublicKey();

    Signature signature = Signature.getInstance("SHA1withRSAandMGF1");
    signature.initSign(authnPrivateKey);

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

    signature.initVerify(authnPublicKey);
    signature.update(toBeSigned);
    boolean result = signature.verify(signatureValue);
    assertTrue(result);

    RSAPublicKey rsaPublicKey = (RSAPublicKey) authnPublicKey;
    BigInteger signatureValueBigInteger = new BigInteger(signatureValue);
    BigInteger messageBigInteger = signatureValueBigInteger.modPow(rsaPublicKey.getPublicExponent(),
            rsaPublicKey.getModulus());
    String paddedMessage = new String(Hex.encodeHex(messageBigInteger.toByteArray()));
    LOG.debug("padded message: " + paddedMessage);
    assertTrue(paddedMessage.endsWith("bc"));
}

From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java

private byte[] encodeRsaPublicKeyAsBitString(RSAPublicKey rsaPublicKey) throws SpkacException {
    try {//from  w w  w.j  a  va 2  s.  c o  m
        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new ASN1Integer(rsaPublicKey.getModulus()));
        vec.add(new ASN1Integer(rsaPublicKey.getPublicExponent()));
        DERSequence derSequence = new DERSequence(vec);
        return derSequence.getEncoded(ASN1Encoding.DER);
    } catch (Exception ex) {
        throw new SpkacException(res.getString("NoEncodeRsaPublicKey.exception.message"), ex);
    }
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA???// ww  w  . j  a  v a2 s  .com
 * <dl>
 * <dt>?
 * <dd>RSA????
 * </dl>
 * @param key RSA?
 * @return RSA?
 */
public File savePublicKeyFile(final RSAPublicKey key) {
    try {
        final File file = File.createTempFile("public", ".key");
        try (FileOutputStream fos = new FileOutputStream(file);
                DataOutputStream dos = new DataOutputStream(fos)) {
            final byte[] modulus = key.getModulus().toByteArray();
            dos.writeInt(modulus.length);
            dos.write(modulus);
            final byte[] publicExponent = key.getPublicExponent().toByteArray();
            dos.writeInt(publicExponent.length);
            dos.write(publicExponent);
        }
        return file;
    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.dasein.cloud.test.identity.IdentityResources.java

/**
 * @link http://stackoverflow.com/a/14582408/211197
 * @return Encoded generated public key/*from  w ww. j ava2s  . co  m*/
 */
private @Nullable String generateKey() {
    KeyPairGenerator generator;
    try {
        generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair keyPair = generator.genKeyPair();
        RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
        ByteArrayOutputStream byteOs = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(byteOs);
        dos.writeInt("ssh-rsa".getBytes().length);
        dos.write("ssh-rsa".getBytes());
        dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length);
        dos.write(rsaPublicKey.getPublicExponent().toByteArray());
        dos.writeInt(rsaPublicKey.getModulus().toByteArray().length);
        dos.write(rsaPublicKey.getModulus().toByteArray());
        String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
        return "ssh-rsa " + publicKeyEncoded + " dasein";
    } catch (Throwable e) {
        return null;
    }
}

From source file:qauth.djd.qauthclient.main.ContentFragment.java

@Override
public void onMessageReceived(MessageEvent messageEvent) {
    Log.i("qAuthWear", "on message received23123123!!!!!");

    if (messageEvent.getPath().equals("REGISTER")) {
        //Log.i("test", "device id:" + messageEvent.getData().toString());

        watch = null;//from  w ww  . j  ava2 s .  c om
        ByteArrayInputStream bis = new ByteArrayInputStream(messageEvent.getData());
        ObjectInput in = null;
        try {
            in = new ObjectInputStream(bis);
        } catch (Exception e) {
            Log.i("exception1", "e: " + e);
        }
        try {
            watch = (Watch) in.readObject();
        } catch (Exception e) {
            Log.i("exception2", "e: " + e);
        }

        if (watch != null) {
            Log.i("WATCH SERIALIZABLE", "deviceId:" + watch.deviceId + " model:" + watch.model);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!wDataset.contains(watch)) {
                        wDataset.add(watch);
                        wAdapter.notifyDataSetChanged();
                    }
                }
            });

            RSAPrivateKey rsaPrivKey = null;
            RSAPublicKey rsaPubKey = null;

            try {
                rsaPrivKey = (RSAPrivateKey) Authenticate.getPrivKeyFromString(watch.privKey);
                rsaPubKey = (RSAPublicKey) Authenticate.getPubKeyFromString(watch.pubKey);
            } catch (Exception e) {
            }

            String N = rsaPubKey.getModulus().toString(10); //N
            int E = rsaPubKey.getPublicExponent().intValue(); //E

            for (String nodeId : getNodes()) {

                SharedPreferences prefs = getActivity().getSharedPreferences("qauth.djd.qauthclient",
                        Context.MODE_PRIVATE);
                String email = prefs.getString("email", "email");
                String password = prefs.getString("password", "password");
                new RegisterBluetooth(email, password, watch.deviceId, N, E, nodeId).execute();

            }

        } else {
            Log.i("WATCH SERIALIZABLE", "watch = null");
        }

    }

}

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Gets an RSA Public key as an xml document
 * //from  w  ww  .  j  ava  2s .  c o  m
 * @param key
 * @return
 * @throws ParserConfigurationException
 * @throws UnsupportedEncodingException
 */
private Document getRSAPublicKeyAsXML(RSAPublicKey key)
        throws ParserConfigurationException, UnsupportedEncodingException {

    Document result = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element rsaKeyValue = result.createElement("RSAKeyValue");
    result.appendChild(rsaKeyValue);

    Element modulus = result.createElement("Modulus");
    rsaKeyValue.appendChild(modulus);

    byte[] modulusBytes = key.getModulus().toByteArray();
    modulusBytes = stripLeadingZeros(modulusBytes);
    modulus.appendChild(result.createTextNode(new String(Base64.encodeBase64(modulusBytes))));

    Element exponent = result.createElement("Exponent");
    rsaKeyValue.appendChild(exponent);

    byte[] exponentBytes = key.getPublicExponent().toByteArray();
    exponent.appendChild(result.createTextNode(new String(Base64.encodeBase64(exponentBytes))));

    return result;
}

From source file:com.qut.middleware.crypto.impl.CryptoProcessorImpl.java

public KeyDescriptor createSigningKeyDescriptor(RSAPublicKey pubKey, String keyPairName, String issuerDN,
        String serialNumber) {//from www.  j a v  a  2  s  .c om
    KeyDescriptor keyDescriptor = new KeyDescriptor();
    keyDescriptor.setUse(KeyTypes.SIGNING);
    KeyInfo keyInfo = new KeyInfo();
    KeyName keyName = new KeyName(keyPairName);
    keyInfo.getContent().add(keyName);

    KeyValue keyValue = new KeyValue();
    RSAKeyValue rsaKeyValue = new RSAKeyValue();
    rsaKeyValue.setExponent(pubKey.getPublicExponent().toByteArray());
    rsaKeyValue.setModulus(pubKey.getModulus().toByteArray());
    keyValue.getContent().add(rsaKeyValue);
    keyInfo.getContent().add(keyValue);
    keyDescriptor.setKeyInfo(keyInfo);

    if (issuerDN != null && serialNumber != null) {
        BigInteger serialNumberValue = new BigInteger(serialNumber);
        X509Data x509Data = new X509Data();
        X509IssuerSerialType x509IssuerSerialType = new X509IssuerSerialType();
        x509IssuerSerialType.setX509IssuerName(issuerDN);
        x509IssuerSerialType.setX509SerialNumber(serialNumberValue);
        x509Data.getX509DataContent()
                .add(new ObjectFactory().createX509DataX509IssuerSerial(x509IssuerSerialType));
        keyInfo.getContent().add(x509Data);
    }

    logger.debug("Generated KeyDescriptor for document signing with keyname " + keyPairName);

    return keyDescriptor;

}

From source file:acp.sdk.SecureUtil.java

/**
 * /*  www  . ja  va2 s .c om*/
 * @param tPIN
 * @param iPan
 * @param publicKey
 * @return
 */
public String assymEncrypt(String tPIN, String iPan, RSAPublicKey publicKey) {

    System.out.println("SampleHashMap::assymEncrypt([" + tPIN + "])");
    System.out.println("SampleHashMap::assymEncrypt(PIN =[" + tPIN + "])");

    try {
        int tKeyLength = 1024;
        int tBlockSize = tKeyLength / 8;

        byte[] tTemp = null;

        tTemp = SecureUtil.pin2PinBlockWithCardNO(tPIN, iPan);
        tTemp = addPKCS1Padding(tTemp, tBlockSize);

        BigInteger tPlainText = new BigInteger(tTemp);
        BigInteger tCipherText = tPlainText.modPow(publicKey.getPublicExponent(), publicKey.getModulus());

        byte[] tCipherBytes = tCipherText.toByteArray();
        int tCipherLength = tCipherBytes.length;
        if (tCipherLength > tBlockSize) {
            byte[] tTempBytes = new byte[tBlockSize];
            System.arraycopy(tCipherBytes, tCipherLength - tBlockSize, tTempBytes, 0, tBlockSize);
            tCipherBytes = tTempBytes;
        } else if (tCipherLength < tBlockSize) {
            byte[] tTempBytes = new byte[tBlockSize];
            for (int i = 0; i < tBlockSize - tCipherLength; i++) {
                tTempBytes[i] = 0x00;
            }
            System.arraycopy(tCipherBytes, 0, tTempBytes, tBlockSize - tCipherLength, tCipherLength);
            tCipherBytes = tTempBytes;
        }
        String tEncryptPIN = new String(SecureUtil.base64Encode(tCipherBytes));

        System.out.println("SampleHashMap::assymEncrypt(EncryptCardNo =[" + tEncryptPIN + "])");

        return tEncryptPIN;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        return tPIN;
    } catch (Error e) {
        e.printStackTrace(System.out);
        return tPIN;
    }
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static byte[] getPublicExponent(PublicKey pubk) {
    RSAPublicKey rsaKey = (RSAPublicKey) pubk;

    return rsaKey.getPublicExponent().toByteArray();
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static X509Key convertPublicKeyToX509Key(PublicKey pubk) throws InvalidKeyException {
    X509Key xKey;/*w  w  w  .  jav  a2  s  .c  o  m*/

    if (pubk instanceof RSAPublicKey) {
        RSAPublicKey rsaKey = (RSAPublicKey) pubk;

        xKey = new netscape.security.provider.RSAPublicKey(new BigInt(rsaKey.getModulus()),
                new BigInt(rsaKey.getPublicExponent()));
    } else if (pubk instanceof PK11ECPublicKey) {
        byte encoded[] = pubk.getEncoded();
        xKey = CryptoUtil.getPublicX509ECCKey(encoded);
    } else {
        // Assert.assert(pubk instanceof DSAPublicKey);
        DSAPublicKey dsaKey = (DSAPublicKey) pubk;
        DSAParams params = dsaKey.getParams();

        xKey = new netscape.security.provider.DSAPublicKey(dsaKey.getY(), params.getP(), params.getQ(),
                params.getG());
    }
    return xKey;
}