Example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

List of usage examples for java.security.spec RSAPublicKeySpec RSAPublicKeySpec

Introduction

In this page you can find the example usage for java.security.spec RSAPublicKeySpec RSAPublicKeySpec.

Prototype

public RSAPublicKeySpec(BigInteger modulus, BigInteger publicExponent) 

Source Link

Document

Creates a new RSAPublicKeySpec.

Usage

From source file:com.vmware.o11n.plugin.crypto.model.CryptoUtil.java

/**
 * Compute the RSA Public Key from an RSA Private Key
 *
 * @param privateKey RSA Private Key/*from   ww  w .  j  a  v  a 2 s. com*/
 * @return RSA Public Key
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static RSAPublicKey getPublicFromPrivate(RSAPrivateCrtKey privateKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    RSAPublicKeySpec spec = new RSAPublicKeySpec(privateKey.getModulus(), privateKey.getPublicExponent());
    return (RSAPublicKey) getPublicKey(spec);
}

From source file:io.cslinmiso.line.api.impl.LineApiImpl.java

public LoginResult login(String id, String password, String certificate) throws Exception {

    IdentityProvider provider = null;/* w w w. j a v a 2s  . co  m*/
    Map<String, String> json = null;
    String sessionKey = null;
    boolean keepLoggedIn = true;
    String accessLocation = this.ip;

    // Login to LINE server.
    if (id.matches(EMAIL_REGEX)) {
        provider = IdentityProvider.LINE; // LINE
        json = getCertResult(LINE_SESSION_LINE_URL);
    } else {
        provider = IdentityProvider.NAVER_KR; // NAVER
        json = getCertResult(LINE_SESSION_NAVER_URL);
    }

    if (id != null) {
        this.id = id;
    }

    if (password != null) {
        this.password = password;
    }

    if (StringUtils.isNotEmpty(certificate)) {
        setCertificate(certificate);
    } else {
        // read the certificate file if it exists
        try {
            List<String> readFile = Utility.readFile(LineApiImpl.CERT_FILE);
            String tmpCert = readFile != null ? readFile.get(0) : "";
            if (tmpCert != null) {
                setCertificate(tmpCert);
            }
        } catch (Exception ex) {
            setCertificate("");
        }
    }

    sessionKey = json.get("session_key");
    String tmpMsg = (char) (sessionKey.length()) + sessionKey + (char) (id.length()) + id
            + (char) (password.length()) + password;
    String message = new String(tmpMsg.getBytes(), java.nio.charset.StandardCharsets.UTF_8);
    String[] keyArr = json.get("rsa_key").split(",");
    String keyName = keyArr[0];
    String n = keyArr[1];
    String e = keyArr[2];

    BigInteger modulus = new BigInteger(n, 16);
    BigInteger pubExp = new BigInteger(e, 16);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, pubExp);
    RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(pubKeySpec);
    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    byte[] enBytes = cipher.doFinal(message.getBytes());
    String encryptString = Hex.encodeHexString(enBytes);

    THttpClient transport = new THttpClient(LINE_HTTP_URL);
    transport.setCustomHeaders(headers);
    transport.open();

    TProtocol protocol = new TCompactProtocol(transport);
    this.client = new TalkService.Client(protocol);

    LoginResult result = this.client.loginWithIdentityCredentialForCertificate(provider, keyName, encryptString,
            keepLoggedIn, accessLocation, this.systemName, this.certificate);

    if (result.getType() == LoginResultType.REQUIRE_DEVICE_CONFIRM) {

        headers.put("X-Line-Access", result.getVerifier());
        String pinCode = result.getPinCode();

        System.out.printf("Enter PinCode '%s' to your mobile phone in 2 minutes.\n", pinCode);
        // await for pinCode to be certified, it will return a verifier afterward.
        loginWithVerifierForCertificate();
    } else if (result.getType() == LoginResultType.SUCCESS) {
        // if param certificate has passed certification
        setAuthToken(result.getAuthToken());
    }

    // Once the client passed the verification, switch connection to HTTP_IN_URL
    this.client = ready();
    return result;
}

From source file:sernet.verinice.encryption.test.CryptoTest.java

X509Certificate generateCertificate(String dn, KeyPair pair, int days)
        throws GeneralSecurityException, IOException {
    PublicKey publicKey = pair.getPublic();
    PrivateKey privateKey = pair.getPrivate();
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPk = (RSAPublicKey) publicKey;
        RSAPublicKeySpec rsaPkSpec = new RSAPublicKeySpec(rsaPk.getModulus(), rsaPk.getPublicExponent());
        try {/* ww w.j a  v a 2 s  .c om*/
            publicKey = KeyFactory.getInstance("RSA").generatePublic(rsaPkSpec);
        } catch (InvalidKeySpecException e) {
            publicKey = pair.getPublic();
        }
    }
    if (privateKey instanceof RSAPrivateKey) {
        RSAPrivateKey rsaPk = (RSAPrivateKey) privateKey;
        RSAPrivateKeySpec rsaPkSpec = new RSAPrivateKeySpec(rsaPk.getModulus(), rsaPk.getPrivateExponent());
        try {
            privateKey = KeyFactory.getInstance("RSA").generatePrivate(rsaPkSpec);
        } catch (InvalidKeySpecException e) {
            privateKey = pair.getPrivate();
        }
    }

    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
    String commonName = "CN=" + dn + ", OU=None, O=None L=None, C=None";
    X500Principal dnName = new X500Principal(commonName);
    certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
    certGen.setIssuerDN(dnName);
    certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(true));
    Calendar cal = Calendar.getInstance();
    certGen.setNotBefore(cal.getTime());
    cal.add(Calendar.YEAR, 5);
    certGen.setNotAfter(cal.getTime());
    certGen.setSubjectDN(dnName);
    certGen.setPublicKey(publicKey);
    certGen.setSignatureAlgorithm("MD5WithRSA");
    return certGen.generate(privateKey, BouncyCastleProvider.PROVIDER_NAME);
}

From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java

public static KeyPair getKeyPairFromProperties(String parentName, String keyName) {
    InputStream is = null;/*www. jav  a2  s. c o m*/
    try {
        is = KeyTestUtil.class.getResourceAsStream("/" + parentName + "/" + keyName + ".properties");
        Properties props = new Properties();
        props.load(is);
        if (TYPE_RSA.equals(props.getProperty(P_TYPE))) {
            RSAPrivateKeySpec privSpec = null;
            if (props.getProperty(RSA_P) != null && props.getProperty(RSA_Q) != null
                    && props.getProperty(RSA_U) != null) {
                privSpec = new RSAPrivateCrtKeySpec(new BigInteger(props.getProperty(RSA_N)),
                        new BigInteger(props.getProperty(RSA_E)), new BigInteger(props.getProperty(RSA_D)),
                        new BigInteger(props.getProperty(RSA_P)), new BigInteger(props.getProperty(RSA_Q)),
                        new BigInteger(props.getProperty(RSA_PE)), new BigInteger(props.getProperty(RSA_QE)),
                        new BigInteger(props.getProperty(RSA_U)));
            } else {
                privSpec = new RSAPrivateKeySpec(new BigInteger(props.getProperty(RSA_N)),
                        new BigInteger(props.getProperty(RSA_D)));
            }
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(new BigInteger(props.getProperty(RSA_N)),
                    new BigInteger(props.getProperty(RSA_E)));

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            return new KeyPair(keyFactory.generatePublic(pubSpec), keyFactory.generatePrivate(privSpec));
        } else if (TYPE_DSA.equals(props.getProperty(P_TYPE))) {
            DSAPrivateKeySpec privSpec = new DSAPrivateKeySpec(new BigInteger(props.getProperty(DSA_X)),
                    new BigInteger(props.getProperty(DSA_P)), new BigInteger(props.getProperty(DSA_Q)),
                    new BigInteger(props.getProperty(DSA_G)));
            DSAPublicKeySpec pubSpec = new DSAPublicKeySpec(new BigInteger(props.getProperty(DSA_Y)),
                    new BigInteger(props.getProperty(DSA_P)), new BigInteger(props.getProperty(DSA_Q)),
                    new BigInteger(props.getProperty(DSA_G)));
            KeyFactory keyFactory = KeyFactory.getInstance("DSA");
            return new KeyPair(keyFactory.generatePublic(pubSpec), keyFactory.generatePrivate(privSpec));
        }
    } catch (Exception e) {
        LOGGER.error("Failed to read properties", e);
    } finally {
        IOUtils.closeQuietly(is);
    }

    return null;
}

From source file:org.cloudfoundry.identity.uaa.oauth.SignerProvider.java

static KeyPair parseKeyPair(String pemData) {
    Matcher m = PEM_DATA.matcher(pemData.trim());

    if (!m.matches()) {
        throw new IllegalArgumentException("String is not PEM encoded data");
    }/*w  w w  .j a v a  2 s  .co m*/

    String type = m.group(1);
    final byte[] content = b64Decode(utf8Encode(m.group(2)));

    PublicKey publicKey;
    PrivateKey privateKey = null;

    try {
        KeyFactory fact = KeyFactory.getInstance("RSA");
        if (type.equals("RSA PRIVATE KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            if (seq.size() != 9) {
                throw new IllegalArgumentException("Invalid RSA Private Key ASN1 sequence.");
            }
            org.bouncycastle.asn1.pkcs.RSAPrivateKey key = org.bouncycastle.asn1.pkcs.RSAPrivateKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            RSAPrivateCrtKeySpec privSpec = new RSAPrivateCrtKeySpec(key.getModulus(), key.getPublicExponent(),
                    key.getPrivateExponent(), key.getPrime1(), key.getPrime2(), key.getExponent1(),
                    key.getExponent2(), key.getCoefficient());
            publicKey = fact.generatePublic(pubSpec);
            privateKey = fact.generatePrivate(privSpec);
        } else if (type.equals("PUBLIC KEY")) {
            KeySpec keySpec = new X509EncodedKeySpec(content);
            publicKey = fact.generatePublic(keySpec);
        } else if (type.equals("RSA PUBLIC KEY")) {
            ASN1Sequence seq = ASN1Sequence.getInstance(content);
            org.bouncycastle.asn1.pkcs.RSAPublicKey key = org.bouncycastle.asn1.pkcs.RSAPublicKey
                    .getInstance(seq);
            RSAPublicKeySpec pubSpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
            publicKey = fact.generatePublic(pubSpec);
        } else {
            throw new IllegalArgumentException(type + " is not a supported format");
        }

        return new KeyPair(publicKey, privateKey);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    }
}

From source file:tor.TorCrypto.java

/**
 * Parses a public key encoded as ASN.1/*from  w  w w .ja  v  a  2 s . c om*/
 *
 * @param rsapublickey ASN.1 Encoded public key
 * @return PublicKey
 */
public static PublicKey asn1GetPublicKey(byte[] rsapublickey) {
    int blobsize = rsapublickey.length;
    DataInputStream dis = null;
    int jint = 0; // int to represent unsigned byte or unsigned short
    int datacount = 0;

    try {
        // --- Try to read the ANS.1 encoded RSAPublicKey blob -------------
        ByteArrayInputStream bis = new ByteArrayInputStream(rsapublickey);
        dis = new DataInputStream(bis);

        if (dis.readByte() != 0x30) // asn.1 encoded starts with 0x30
            return null;

        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey byte-sizes can be
        // specified in at most 2 bytes

        if ((jint - 0x80 + 2 + datacount) != blobsize) // sanity check for
            // correct number of
            // remaining bytes
            return null;

        //      System.out
        //         .println("\nRead outer sequence bytes; validated outer asn.1 consistency ");

        // ------- Next attempt to read Integer sequence for modulus ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        jint = dis.readUnsignedByte(); // asn.1 is 0x80 plus number of bytes
        // representing data count
        if (jint == 0x81)
            datacount = dis.readUnsignedByte(); // datalength is specified
        // in next byte.
        else if (jint == 0x82) // bytes count for any supported keysize
            // would be at most 2 bytes
            datacount = dis.readUnsignedShort(); // datalength is specified
        // in next 2 bytes
        else
            return null; // all supported publickey modulus byte-sizes can
        // be specified in at most 2 bytes

        // ---- next bytes are big-endian ordered modulus -----
        byte[] modulus = new byte[datacount];
        int modbytes = dis.read(modulus);
        if (modbytes != datacount) // if we can read enought modulus bytes
            // ...
            return null;

        //System.out.println("Read modulus");

        // ------- Next attempt to read Integer sequence for public exponent
        // ------
        if (dis.readUnsignedByte() != 0x02) // next byte read must be
            // Integer asn.1 specifier
            return null;
        datacount = dis.readUnsignedByte(); // size of modulus is specified
        // in one byte
        byte[] exponent = new byte[datacount];
        int expbytes = dis.read(exponent);
        if (expbytes != datacount)
            return null;
        //System.out.println("Read exponent");

        // ----- Finally, create the PublicKey object from modulus and
        // public exponent --------
        RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(1, modulus),
                new BigInteger(1, exponent));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);
        return pubKey;
    } catch (Exception exc) {
        return null;
    } finally {
        try {
            dis.close();
        } catch (Exception exc) {
            /* ignore */
            ;
        }
    }
}

From source file:com.aqnote.shared.cryptology.cert.gen.CertGenerator.java

public X509Certificate signCert(PKCS10CertificationRequest pkcs10CSR, X500Name issuer, KeyPair pKeyPair)
        throws Exception {
    SubjectPublicKeyInfo pkInfo = pkcs10CSR.getSubjectPublicKeyInfo();
    RSAKeyParameters rsa = (RSAKeyParameters) PublicKeyFactory.createKey(pkInfo);
    RSAPublicKeySpec rsaSpec = new RSAPublicKeySpec(rsa.getModulus(), rsa.getExponent());
    KeyFactory kf = KeyFactory.getInstance(ALG_RSA);
    PublicKey publicKey = kf.generatePublic(rsaSpec);

    SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(publicKey.getEncoded()));
    X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(issuer,
            BigInteger.valueOf(System.currentTimeMillis()),
            new Date(System.currentTimeMillis() - DateConstant.ONE_DAY),
            new Date(System.currentTimeMillis() + DateConstant.ONE_YEAR), pkcs10CSR.getSubject(), keyInfo);

    ContentSigner signer = new JcaContentSignerBuilder(ALG_SIG_SHA256_RSA).setProvider(JCE_PROVIDER)
            .build(pKeyPair.getPrivate());
    X509Certificate signedCert = new JcaX509CertificateConverter().setProvider(JCE_PROVIDER)
            .getCertificate(certBuilder.build(signer));
    signedCert.verify(pKeyPair.getPublic());

    return signedCert;
}

From source file:com.glaf.core.security.RSAUtils.java

/**
 * ?RSA//from  w  w w.j  av  a  2s.c  om
 * 
 * @param modulus
 *            
 * @param publicExponent
 *            
 * @return RSA
 */
public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) {
    RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(new BigInteger(modulus),
            new BigInteger(publicExponent));
    try {
        return (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException ex) {
        LOGGER.error("RSAPublicKeySpec is unavailable.", ex);
    } catch (Exception ex) {
        LOGGER.error("RSAUtils#KEY_FACTORY is null, can not generate KeyFactory instance.", ex);
    }
    return null;
}

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

private KeyPair generateKeyPair() {
    try {/*from  w ww .j  a  va  2 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:com.bitdubai.fermat_api.layer.all_definition.crypto.asymmetric.util.PublicKeyReaderUtil.java

/**
 * <p>Decode a RSA public key encoded according to the SSH standard from
 * the data <code>_buffer</code>. The values of the RSA public key
 * specification are read in the order//from   w  w w  .j a v  a2s.  c o  m
 * <ul>
 * <li>public exponent</li>
 * <li>modulus</li>
 * </ul>
 * With the specification the related RSA public key is generated.</p>
 *
 * @param _buffer   key / certificate data (certificate or public key
 *                  format identifier is already read)
 * @return RSA public key instance
 * @throws PublicKeyParseException if the SSH2 public key blob could not be
 *                                 decoded
 * @see RSAPublicKeySpec
 * @see <a href="http://en.wikipedia.org/wiki/RSA">RSA on Wikipedia</a>
 * @see <a href="http://tools.ietf.org/html/rfc4253#section-6.6">RFC 4253 Section 6.6</a>
 */
private static PublicKey decodePublicKey(final SSH2DataBuffer _buffer) throws PublicKeyParseException {
    final BigInteger e = _buffer.readMPint();
    final BigInteger n = _buffer.readMPint();

    try {
        final KeyFactory rsaKeyFact = KeyFactory.getInstance("RSA");
        final RSAPublicKeySpec rsaPubSpec = new RSAPublicKeySpec(n, e);

        return rsaKeyFact.generatePublic(rsaPubSpec);

    } catch (final Exception ex) {
        throw new PublicKeyParseException(
                PublicKeyParseException.ErrorCode.SSH2RSA_ERROR_DECODING_PUBLIC_KEY_BLOB, ex);
    }
}