Example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

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

Introduction

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

Prototype

public PKCS8EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new PKCS8EncodedKeySpec with the given encoded key.

Usage

From source file:com.zxy.commons.codec.rsa.RSAUtils.java

/**
 * <p>/*  w w w  .  j a v  a 2  s. co m*/
 * ?????
 * </p>
 * 
 * @param data ?
 * @param privateKey ?(BASE64?)
 * 
 * @return String
 * @throws Exception Exception
 */
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return new String(Base64.encodeBase64(signature.sign()));
}

From source file:com.nexmo.client.auth.JWTAuthMethod.java

public JWTAuthMethod(final String applicationId, final byte[] privateKey)
        throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    this.applicationId = applicationId;

    byte[] decodedPrivateKey = privateKey;
    if (privateKey[0] == '-') {
        decodedPrivateKey = decodePrivateKey(privateKey);
    }/*from   w w w.ja v a  2s  .c om*/
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(decodedPrivateKey);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PrivateKey key = kf.generatePrivate(spec);
    this.signer = new JWTSigner(key);
}

From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseCreator.control = EasyMock.createStrictControl();

    TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class);
    TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class);

    try {/*  w w w.  ja v  a  2  s .c o  m*/
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider);

    try {
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider);

    LicenseCreator.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseCreator.publicKey = keyPair.getPublic();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream);
    TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray();
}

From source file:org.echocat.marquardt.example.keyprovisioning.KeyFileReadingKeyPairProvider.java

private PrivateKey loadPrivateKey(final String privateKeyFile) {
    LOGGER.debug("Reading private key file {}.", privateKeyFile);
    final byte[] keyFilePayload = readKeyFile(privateKeyFile);
    final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyFilePayload);
    try {//from   ww w . j a v  a 2 s  .c  om
        final KeyFactory keyFactory = KeyFactory.getInstance(rsa.getJavaInternalName());
        return keyFactory.generatePrivate(spec);
    } catch (final GeneralSecurityException e) {
        throw new IllegalArgumentException("Failed to create private key from keyfile " + privateKeyFile + ".",
                e);
    }
}

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

/**
 * Creates a new private and public key and at the same time encodes the public key as XML to be used by the .NET client
 * @param size/*from w ww .  j a  v  a2 s .  c  o  m*/
 * @param productId
 *
 */
private void firstTimeInitialisation(int size) {
    try {

        // Get Key Pair Generator for RSA.
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(size);

        KeyPair keypair = keyGen.genKeyPair();
        privateKey = keypair.getPrivate();
        publicKey = keypair.getPublic();

        // Get the bytes of the public and private keys
        byte[] privateKeyBytes = privateKey.getEncoded();
        byte[] publicKeyBytes = publicKey.getEncoded();

        // store temporarily witht he public key for the lifetime of this class.
        encodedPrivateKey = new Base64().encode(privateKeyBytes);

        // Generate the Private Key, Public Key and Public Key in XML format.
        KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(publicKeyBytes));
        RSAPublicKey rsaPublicKey = (RSAPublicKey) KeyFactory.getInstance("RSA")
                .generatePublic(new X509EncodedKeySpec(publicKeyBytes));

        // Store the public key in XML string to make compatible .Net public key file
        encodedToXMLPublicKey = getRSAPublicKeyAsXMLString(rsaPublicKey);

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

public static KeyPair loadRSAKeys() {
    try {/*from  w w w.ja  v a 2 s.  c om*/
        km_log.i("Loading RSA key pair from disk.");
        byte[] privEncoded = Files.readAllBytes(privkeyFile.toPath());
        byte[] pubEncoded = Files.readAllBytes(pubkeyFile.toPath());

        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(Base64.decodeBase64(pubEncoded));
        PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privEncoded));

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        PublicKey pubkey = keyFactory.generatePublic(pubSpec);
        PrivateKey privkey = keyFactory.generatePrivate(privSpec);

        return new KeyPair(pubkey, privkey);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
        km_log.e("Error while loading keypair!");
        e.printStackTrace();
    }
    return null;
}

From source file:com.spotify.docker.client.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    try {//from  w ww.ja  va2  s . c  om
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Saves public and private keys to specified streams.
 *
 * @param keyPair          the key pair//  w ww  .j a v a2s .  c  om
 * @param privateKeyOutput the private key output stream
 * @param publicKeyOutput  the public key output stream
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void saveKeyPair(KeyPair keyPair, OutputStream privateKeyOutput, OutputStream publicKeyOutput)
        throws IOException {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    publicKeyOutput.write(x509EncodedKeySpec.getEncoded());

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    privateKeyOutput.write(pkcs8EncodedKeySpec.getEncoded());
}

From source file:sec_algo.commonenc.java

/**
* Decrypts an AES key from a file using an RSA private key
*///from ww  w  . j  ava 2s .c o  m
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        pkCipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:hh.learnj.test.license.test.rsacoder.RSACoder.java

/**
 * ?// w  w w . j  av a2s  .co m
 * 
 * @param data
 *            ?
 * @param key
 *            
 * @return byte[] ?
 */
public static byte[] decryptByPrivateKey(byte[] data, byte[] key) throws Exception {
    // ??
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    // ??
    PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
    // ?
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, privateKey);
    return cipher.doFinal(data);
}