Example usage for java.security PrivateKey getAlgorithm

List of usage examples for java.security PrivateKey getAlgorithm

Introduction

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

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

From source file:com.vmware.identity.rest.idm.data.PrivateKeyDTO.java

private static String encodePrivateKey(PrivateKey key)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    if (key == null) {
        return null;
    }/*  w  w  w .  ja v  a2s.  c  o  m*/

    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
    byte[] packed = spec.getEncoded();
    String encodePrivateKey = Base64.encodeBase64String(packed);
    Arrays.fill(packed, (byte) 0);
    return encodePrivateKey;
}

From source file:Main.java

public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException,
        XMLSignatureException {// w  ww  .  ja v  a2 s .  co m

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    String method = SignatureMethod.RSA_SHA1; // default

    if ("DSA".equals(privKey.getAlgorithm()))
        method = SignatureMethod.DSA_SHA1;

    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical
            (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null),
            Collections.singletonList(ref));

    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(pubKey);

    // Create a KeyInfo and add the KeyValue to it
    List<XMLStructure> kidata = new ArrayList<XMLStructure>();
    kidata.add(kv);
    KeyInfo ki = kif.newKeyInfo(kidata);

    // Create a DOMSignContext and specify the PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privKey, doc);

    // Create the XMLSignature (but don't sign it yet)
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Marshal, generate (and sign) the enveloped signature
    signature.sign(dsc);

}

From source file:org.lockss.util.KeyStoreUtil.java

private static void initializeKeyStore(KeyStore keyStore, Configuration config)
        throws CertificateException, IOException, InvalidKeyException, KeyStoreException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, UnrecoverableKeyException {
    String keyAlias = config.get(PROP_KEY_ALIAS, DEFAULT_KEY_ALIAS);
    String certAlias = config.get(PROP_CERT_ALIAS, DEFAULT_CERT_ALIAS);
    String keyAlgName = config.get(PROP_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM);
    String sigAlgName = config.get(PROP_SIG_ALGORITHM, DEFAULT_SIG_ALGORITHM);
    String keyStorePassword = config.get(PROP_KEYSTORE_PASSWORD);
    String keyPassword = config.get(PROP_KEY_PASSWORD);
    int keyBits = config.getInt(PROP_KEY_BITS, DEFAULT_KEY_BITS);
    long expireIn = config.getTimeInterval(PROP_EXPIRE_IN, DEFAULT_EXPIRE_IN);
    String x500String = config.get(PROP_X500_NAME, DEFAULT_X500_NAME);

    CertAndKeyGen keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    keypair.generate(keyBits);// w ww  . java2s . co  m

    PrivateKey privKey = keypair.getPrivateKey();
    log.debug3("PrivKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());

    X509Certificate[] chain = new X509Certificate[1];

    X500Name x500Name = new X500Name(x500String);
    chain[0] = keypair.getSelfCertificate(x500Name, expireIn);
    log.debug3("Certificate: " + chain[0].toString());

    keyStore.load(null, keyStorePassword.toCharArray());
    keyStore.setCertificateEntry(certAlias, chain[0]);
    keyStore.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), chain);
    Key myKey = keyStore.getKey(keyAlias, keyPassword.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
}

From source file:org.lockss.util.KeyStoreUtil.java

private static void initializeKeyStore(KeyStore keyStore, String domainName, String password)
        throws IOException, CertificateException, InvalidKeyException, SignatureException,
        NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException {
    String keyAlias = domainName + keySuffix;
    String certAlias = domainName + crtSuffix;
    String keyStorePassword = domainName;
    String keyStoreFileName = domainName + ".jceks";
    File keyStoreFile = new File(keyStoreFileName);
    if (keyStoreFile.exists()) {
        log.debug("Key store file " + keyStoreFileName + " exists");
        throw new IOException("Key store file " + keyStoreFileName + " exists");
    }//from w w w. j  a  v a 2s  .  c o  m
    String keyAlgName = "RSA";
    String sigAlgName = "MD5WithRSA";
    log.debug("About to create a CertAndKeyGen: " + keyAlgName + " " + sigAlgName);
    CertAndKeyGen keypair;
    try {
        keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    } catch (NoSuchAlgorithmException e) {
        log.debug("new CertAndKeyGen(" + keyAlgName + "," + sigAlgName + ") threw " + e);
        throw e;
    }
    log.debug("About to generate a key pair");
    try {
        keypair.generate(1024);
    } catch (InvalidKeyException e) {
        log.debug("keypair.generate(1024) threw " + e);
        throw e;
    }
    log.debug("About to get a PrivateKey");
    PrivateKey privKey = keypair.getPrivateKey();
    log.debug("MyKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());
    log.debug("About to get a self-signed certificate");
    X509Certificate[] chain = new X509Certificate[1];
    X500Name x500Name = new X500Name(
            "CN=" + domainName + ", " + "OU=LOCKSS Team, O=Stanford, " + "L=Stanford, S=California, C=US");
    chain[0] = keypair.getSelfCertificate(x500Name, 365 * 24 * 60 * 60);
    log.debug("Certificate: " + chain[0].toString());
    log.debug("About to keyStore.load(null)");
    try {
        keyStore.load(null, keyStorePassword.toCharArray());
    } catch (IOException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (CertificateException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (NoSuchAlgorithmException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    }
    log.debug("About to store " + certAlias + " in key store");
    try {
        keyStore.setCertificateEntry(certAlias, chain[0]);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setCertificateEntry() threw " + e);
        throw e;
    }
    log.debug("About to store " + keyAlias + " in key store");
    try {
        keyStore.setKeyEntry(keyAlias, privKey, password.toCharArray(), chain);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setKeyEntry() threw " + e);
        throw e;
    }
    log.debug("About to getKeyEntry()");
    Key myKey = keyStore.getKey(keyAlias, password.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
    log.debug("Done storing");
}

From source file:org.opensaml.security.crypto.SigningUtil.java

/**
 * Compute the raw signature value over the supplied input.
 * //from   www .java  2s.  c o m
 * It is up to the caller to ensure that the specified algorithm ID is consistent with the type of signing key
 * supplied.
 * 
 * @param signingKey the private key with which to compute the signature
 * @param jcaAlgorithmID the Java JCA algorithm ID to use
 * @param input the input over which to compute the signature
 * @return the computed signature value
 * @throws SecurityException thrown if the signature computation results in an error
 */
@Nonnull
public static byte[] sign(@Nonnull final PrivateKey signingKey, @Nonnull final String jcaAlgorithmID,
        @Nonnull final byte[] input) throws SecurityException {
    Constraint.isNotNull(signingKey, "Private key cannot be null");
    Constraint.isNotNull(jcaAlgorithmID, "JCA algorithm ID cannot be null");
    Constraint.isNotNull(input, "Input data to sign cannot be null");

    Logger log = getLogger();
    log.debug("Computing signature over input using private key of type {} and JCA algorithm ID {}",
            signingKey.getAlgorithm(), jcaAlgorithmID);

    try {
        Signature signature = Signature.getInstance(jcaAlgorithmID);
        signature.initSign(signingKey);
        signature.update(input);
        byte[] rawSignature = signature.sign();
        log.debug("Computed signature: {}", Hex.encodeHex(rawSignature));
        return rawSignature;
    } catch (GeneralSecurityException e) {
        log.error("Error during signature generation", e);
        throw new SecurityException("Error during signature generation", e);
    }
}

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

public static X509Certificate generateCertificate(PublicKey subjectPublicKey, String subjectDn,
        PrivateKey issuerPrivateKey, @Nullable X509Certificate issuerCert, DateTime notBefore,
        DateTime notAfter, String inSignatureAlgorithm, boolean caCert, boolean timeStampingPurpose,
        @Nullable URI ocspUri) {/*from   ww  w.  j  ava2s .  c  o  m*/

    try {
        String signatureAlgorithm = inSignatureAlgorithm;
        if (null == signatureAlgorithm)
            signatureAlgorithm = String.format("SHA1With%s", issuerPrivateKey.getAlgorithm());

        X509Principal issuerDN;
        if (null != issuerCert)
            issuerDN = new X509Principal(issuerCert.getSubjectX500Principal().toString());
        else
            issuerDN = new X509Principal(subjectDn);

        // new bc 2.0 API
        X509Principal subject = new X509Principal(subjectDn);
        SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(subjectPublicKey.getEncoded());
        BigInteger serialNumber = new BigInteger(SERIALNUMBER_NUM_BITS, new SecureRandom());

        X509v3CertificateBuilder certificateBuilder = new X509v3CertificateBuilder(
                X500Name.getInstance(issuerDN.toASN1Primitive()), serialNumber, notBefore.toDate(),
                notAfter.toDate(), X500Name.getInstance(subject.toASN1Primitive()), publicKeyInfo);

        // prepare signer
        ContentSigner signer = new JcaContentSignerBuilder(signatureAlgorithm).build(issuerPrivateKey);
        certificateBuilder.addExtension(X509Extension.subjectKeyIdentifier, false,
                createSubjectKeyId(subjectPublicKey));
        PublicKey issuerPublicKey;
        if (null != issuerCert)
            issuerPublicKey = issuerCert.getPublicKey();
        else
            issuerPublicKey = subjectPublicKey;
        certificateBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
                createAuthorityKeyId(issuerPublicKey));

        certificateBuilder.addExtension(X509Extension.basicConstraints, false, new BasicConstraints(caCert));

        if (timeStampingPurpose)
            certificateBuilder.addExtension(X509Extension.extendedKeyUsage, true,
                    new ExtendedKeyUsage(KeyPurposeId.id_kp_timeStamping));

        if (null != ocspUri) {
            GeneralName ocspName = new GeneralName(GeneralName.uniformResourceIdentifier, ocspUri.toString());
            AuthorityInformationAccess authorityInformationAccess = new AuthorityInformationAccess(
                    X509ObjectIdentifiers.ocspAccessMethod, ocspName);
            certificateBuilder.addExtension(X509Extension.authorityInfoAccess, false,
                    authorityInformationAccess);
        }

        // build
        return new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certificateBuilder.build(signer));
    } catch (CertificateException e) {
        throw new InternalInconsistencyException("X.509 is not supported.", e);
    } catch (OperatorCreationException e) {
        throw new InternalInconsistencyException(e);
    } catch (CertIOException e) {
        throw new InternalInconsistencyException(e);
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpMessageHelper.java

public static PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts,
        PrivateKey key, String digestAlg, String provider) throws NoSuchProviderException,
        NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException {
    // Select which signature algorithm we should use for the response, based on the digest algorithm and key type.
    ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm());
    if (LOG.isDebugEnabled()) {
        LOG.debug("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm());
    }/*w w  w .  j  a  v  a2s  . com*/
    // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null.
    // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL."
    PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader());
    AlgorithmIdentifier pAlg = null;
    if ("RSA".equalsIgnoreCase(key.getAlgorithm())) {
        pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE);
    } else {
        pAlg = new AlgorithmIdentifier(oid);
    }
    headerBuilder.setProtectionAlg(pAlg);
    // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so 
    // we use BC classes to translate it into a signature algorithm name instead
    PKIHeader head = headerBuilder.build();
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Signing CMP message with signature alg: " + signatureAlgorithmName);
    }
    Signature sig = Signature.getInstance(signatureAlgorithmName, provider);
    sig.initSign(key);
    sig.update(CmpMessageHelper.getProtectedBytes(head, pKIMessage.getBody()));

    if ((extraCerts != null) && (extraCerts.length > 0)) {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts);
    } else {
        pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()));
    }
    return pKIMessage;
}

From source file:test.integ.be.agiv.security.PKCS12Test.java

@Test
public void testLoadPKCS12() throws Exception {
    Config config = new Config();
    String pkcs12Path = config.getPKCS12Path();
    String pkcs12Password = config.getPKCS12Password();

    InputStream pkcs12InputStream = new FileInputStream(pkcs12Path);
    assertNotNull(pkcs12InputStream);

    LOG.debug("loading PKCS12 keystore");
    KeyStore keyStore = KeyStore.getInstance("PKCS12");
    keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());

    Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
        X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
        LOG.debug("certificate: " + certificate);
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
        LOG.debug("private key algo: " + privateKey.getAlgorithm());
        assertEquals("RSA", privateKey.getAlgorithm());
        LOG.debug("certificate fingerprint: " + DigestUtils.shaHex(certificate.getEncoded()));
    }//from ww  w .  j  a va 2s  . c o  m
}

From source file:be.fedict.eid.applet.service.signer.SHA1WithRSAProxySignature.java

@Override
protected void engineInitSign(PrivateKey privateKey) throws InvalidKeyException {
    LOG.debug("engineInitSign: " + privateKey.getAlgorithm());
}

From source file:org.jgrades.security.utils.KeyStoreContentExtractorTest.java

@Test
public void shouldExtractPrivateKeyForSigning() throws Exception {
    // when//from w ww.ja  v  a2 s. c o m
    PrivateKey privateKey = extractor.getPrivateKeyForSigning();

    // then
    assertThat(privateKey).isNotNull();
    assertThat(privateKey.getAlgorithm()).isEqualTo("RSA");
    assertThat(privateKey.getEncoded()).isEqualTo(FileUtils.readFileToByteArray(signingPrivateKey));
}