Example usage for java.security PublicKey getAlgorithm

List of usage examples for java.security PublicKey getAlgorithm

Introduction

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

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:org.ow2.proactive.authentication.crypto.Credentials.java

/**
 * Creates new encrypted credentials/*from w ww  . ja  v a 2 s .  co m*/
 * <p>
 * Encrypts the message '<code>login</code>:<code>password</code>' using the
 * public key <code>pubKey</code> and <code>cipher</code>
 * and store it in a new Credentials object.
 * 
 * @see KeyPairUtil#encrypt(PublicKey, String, byte[])
 * @param login the login to encrypt
 * @param password the corresponding password to encrypt
 * @param pubKey public key used for encryption
 * @param cipher cipher parameters: combination of transformations
 * @return the Credentials object containing the encrypted data
 * @throws KeyException key generation or encryption failed
 */
@Deprecated
public static Credentials createCredentials(String login, String password, byte[] datakey, PublicKey pubKey,
        String cipher) throws KeyException {

    CredData cc = new CredData();
    cc.setLogin(CredData.parseLogin(login));
    cc.setDomain(CredData.parseDomain(login));
    cc.setPassword(password);
    cc.setKey(datakey);

    // serialize clear credentials to byte array
    byte[] clearCred;
    try {
        clearCred = ObjectToByteConverter.ObjectStream.convert(cc);
    } catch (IOException e1) {
        throw new KeyException(e1.getMessage());
    }

    int size = keySize(pubKey);

    HybridEncryptionUtil.HybridEncryptedData encryptedData = HybridEncryptionUtil.encrypt(pubKey, cipher,
            clearCred);
    byte[] encAes = encryptedData.getEncryptedSymmetricKey();
    byte[] encData = encryptedData.getEncryptedData();

    return new Credentials(pubKey.getAlgorithm(), size, cipher, encAes, encData);
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Creates a test signature and verifies it.
 *
 * @param privateKey Private key to sign with
 * @param publicKey Public key to verify with
 * @param signatureProvider Name of provider to sign with
 * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown
 * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed
 * @throws InvalidKeyException If signature verification failed or the key was invalid
 * @throws SignatureException If the signature could not be made or verified correctly
 *//*from w w  w  . j  ava  2s . c o m*/
public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException {
    final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes();
    final String sigAlg = suggestSigAlg(publicKey);
    if (sigAlg == null) {
        throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm());
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm());
        LOG.debug("testSigAlg: " + sigAlg);
        LOG.debug("provider: " + signatureProvider);
        LOG.trace("privateKey: " + privateKey);
        LOG.trace("privateKey class: " + privateKey.getClass().getName());
        LOG.trace("publicKey: " + publicKey);
        LOG.trace("publicKey class: " + publicKey.getClass().getName());
    }
    final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider);
    signSignature.initSign(privateKey);
    signSignature.update(input);
    byte[] signBA = signSignature.sign();
    if (LOG.isTraceEnabled()) {
        LOG.trace("Created signature of size: " + signBA.length);
        LOG.trace("Created signature: " + new String(Hex.encode(signBA)));
    }

    final Signature verifySignature = Signature.getInstance(sigAlg, "BC");
    verifySignature.initVerify(publicKey);
    verifySignature.update(input);
    if (!verifySignature.verify(signBA)) {
        throw new InvalidKeyException("Test signature inconsistent");
    }
}

From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java

/**
 * Generate a certificate signing request (PKCS#10).
 * @param info A PKCS10CertReqInfo/*from w w w .j a v  a2s.  c om*/
 * @param privateKey Private key for signing the request
 * @param signatureProvider Name of provider to sign with
 * @param publicKey Public key to include in the request
 * @param explicitEccParameters True if the EC domain parameters should be included (ie. not a named curve)
 * @return the certificate request data
 */
public static ICertReqData genCertificateRequest(ISignerCertReqInfo info, final PrivateKey privateKey,
        final String signatureProvider, PublicKey publicKey, final boolean explicitEccParameters)
        throws IllegalArgumentException {
    LOG.debug(">genCertificateRequest");
    final Base64SignerCertReqData retval;
    if (info instanceof PKCS10CertReqInfo) {
        PKCS10CertReqInfo reqInfo = (PKCS10CertReqInfo) info;
        PKCS10CertificationRequest pkcs10;

        if (LOG.isDebugEnabled()) {
            LOG.debug("signatureAlgorithm: " + reqInfo.getSignatureAlgorithm());
            LOG.debug("subjectDN: " + reqInfo.getSubjectDN());
            LOG.debug("explicitEccParameters: " + explicitEccParameters);
        }

        try {
            // Handle ECDSA key with explicit parameters
            if (explicitEccParameters && publicKey.getAlgorithm().contains("EC")) {
                publicKey = ECKeyUtil.publicToExplicitParameters(publicKey, "BC");
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Public key SHA1: " + createKeyHash(publicKey));
                LOG.debug("Public key SHA256: " + KeyUsageCounterHash.create(publicKey));
            }

            // Generate request
            final JcaPKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(
                    new X500Name(CertTools.stringToBCDNString(reqInfo.getSubjectDN())), publicKey);
            final ContentSigner contentSigner = new JcaContentSignerBuilder(reqInfo.getSignatureAlgorithm())
                    .setProvider(signatureProvider).build(privateKey);
            pkcs10 = builder.build(contentSigner);
            retval = new Base64SignerCertReqData(Base64.encode(pkcs10.getEncoded()));
        } catch (IOException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (OperatorCreationException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        } catch (NoSuchProviderException e) {
            throw new IllegalArgumentException("Certificate request error: " + e.getMessage(), e);
        }
        LOG.debug("<genCertificateRequest");
        return retval;
    } else {
        throw new IllegalArgumentException(
                "Unsupported certificate request info type: " + info.getClass().getName());
    }
}

From source file:org.tolven.connectors.passwordstore.PasswordStoreImpl.java

/**
 * Set password to have this alias//ww  w .j  a  v a 2  s. c  o  m
 */
public String setPassword(String alias, char[] password) {
    String encryptedPassword;
    try {
        String keyStoreAlias = getKeyStore().aliases().nextElement();
        X509Certificate x509Certificate = (X509Certificate) getKeyStore().getCertificate(keyStoreAlias);
        PublicKey publicKey = x509Certificate.getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedBytes = cipher.doFinal(getBytes(password));
        encryptedPassword = new String(Base64.encodeBase64(encryptedBytes), Charset.forName("UTF-8"));
        getEncryptedPasswordStore().getEncryptedPasswords().put(alias, encryptedPassword);
    } catch (Exception ex) {
        throw new RuntimeException("Could not set password for alias: " + alias, ex);
    }
    return encryptedPassword;
}

From source file:org.tolven.security.password.PasswordHolder.java

private void generateSecretKey(File secretKeyFile) {
    if (getSecretKeyFile().exists()) {
        throw new RuntimeException("A secretkey file already exists at: " + getSecretKeyFile().getPath());
    }/*from   w  ww  . j  a  va  2 s .  c  o  m*/
    try {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("DESede");
        keyGenerator.init(112);
        secretKey = keyGenerator.generateKey();
        String alias = getKeyStore().aliases().nextElement();
        Certificate adminCert = getKeyStore().getCertificate(alias);
        PublicKey publicKey = adminCert.getPublicKey();
        Cipher cipher = Cipher.getInstance(publicKey.getAlgorithm());
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] encryptedSecretKey = cipher.wrap(secretKey);
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(secretKeyFile);
            out.write(Base64.encodeBase64(encryptedSecretKey));
        } finally {
            if (out != null) {
                out.close();
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException("Could not generate secret key for file: " + secretKeyFile.getPath(), ex);
    }
}

From source file:uk.ac.ed.epcc.webapp.ssh.PublicKeyReaderUtil.java

/** format a key (of the types supported by the {@link #load(String)} method. 
 * /*w  w w .j a v  a 2  s  .  c  o m*/
 * @param key
 * @return public key string
 * @throws PublicKeyParseException 
 * @throws IOException 
 */
public static String format(PublicKey key) throws PublicKeyParseException, IOException {
    StringBuilder sb = new StringBuilder();
    String alg = key.getAlgorithm();
    if (alg.equalsIgnoreCase("RSA")) {
        RSAPublicKey pub = (RSAPublicKey) key;
        sb.append(SSH2_RSA_KEY);
        sb.append(" ");
        SSH2ByteBuffer buf = new SSH2ByteBuffer();
        buf.writeString(SSH2_RSA_KEY);
        buf.writeMPint(pub.getPublicExponent());
        buf.writeMPint(pub.getModulus());
        sb.append(Base64.encodeBase64String(buf.toByteArray()));
    } else if (alg.equalsIgnoreCase("DSA")) {
        DSAPublicKey pub = (DSAPublicKey) key;
        sb.append(SSH2_DSA_KEY);
        sb.append(" ");
        SSH2ByteBuffer buf = new SSH2ByteBuffer();
        buf.writeString(SSH2_DSA_KEY);
        DSAParams params = pub.getParams();
        buf.writeMPint(params.getP());
        buf.writeMPint(params.getQ());
        buf.writeMPint(params.getG());
        buf.writeMPint(pub.getY());
        sb.append(Base64.encodeBase64String(buf.toByteArray()));
    } else {
        throw new PublicKeyParseException(ErrorCode.UNKNOWN_PUBLIC_KEY_FILE_FORMAT);
    }
    return sb.toString();
}

From source file:uk.org.ukfederation.mda.validate.X509RSAOpenSSLBlacklistValidator.java

/** {@inheritDoc} */
@Override/*from www . j  a va  2s .  c  o  m*/
public void validate(@Nonnull final X509Certificate cert, @Nonnull final Item<?> item,
        @Nonnull final String stageId) throws StageProcessingException {
    ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this);
    final PublicKey key = cert.getPublicKey();
    if ("RSA".equals(key.getAlgorithm())) {
        final RSAPublicKey rsaKey = (RSAPublicKey) key;
        final BigInteger modulus = rsaKey.getModulus();
        if (keySize == 0 || keySize == modulus.bitLength()) {
            final String value = openSSLDigest(modulus);
            if (blacklistedValues.contains(value)) {
                addError("RSA modulus included in key blacklist (" + value + ")", item, stageId);
            }
        }
    }
}

From source file:vellum.cryptostore.RsaStoreTest.java

public void testGenerate(int iterationCount) throws Exception {
    long millis = System.currentTimeMillis();
    RsaKeyStore ks = new RsaKeyStore();
    ks.generate(alias, keySize);/*  w w w .  j  a  va  2s . c  o  m*/
    ByteArrayOutputStream kos = new ByteArrayOutputStream();
    ks.storePublic(kos);
    ByteArrayInputStream kis = new ByteArrayInputStream(kos.toByteArray());
    PublicKey loadedPublicKey = ks.loadPublic(kis);
    System.out.printf("loaded public key %s %s: %s\n", alias, loadedPublicKey.getAlgorithm(),
            Base64.encodeBase64String(loadedPublicKey.getEncoded()));
    assertTrue("loaded public key",
            Arrays.equals(ks.getKeyPair().getPublic().getEncoded(), loadedPublicKey.getEncoded()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new RsaStore().store(baos, type, alias, text.getBytes(), ks.getKeyPair().getPublic());
    millis = Millis.elapsed(millis);
    System.out.printf("store %s %d %dms: %s\n", alias, iterationCount, millis, text);
    millis = System.currentTimeMillis();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    kos = new ByteArrayOutputStream();
    ks.storePrivate(kos, password);
    kis = new ByteArrayInputStream(kos.toByteArray());
    PrivateKey loadedPrivateKey = ks.loadPrivate(kis, alias, password);
    assertTrue("loaded private key",
            Arrays.equals(ks.getKeyPair().getPrivate().getEncoded(), loadedPrivateKey.getEncoded()));
    millis = Millis.elapsed(millis);
    System.out.printf("loaded private key %s %d %dms: %s\n", alias, iterationCount, millis,
            loadedPrivateKey.getAlgorithm());
    millis = System.currentTimeMillis();
    byte[] loadBytes = new RsaStore().load(bais, type, alias, loadedPrivateKey);
    millis = Millis.elapsed(millis);
    System.out.printf("load %s %d %dms: %s\n", alias, iterationCount, millis, new String(loadBytes));
    assertTrue("loaded bytes", Arrays.equals(loadBytes, text.getBytes()));
}