Example usage for java.security Key getFormat

List of usage examples for java.security Key getFormat

Introduction

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

Prototype

public String getFormat();

Source Link

Document

Returns the name of the primary encoding format of this key, or null if this key does not support encoding.

Usage

From source file:Main.java

public static String formatKey(Key key) {
    String algo = key.getAlgorithm();
    String fmt = key.getFormat();
    byte[] encoded = key.getEncoded();
    return "Key[algorithm=" + algo + ", format=" + fmt + ", bytes=" + encoded.length + "]";
}

From source file:com.kuzumeji.platform.standard.SecurityServiceTest.java

private static String dumpKeyPair(final Key key) {
    return MessageFormat.format("?:{0} ?:{1} ?:{2}", key.getAlgorithm(), key.getFormat(),
            Hex.encodeHexString(key.getEncoded()));
}

From source file:com.google.api.auth.DefaultJwksSupplierTest.java

private static void assertKeysEqual(Key expected, Key actual) {
    assertEquals(expected.getAlgorithm(), actual.getAlgorithm());
    assertEquals(new String(Hex.encode(expected.getEncoded())), new String(Hex.encode(actual.getEncoded())));
    assertEquals(expected.getFormat(), actual.getFormat());
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

public byte[] loadSecretKey() {
    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    Key key = null;
    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);//from   www.j a v a  2  s .c om
        key = ks.getKey(keystorePKAlias, ksKeyPassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException e) {
        LOGGER.error("Exception occured during the loading of the secret key. {}", e);
        throw new RuntimeException(e);
    }
    if (key == null) {
        return new byte[0];
    }
    LOGGER.info("Algorithm: " + key.getAlgorithm());
    LOGGER.info("Format: " + key.getFormat());
    return key.getEncoded();
}

From source file:mitm.common.security.keystore.hibernate.SerializableKeyEntry.java

public SerializableKeyEntry(Key key, char[] password, PBEncryption encryptor)
        throws InvalidKeyException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {
    if (encryptor == null || password == null) {
        this.rawKey = key.getEncoded();
        this.protection = Protection.NONE;
    } else {//w  w  w  . j  a v a 2  s  . c om
        this.rawKey = encryptor.encrypt(key.getEncoded(), password);
        this.protection = Protection.ENCRYPTED;
    }

    this.algorithm = key.getAlgorithm();
    this.format = key.getFormat();

    if (key instanceof PrivateKey) {
        keyType = KeyType.PRIVATE;
    } else {
        if (key instanceof PublicKey) {
            keyType = KeyType.PUBLIC;
        } else {
            keyType = KeyType.SECRET;
        }
    }
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.ConnectorFactoryIcfImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result/*  ww  w  .ja va2s . c  o m*/
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryIcfImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:com.evolveum.midpoint.provisioning.ucf.impl.connid.ConnectorFactoryConnIdImpl.java

private void selfTestGuardedString(OperationResult parentTestResult) {
    OperationResult result = parentTestResult
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString");

    OperationResult subresult = result/*ww  w .jav  a  2 s  . c  o m*/
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptorReflection");
    EncryptorFactory encryptorFactory = EncryptorFactory.getInstance();
    subresult.addReturn("encryptorFactoryImpl", encryptorFactory.getClass());
    LOGGER.debug("Encryptor factory implementation class: {}", encryptorFactory.getClass());
    Encryptor encryptor = EncryptorFactory.getInstance().newRandomEncryptor();
    subresult.addReturn("encryptorImpl", encryptor.getClass());
    LOGGER.debug("Encryptor implementation class: {}", encryptor.getClass());
    if (encryptor.getClass().getName().equals("org.identityconnectors.common.security.impl.EncryptorImpl")) {
        // let's do some reflection magic to have a look inside
        try {
            LOGGER.trace("Encryptor fields: {}", Arrays.asList(encryptor.getClass().getDeclaredFields()));
            Field keyField = encryptor.getClass().getDeclaredField("key");
            keyField.setAccessible(true);
            Key key = (Key) keyField.get(encryptor);
            subresult.addReturn("keyAlgorithm", key.getAlgorithm());
            subresult.addReturn("keyLength", key.getEncoded().length * 8);
            subresult.addReturn("keyFormat", key.getFormat());
            subresult.recordSuccess();
        } catch (IllegalArgumentException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (IllegalAccessException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (NoSuchFieldException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        } catch (SecurityException e) {
            subresult.recordPartialError("Reflection introspection failed", e);
        }
    }

    OperationResult encryptorSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.encryptor");
    try {
        String plainString = "Scurvy seadog";
        byte[] encryptedBytes = encryptor.encrypt(plainString.getBytes());
        byte[] decryptedBytes = encryptor.decrypt(encryptedBytes);
        String decryptedString = new String(decryptedBytes);
        if (!plainString.equals(decryptedString)) {
            encryptorSubresult.recordFatalError(
                    "Encryptor roundtrip failed; encrypted=" + plainString + ", decrypted=" + decryptedString);
        } else {
            encryptorSubresult.recordSuccess();
        }
    } catch (Throwable e) {
        LOGGER.error("Encryptor operation error: {}", e.getMessage(), e);
        encryptorSubresult.recordFatalError("Encryptor opeation error: " + e.getMessage(), e);
    }

    final OperationResult guardedStringSubresult = result
            .createSubresult(ConnectorFactoryConnIdImpl.class + ".selfTestGuardedString.guardedString");
    // try to encrypt and decrypt GuardedString
    try {
        final String origString = "Shiver me timbers";
        // This should encrypt it
        GuardedString guardedString = new GuardedString(origString.toCharArray());
        // and this should decrypt it
        guardedString.access(new GuardedString.Accessor() {
            @Override
            public void access(char[] decryptedChars) {
                if (!(new String(decryptedChars)).equals(origString)) {
                    guardedStringSubresult.recordFatalError("GuardeString roundtrip failed; encrypted="
                            + origString + ", decrypted=" + (new String(decryptedChars)));
                }
            }
        });
        guardedStringSubresult.recordSuccessIfUnknown();
    } catch (Throwable e) {
        LOGGER.error("GuardedString operation error: {}", e.getMessage(), e);
        guardedStringSubresult.recordFatalError("GuardedString opeation error: " + e.getMessage(), e);
    }

    result.computeStatus();
}

From source file:nl.b3p.viewer.admin.stripes.CycloramaConfigurationActionBean.java

private String getBase64EncodedPrivateKeyFromPfxUpload(InputStream in, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {

    String base64 = null;//from  www . j  ava 2 s . co  m

    PrivateKey privateKey = null;

    KeyStore ks = java.security.KeyStore.getInstance(CERT_TYPE);
    ks.load(new BufferedInputStream(in), password.toCharArray());

    Enumeration<String> aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        Key ksKey = ks.getKey(alias, password.toCharArray());
        String keyFormat = ksKey.getFormat();

        if ((ksKey instanceof RSAPrivateCrtKeyImpl) && keyFormat.equals(KEY_FORMAT)) {
            privateKey = (PrivateKey) ksKey;
        }
    }

    if (privateKey != null) {
        Base64 encoder = new Base64();
        base64 = new String(encoder.encode(privateKey.getEncoded()));
    }

    return base64;
}

From source file:org.apache.hadoop.io.crypto.KeyStoreKeyProvider.java

/**
 * Implementation of getting keys from the key store.
 *//*  w  w  w.  j a  va2s. co  m*/
@Override
public Key[] getKeys(String[] keyNames) throws CryptoException {
    if (keyStore == null)
        throw new CryptoException("Key store is not intialized.");

    if (keyNames == null)
        return null;

    Key[] rawKeys = new Key[keyNames.length];

    try {
        for (int i = 0; i < keyNames.length; i++) {
            String keyName = keyNames[i];
            String password = getKeyPassword(keyName);

            char[] passphase = null;
            if (password != null)
                passphase = password.toCharArray();

            Key.KeyType keyType = Key.KeyType.OPAQUE;
            String algorithm = null;
            String format = null;
            byte[] rawKey;

            java.security.Key key = keyStore.getKey(keyName, passphase);
            if (key != null) {
                // secret key or private key
                rawKey = key.getEncoded();
                algorithm = key.getAlgorithm();
                format = key.getFormat();

                if (key instanceof SecretKey) {
                    keyType = Key.KeyType.SYMMETRIC_KEY;
                } else if (key instanceof PrivateKey) {
                    keyType = Key.KeyType.PRIVATE_KEY;
                }
            } else {
                // trusted certificate
                Certificate certificate = keyStore.getCertificate(keyName);
                if (certificate == null)
                    throw new CryptoException("Key " + keyName + " not found");

                keyType = Key.KeyType.CERTIFICATE;
                rawKey = certificate.getEncoded();
            }

            rawKeys[i] = new Key(keyType, algorithm, 0, format, rawKey);
        }
    } catch (KeyStoreException e) {
        throw new CryptoException(e);
    } catch (UnrecoverableEntryException e) {
        throw new CryptoException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new CryptoException(e);
    } catch (CertificateException e) {
        throw new CryptoException(e);
    }

    return rawKeys;
}

From source file:org.ejbca.core.protocol.ws.client.NestedCrmfRequestTestCommand.java

private void init(String args[]) {

    FileInputStream file_inputstream;
    try {//from  w w w .  j  a  v  a2 s. c  o  m
        String pwd = args[ARG_KEYSTOREPASSWORD];
        String certNameInKeystore = args[ARG_CERTNAMEINKEYSTORE];
        file_inputstream = new FileInputStream(args[ARG_KEYSTOREPATH]);
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        keyStore.load(file_inputstream, pwd.toCharArray());
        System.out.println("Keystore size " + keyStore.size());
        Enumeration aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            System.out.println(aliases.nextElement());
        }
        Key key = keyStore.getKey(certNameInKeystore, pwd.toCharArray());
        getPrintStream().println("Key information " + key.getAlgorithm() + " " + key.getFormat());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(key.getEncoded());
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        innerSignKey = keyFactory.generatePrivate(keySpec);
        innerCertificate = keyStore.getCertificate(certNameInKeystore);
    } catch (FileNotFoundException e2) {
        e2.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeySpecException e) {
        e.printStackTrace();
    }

    try {
        KeyPair outerSignKeys = KeyTools.genKeys("1024", "RSA");
        outerSignKey = outerSignKeys.getPrivate();
        X509Certificate signCert = CertTools.genSelfCert("CN=cmpTest,C=SE", 5000, null,
                outerSignKeys.getPrivate(), outerSignKeys.getPublic(),
                PKCSObjectIdentifiers.sha256WithRSAEncryption.getId(), true, "BC");

        writeCertificate(signCert, "/opt/racerts", "cmpTest.pem");

        /*
        ArrayList<Certificate> certCollection = new ArrayList<Certificate>();
        certCollection.add(signCert);
        byte[] pemRaCert = CertTools.getPEMFromCerts(certCollection);
                
        FileOutputStream out = new FileOutputStream(new File("/opt/racerts/cmpStressTest.pem"));
        out.write(pemRaCert);
        out.close();
        */
    } catch (NoSuchAlgorithmException e1) {
        e1.printStackTrace();
    } catch (NoSuchProviderException e1) {
        e1.printStackTrace();
    } catch (InvalidAlgorithmParameterException e1) {
        e1.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
        //} catch (FileNotFoundException e) {
        //   e.printStackTrace();
        //} catch (IOException e) {
        //   e.printStackTrace();
        //} catch (CertificateException e) {
        //   e.printStackTrace();
    }

}