Example usage for java.security PublicKey getEncoded

List of usage examples for java.security PublicKey getEncoded

Introduction

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

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();//from w w  w  .  j ava 2s. c  om

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}

From source file:com.owncloud.android.utils.PushUtils.java

public static void pushRegistrationToServer() {
    String token = PreferenceManager.getPushToken(MainApp.getAppContext());
    arbitraryDataProvider = new ArbitraryDataProvider(MainApp.getAppContext().getContentResolver());

    if (!TextUtils.isEmpty(MainApp.getAppContext().getResources().getString(R.string.push_server_url))
            && !TextUtils.isEmpty(token)) {
        PushUtils.generateRsa2048KeyPair();
        String pushTokenHash = PushUtils.generateSHA512Hash(token).toLowerCase();
        PublicKey devicePublicKey = (PublicKey) PushUtils.readKeyFromFile(true);
        if (devicePublicKey != null) {
            byte[] publicKeyBytes = Base64.encode(devicePublicKey.getEncoded(), Base64.NO_WRAP);
            String publicKey = new String(publicKeyBytes);
            publicKey = publicKey.replaceAll("(.{64})", "$1\n");

            publicKey = "-----BEGIN PUBLIC KEY-----\n" + publicKey + "\n-----END PUBLIC KEY-----\n";

            Context context = MainApp.getAppContext();
            String providerValue;
            PushConfigurationState accountPushData = null;
            Gson gson = new Gson();
            for (Account account : AccountUtils.getAccounts(context)) {
                providerValue = arbitraryDataProvider.getValue(account, KEY_PUSH);
                if (!TextUtils.isEmpty(providerValue)) {
                    accountPushData = gson.fromJson(providerValue, PushConfigurationState.class);
                } else {
                    accountPushData = null;
                }/*from w w w . j  a v a2 s  .  c  o  m*/

                if (accountPushData != null && !accountPushData.getPushToken().equals(token)
                        && !accountPushData.isShouldBeDeleted() || TextUtils.isEmpty(providerValue)) {
                    try {
                        OwnCloudAccount ocAccount = new OwnCloudAccount(account, context);
                        OwnCloudClient mClient = OwnCloudClientManagerFactory.getDefaultSingleton()
                                .getClientFor(ocAccount, context);

                        RemoteOperation registerAccountDeviceForNotificationsOperation = new RegisterAccountDeviceForNotificationsOperation(
                                pushTokenHash, publicKey,
                                context.getResources().getString(R.string.push_server_url));

                        RemoteOperationResult remoteOperationResult = registerAccountDeviceForNotificationsOperation
                                .execute(mClient);

                        if (remoteOperationResult.isSuccess()) {
                            PushResponse pushResponse = remoteOperationResult.getPushResponseData();

                            RemoteOperation registerAccountDeviceForProxyOperation = new RegisterAccountDeviceForProxyOperation(
                                    context.getResources().getString(R.string.push_server_url), token,
                                    pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                    pushResponse.getPublicKey());

                            remoteOperationResult = registerAccountDeviceForProxyOperation.execute(mClient);

                            if (remoteOperationResult.isSuccess()) {
                                PushConfigurationState pushArbitraryData = new PushConfigurationState(token,
                                        pushResponse.getDeviceIdentifier(), pushResponse.getSignature(),
                                        pushResponse.getPublicKey(), false);
                                arbitraryDataProvider.storeOrUpdateKeyValue(account.name, KEY_PUSH,
                                        gson.toJson(pushArbitraryData));
                            }
                        }
                    } catch (com.owncloud.android.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
                        Log_OC.d(TAG, "Failed to find an account");
                    } catch (AuthenticatorException e) {
                        Log_OC.d(TAG, "Failed via AuthenticatorException");
                    } catch (IOException e) {
                        Log_OC.d(TAG, "Failed via IOException");
                    } catch (OperationCanceledException e) {
                        Log_OC.d(TAG, "Failed via OperationCanceledException");
                    }
                } else if (accountPushData != null && accountPushData.isShouldBeDeleted()) {
                    deleteRegistrationForAccount(account);
                }
            }
        }
    }
}

From source file:net.link.util.common.KeyUtils.java

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) {

    try {/*from www  .  j  ava 2  s .c o  m*/
        ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bais).readObject());

        return new SubjectKeyIdentifier(info);
    } catch (IOException e) {
        throw new InternalInconsistencyException("Can't read from a ByteArrayInputStream?", e);
    }
}

From source file:net.link.util.common.KeyUtils.java

@SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) {

    try {//  w  ww  .jav  a2 s . co m
        ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
        SubjectPublicKeyInfo info = new SubjectPublicKeyInfo(
                (ASN1Sequence) new ASN1InputStream(bais).readObject());

        return new AuthorityKeyIdentifier(info);
    } catch (IOException e) {
        throw new InternalInconsistencyException("Can't read from a ByteArrayInputStream?", e);
    }
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

/**
 * @param gen/*  w w  w.j  av  a  2  s  . c  o m*/
 * @param pubKey
 *
 * @throws IOException
 */
private static void addSubjectKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey) throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo spki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            SubjectKeyIdentifier ski = new SubjectKeyIdentifier(spki);
            gen.addExtension(X509Extensions.SubjectKeyIdentifier.getId(), false, ski);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Method calculates a fingerprint for the given public key instance
 * //w ww .j av  a2s .  c  o m
 * @param pubKey
 * @return secure hash {@link KeyConstants#PUBKEY_FINGERPRINT_DIGEST} of the
 *         encoded public key, or null if there was an error
 */
public static byte[] getPublicKeyfingerprint(PublicKey pubKey) {
    try {
        MessageDigest mdFingerprint = MessageDigest.getInstance(KeyConstants.PUBKEY_FINGERPRINT_DIGEST,
                KeyConstants.PROV_BC);
        byte[] enc = pubKey.getEncoded();
        if (enc != null && enc.length != 0) {
            return mdFingerprint.digest(enc);
        } else {
            logger.error(CryptCore.class.getName() + "::getPublicKeyFingerprint: Invalid public key!");
        }
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        logger.error(CryptCore.class.getName()
                + "::getPublicKeyFingerprint: Could not init digest for fingerprinting!", e);
    }
    return null;
}

From source file:com.peterphi.std.crypto.keygen.CaHelper.java

/**
 * @param gen/*w w  w  . ja  va  2 s.  c o  m*/
 * @param pubKey
 *
 * @throws IOException
 */
private static void addAuthorityKeyIdentifier(X509V3CertificateGenerator gen, PublicKey pubKey)
        throws Exception {
    {
        ASN1InputStream is = new ASN1InputStream(new ByteArrayInputStream(pubKey.getEncoded()));
        try {
            SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) is.readObject());
            AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);

            gen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), false, aki);
        } finally {
            IOUtils.closeQuietly(is);
        }
    }
}

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

/**
 * PEM encode a public key/*from w  ww.  ja v a2  s.c  o  m*/
 *
 * @param pubKey Public
 * @return PEM encoded public key string
 */
public static String pemEncode(PublicKey pubKey) {
    String toReturn;
    if (pubKey instanceof RSAPublicKey) {
        final String keyHeader = FIVE_DASH + "BEGIN PUBLIC KEY" + FIVE_DASH;
        final String keyFooter = FIVE_DASH + "END PUBLIC KEY" + FIVE_DASH;
        Base64 encoder = new Base64(64);
        toReturn = String.join("\n", keyHeader, new String(encoder.encode(pubKey.getEncoded())), keyFooter);
    } else {
        throw new UnsupportedOperationException("Unknown public key type.  Only implemented for RSAPublicKey.");
    }
    return CryptoUtil.fixPemString(toReturn);
}

From source file:test.integ.be.fedict.trust.util.TestUtils.java

private static SubjectKeyIdentifier createSubjectKeyId(PublicKey publicKey) throws IOException {

    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());
    return new SubjectKeyIdentifier(info);
}

From source file:test.integ.be.fedict.trust.util.TestUtils.java

private static AuthorityKeyIdentifier createAuthorityKeyId(PublicKey publicKey) throws IOException {

    ByteArrayInputStream bais = new ByteArrayInputStream(publicKey.getEncoded());
    SubjectPublicKeyInfo info = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(bais).readObject());

    return new AuthorityKeyIdentifier(info);
}