Example usage for java.security KeyPair KeyPair

List of usage examples for java.security KeyPair KeyPair

Introduction

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

Prototype

public KeyPair(PublicKey publicKey, PrivateKey privateKey) 

Source Link

Document

Constructs a key pair from the given public key and private key.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";

    Key key = keystore.getKey(alias, "password".toCharArray());
    if (key instanceof PrivateKey) {
        // Get certificate of public key
        Certificate cert = keystore.getCertificate(alias);

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        new KeyPair(publicKey, (PrivateKey) key);
    }//from   w  w  w  .  j  a v a 2  s. com
}

From source file:S3ClientSideEncryptionAsymmetricMasterKey.java

public static void main(String[] args) throws Exception {

    // 1. Load keys from files
    byte[] bytes = FileUtils.readFileToByteArray(new File(keyDir + "/private.key"));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(bytes);
    PrivateKey pk = kf.generatePrivate(ks);

    bytes = FileUtils.readFileToByteArray(new File(keyDir + "/public.key"));
    PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

    KeyPair loadedKeyPair = new KeyPair(publicKey, pk);

    // 2. Construct an instance of AmazonS3EncryptionClient.
    EncryptionMaterials encryptionMaterials = new EncryptionMaterials(loadedKeyPair);
    AWSCredentials credentials = new BasicAWSCredentials("Q3AM3UQ867SPQQA43P2F",
            "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG");
    AmazonS3EncryptionClient encryptionClient = new AmazonS3EncryptionClient(credentials,
            new StaticEncryptionMaterialsProvider(encryptionMaterials));
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    encryptionClient.setRegion(usEast1);
    encryptionClient.setEndpoint("https://play.minio.io:9000");

    final S3ClientOptions clientOptions = S3ClientOptions.builder().setPathStyleAccess(true).build();
    encryptionClient.setS3ClientOptions(clientOptions);

    // Create the bucket
    encryptionClient.createBucket(bucketName);
    // 3. Upload the object.
    byte[] plaintext = "Hello World, S3 Client-side Encryption Using Asymmetric Master Key!".getBytes();
    System.out.println("plaintext's length: " + plaintext.length);
    encryptionClient.putObject(new PutObjectRequest(bucketName, objectKey, new ByteArrayInputStream(plaintext),
            new ObjectMetadata()));

    // 4. Download the object.
    S3Object downloadedObject = encryptionClient.getObject(bucketName, objectKey);
    byte[] decrypted = IOUtils.toByteArray(downloadedObject.getObjectContent());
    Assert.assertTrue(Arrays.equals(plaintext, decrypted));
    System.out.println("decrypted length: " + decrypted.length);
    //deleteBucketAndAllContents(encryptionClient);
}

From source file:Main.java

public static KeyPair loadKeyPair(Context context, String name)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read Public Key.
    File filePublicKey = new File(context.getFilesDir(), name + "_public.key");
    FileInputStream fis = new FileInputStream(filePublicKey);
    byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
    fis.read(encodedPublicKey);/*from  ww  w.  j av a  2  s .  co m*/
    fis.close();

    // Read Private Key.
    File filePrivateKey = new File(context.getFilesDir(), name + "_private.key");
    fis = new FileInputStream(filePrivateKey);
    byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
    fis.read(encodedPrivateKey);
    fis.close();

    // Generate KeyPair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);
}

From source file:shiver.me.timbers.spring.security.jwt.JJwtDecryptorTest.java

@Before
@SuppressWarnings("unchecked")
public void setUp() {
    parserFactory = mock(JwtParserFactory.class);
    publicKey = mock(PublicKey.class);
    keyPair = new KeyPair(publicKey, mock(PrivateKey.class));
    objectMapper = mock(ObjectMapper.class);
    decryptor = new JJwtDecryptor(parserFactory, keyPair, objectMapper);
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }// w w w.j a v a2  s .co  m

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:org.apache.karaf.shell.ssh.OpenSSHGeneratorFileKeyProvider.java

@Override
protected KeyPair doReadKeyPair(String resourceKey, InputStream is)
        throws IOException, GeneralSecurityException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    return new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
}

From source file:org.apache.karaf.shell.ssh.keygenerator.OpenSSHKeyPairProvider.java

private KeyPair getKeyPair(FileInputStream is) throws GeneralSecurityException, IOException {
    PKCS8Key pkcs8 = new PKCS8Key(is, password == null ? null : password.toCharArray());
    KeyPair kp = new KeyPair(pkcs8.getPublicKey(), pkcs8.getPrivateKey());
    return kp;//w  w  w . j  a va 2 s .com
}

From source file:com.formkiq.core.service.propertystore.PropertyStoreDatabase.java

@Override
public Optional<KeyPair> retrieveKeyPair() throws GeneralSecurityException {

    Optional<KeyPair> result = Optional.empty();
    String pubkey = this.propertyService.getProperty(null, PUBLIC_KEY);
    String privkey = this.propertyService.getProperty(null, PRIVATE_KEY);

    if (!isEmpty(pubkey) && !isEmpty(privkey)) {
        KeyGenerator keygen = new KeyGenerator();
        RSAPublicKey publickey = keygen.stringToPublicKey(pubkey);
        RSAPrivateKey privatekey = keygen.stringToPrivateKey(privkey);
        result = Optional.of(new KeyPair(publickey, privatekey));
    }// w  ww . j av  a 2 s.  c  om

    return result;
}

From source file:com.mycompany.bankinterface.crypto.Signer.java

private void initKeyPair() throws SignerException {

    char[] passwordBytes = password.toCharArray();
    Key key;/*from   w w w  .j a v  a  2s  .  c  o m*/

    try {
        key = keyStore.getKey(alias, passwordBytes);
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException ex) {
        throw new SignerException("Failed to retrieve key", ex);
    }

    if (key instanceof PrivateKey) {
        java.security.cert.Certificate cert;

        try {
            cert = keyStore.getCertificate(alias);
        } catch (KeyStoreException ex) {
            throw new SignerException("Failed to certificate with alias -->" + alias + "<---", ex);

        }

        PublicKey publicKey = cert.getPublicKey();
        keyPair = new KeyPair(publicKey, (PrivateKey) key);
    }
}

From source file:com.vexsoftware.votifier.crypto.RSAIO.java

/**
 * Loads an RSA key pair from a directory. The directory must have the files
 * "public.key" and "private.key"./*from   w ww .j ava 2 s.  c o  m*/
 * 
 * @param directory
 *            The directory to load from
 * @return The key pair
 * @throws Exception
 *             If an error occurs
 */
public static KeyPair load(File directory) throws Exception {
    // Read the public key file.
    File publicKeyFile = new File(directory + "/public.key");
    byte[] encodedPublicKey = FileUtils.readFileToByteArray(publicKeyFile);
    encodedPublicKey = DatatypeConverter.parseBase64Binary(new String(encodedPublicKey));

    // Read the private key file.
    File privateKeyFile = new File(directory + "/private.key");
    byte[] encodedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
    encodedPrivateKey = DatatypeConverter.parseBase64Binary(new String(encodedPrivateKey));

    // Instantiate and return the key pair.
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
    return new KeyPair(publicKey, privateKey);
}