Example usage for java.security KeyPair getPublic

List of usage examples for java.security KeyPair getPublic

Introduction

In this page you can find the example usage for java.security KeyPair getPublic.

Prototype

public PublicKey getPublic() 

Source Link

Document

Returns a reference to the public key component of this key pair.

Usage

From source file:com.trsst.client.Client.java

private final static SignatureOptions getSignatureOptions(Signature signer, KeyPair signingKeys)
        throws SecurityException {
    SignatureOptions options = signer.getDefaultSignatureOptions();
    options.setSigningAlgorithm("http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1");
    options.setSignLinks(false); // don't sign atom:links
    options.setPublicKey(signingKeys.getPublic());
    options.setSigningKey(signingKeys.getPrivate());
    return options;
}

From source file:org.ejbca.core.protocol.ocsp.ProtocolOcspTestBase.java

protected static void setupTestCertificates(int caId) throws InvalidKeyException, NoSuchAlgorithmException,
        SignatureException, IllegalStateException, NoSuchProviderException, OperatorCreationException,
        CertificateException, IOException, InvalidAlgorithmParameterException, CreateException,
        AuthorizationDeniedException, CustomCertificateSerialNumberException, IllegalKeyException,
        CADoesntExistsException, CertificateCreateException, CesecoreException, CertificateExtensionException {
    CertificateCreateSessionRemote certificateCreateSession = EjbRemoteHelper.INSTANCE
            .getRemoteSession(CertificateCreateSessionRemote.class);
    CertificateStoreSessionRemote certificateStoreSession = EjbRemoteHelper.INSTANCE
            .getRemoteSession(CertificateStoreSessionRemote.class);

    AuthenticationToken authenticationToken = new TestAlwaysAllowLocalAuthenticationToken(
            ProtocolOcspTestBase.class.getSimpleName());
    KeyPair invalidCertKeys = KeyTools.genKeys("512", AlgorithmConstants.KEYALGORITHM_RSA);
    // Issue a certificate in EJBCA for the public key
    final EndEntityInformation revokedUser = new EndEntityInformation(CERTIFICATE_USERNAME, REVOKED_CERT_DN,
            caId, null, null, EndEntityTypes.ENDUSER.toEndEntityType(), 0,
            CertificateProfileConstants.CERTPROFILE_FIXED_OCSPSIGNER, EndEntityConstants.TOKEN_USERGEN, 0,
            null);//  ww  w  .ja  va 2 s.c om
    revokedUser.setPassword("foo123");
    RequestMessage req = new SimpleRequestMessage(invalidCertKeys.getPublic(), revokedUser.getUsername(),
            revokedUser.getPassword());

    X509Certificate revokedCert = (X509Certificate) (((X509ResponseMessage) certificateCreateSession
            .createCertificate(authenticationToken, revokedUser, req, X509ResponseMessage.class, null))
                    .getCertificate());
    certificateStoreSession.setRevokeStatus(authenticationToken, revokedCert,
            RevokedCertInfo.REVOCATION_REASON_UNSPECIFIED, null);

    @SuppressWarnings("unused")
    X509Certificate activeCert = (X509Certificate) (((X509ResponseMessage) certificateCreateSession
            .createCertificate(authenticationToken, revokedUser, req, X509ResponseMessage.class, null))
                    .getCertificate());

}

From source file:net.groupbuy.service.impl.RSAServiceImpl.java

@Transactional(readOnly = true)
public RSAPublicKey generateKey(HttpServletRequest request) {
    Assert.notNull(request);/*from w ww .j a v a2 s  .c om*/
    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);
    return publicKey;
}

From source file:com.iterzp.momo.service.impl.RSAServiceImpl.java

@Override
@Transactional(readOnly = true)/* w  ww. jav a  2  s . c  o  m*/
public RSAPublicKey generateKey(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);
    return publicKey;
}

From source file:org.artifactory.security.crypto.CryptoHelper.java

/**
 * Creates a master encryption key file. Throws an exception if the key file already exists of on any failure with
 * file or key creation./*from   www. jav a  2  s  .com*/
 */
public static void createMasterKeyFile() {
    File keyFile = getMasterKeyFile();
    if (keyFile.exists()) {
        throw new IllegalStateException(
                "Cannot create new master key file if it already exists at " + keyFile.getAbsolutePath());
    }
    log.info("Creating master encryption key at {}", keyFile.getAbsolutePath());
    KeyPair keyPair = generateKeyPair();
    try {
        File securityFolder = keyFile.getParentFile();
        if (!securityFolder.exists()) {
            if (!securityFolder.mkdirs()) {
                throw new RuntimeException("Could not create the folder containing the key file "
                        + securityFolder.getAbsolutePath());
            }
            setPermissionsOnSecurityFolder(securityFolder);
        }

        checkPermissionsOnSecurityFolder(securityFolder);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(keyFile))) {
            writer.write(convertToString(keyPair.getPrivate().getEncoded(), true));
            writer.newLine();
            writer.write(convertToString(keyPair.getPublic().getEncoded(), true));
            writer.newLine();
        }
    } catch (IOException e) {
        throw new RuntimeException("Could not write the key into " + keyFile.getAbsolutePath(), e);
    }
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Generates keys, CSR and certificates for the devices.
 * @param context - Application context.
 * @param listener - DeviceCertCreationListener which provide device .
 *//*from w w  w  .  j a  v a 2 s.  c  om*/
public static void generateDeviceCertificate(final Context context, final DeviceCertCreationListener listener)
        throws AndroidAgentException {

    if (context.getFileStreamPath(Constants.DEVICE_CERTIFCATE_NAME).exists()) {
        try {
            listener.onDeviceCertCreated(
                    new BufferedInputStream(context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
        } catch (FileNotFoundException e) {
            Log.e(TAG, e.getMessage());
        }
    } else {

        try {
            ServerConfig utils = new ServerConfig();
            final KeyPair deviceKeyPair = KeyPairGenerator.getInstance(Constants.DEVICE_KEY_TYPE)
                    .generateKeyPair();
            X500Principal subject = new X500Principal(Constants.DEVICE_CSR_INFO);
            PKCS10CertificationRequest csr = new PKCS10CertificationRequest(Constants.DEVICE_KEY_ALGO, subject,
                    deviceKeyPair.getPublic(), null, deviceKeyPair.getPrivate());

            EndPointInfo endPointInfo = new EndPointInfo();
            endPointInfo.setHttpMethod(org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS.POST);
            endPointInfo.setEndPoint(utils.getAPIServerURL(context) + Constants.SCEP_ENDPOINT);
            endPointInfo.setRequestParams(Base64.encodeToString(csr.getEncoded(), Base64.DEFAULT));

            new APIController().invokeAPI(endPointInfo, new APIResultCallBack() {
                @Override
                public void onReceiveAPIResult(Map<String, String> result, int requestCode) {
                    try {
                        CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                        InputStream in = new ByteArrayInputStream(
                                Base64.decode(result.get("response"), Base64.DEFAULT));
                        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
                        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                        KeyStore keyStore = KeyStore.getInstance("PKCS12");
                        keyStore.load(null);
                        keyStore.setKeyEntry(Constants.DEVICE_CERTIFCATE_ALIAS,
                                (Key) deviceKeyPair.getPrivate(),
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray(),
                                new java.security.cert.Certificate[] { cert });
                        keyStore.store(byteArrayOutputStream,
                                Constants.DEVICE_CERTIFCATE_PASSWORD.toCharArray());
                        FileOutputStream outputStream = context.openFileOutput(Constants.DEVICE_CERTIFCATE_NAME,
                                Context.MODE_PRIVATE);
                        outputStream.write(byteArrayOutputStream.toByteArray());
                        byteArrayOutputStream.close();
                        outputStream.close();
                        try {
                            listener.onDeviceCertCreated(new BufferedInputStream(
                                    context.openFileInput(Constants.DEVICE_CERTIFCATE_NAME)));
                        } catch (FileNotFoundException e) {
                            Log.e(TAG, e.getMessage());
                        }
                    } catch (CertificateException | KeyStoreException | NoSuchAlgorithmException
                            | IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, Constants.SCEP_REQUEST_CODE, context, true);

        } catch (NoSuchAlgorithmException e) {
            throw new AndroidAgentException("No algorithm for key generation", e);
        } catch (SignatureException e) {
            throw new AndroidAgentException("Invalid Signature", e);
        } catch (NoSuchProviderException e) {
            throw new AndroidAgentException("Invalid provider", e);
        } catch (InvalidKeyException e) {
            throw new AndroidAgentException("Invalid key", e);
        }
    }
}

From source file:com.l2jfree.tools.math.ScrambledKeyPair.java

public ScrambledKeyPair(KeyPair Pair) {
    pair = Pair;
    scrambledModulus = scrambleModulus(((RSAPublicKey) pair.getPublic()).getModulus());
}

From source file:br.com.ufjf.labredes.crypto.Cryptography.java

public static void geraChave() {
    try {//from ww  w. ja  va  2 s  .c o m

        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_ASYM);
        keyGen.initialize(1024);
        final KeyPair key = keyGen.generateKeyPair();

        File chavePrivadaFileServer = new File(path, PATH_CHAVE_PRIVADA_SERVER);
        File chavePublicaFileServer = new File(path, PATH_CHAVE_PUBLICA_SERVER);

        // Cria os arquivos para armazenar a chave Privada e a chave Publica            
        if (chavePrivadaFileServer.getParentFile() != null) {
            chavePrivadaFileServer.getParentFile().mkdirs();
        }

        chavePrivadaFileServer.createNewFile();

        if (chavePublicaFileServer.getParentFile() != null) {
            chavePublicaFileServer.getParentFile().mkdirs();
        }

        chavePublicaFileServer.createNewFile();

        // Salva a Chave Pblica do servidor no arquivo
        ObjectOutputStream chavePublicaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePublicaFileServer));
        chavePublicaOSS.writeObject(key.getPublic());
        chavePublicaOSS.close();

        // Salva a Chave Privada do servidor no arquivo
        ObjectOutputStream chavePrivadaOSS = new ObjectOutputStream(
                new FileOutputStream(chavePrivadaFileServer));
        chavePrivadaOSS.writeObject(key.getPrivate());
        chavePrivadaOSS.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:net.solarnetwork.pki.bc.test.BCCertificateServiceTest.java

@Before
public void setup() {
    service = new BCCertificateService();
    KeyPairGenerator keyGen;/*from   ww  w  . j  a va2 s  . com*/
    try {
        keyGen = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    keyGen.initialize(2048, new SecureRandom());
    KeyPair keypair = keyGen.generateKeyPair();
    publicKey = keypair.getPublic();
    privateKey = keypair.getPrivate();
}

From source file:com.microsoft.azure.management.TestContainerService.java

private String getSshKey() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    keyPairGenerator.initialize(2048);//  w w w  .  j  a  v  a2  s  . c  o m
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    RSAPublicKey publicKey = (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(publicKey.getPublicExponent().toByteArray().length);
    dos.write(publicKey.getPublicExponent().toByteArray());
    dos.writeInt(publicKey.getModulus().toByteArray().length);
    dos.write(publicKey.getModulus().toByteArray());
    String publicKeyEncoded = new String(Base64.encodeBase64(byteOs.toByteArray()));
    return "ssh-rsa " + publicKeyEncoded + " ";
}