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:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

protected void storeKeys(ShareKeyDB shareKeys, ObfuscationKeyDB obKeys, Connection con) throws SQLException {
    // Store ShareKeys
    PreparedStatement insert = con.prepareStatement(INSERT_SHAREKEYS);
    Iterator<Integer> entries = shareKeys.getKeyIterator();
    while (entries.hasNext()) {
        int version = entries.next();
        ShareKeyDBEntry entry = shareKeys.getEntry(version);

        insert.setInt(1, version);//from ww w . j  a v a2  s  .c  om

        Iterator<PublicKey> keys = entry.getKeyIterator();
        while (keys.hasNext()) {
            PublicKey pKey = (PublicKey) keys.next();
            byte[] encKey = entry.getEncryptedKey(pKey);
            // Store id, time, pkey enckey;
            insert.setBytes(2, pKey.getEncoded());
            insert.setBytes(3, encKey);
            int count = insert.executeUpdate();
            logger.debug("Inserted " + count + " sharekey");
        }
    }
    insert.close();

    // Store ObKeys
    insert = con.prepareStatement(INSERT_OBFUSCATIONKEYS);
    Iterator<PublicKey> keys = obKeys.getKeys();
    while (keys.hasNext()) {
        PublicKey pKey = (PublicKey) keys.next();
        byte[] encKey = obKeys.get(pKey);
        insert.setBytes(1, pKey.getEncoded());
        insert.setBytes(2, encKey);
        int count = insert.executeUpdate();
        logger.debug("Inserted " + count + " obkey");
        insert.clearParameters();
    }
    insert.close();
}

From source file:eu.dety.burp.joseph.attacks.key_confusion.KeyConfusionInfo.java

String transformKeyByPayload(Enum payloadTypeId, PublicKey key) throws UnsupportedEncodingException {
    Base64 base64Pem = new Base64(64, "\n".getBytes("UTF-8"));

    String modifiedKey;//from   ww  w  .j  a  v a 2s  .  co  m

    switch ((PayloadType) payloadTypeId) {

    case PKCS8_WITH_HEADER_FOOTER:
        modifiedKey = "-----BEGIN PUBLIC KEY-----" + Base64.encodeBase64String(key.getEncoded())
                + "-----END PUBLIC KEY-----";
        break;

    case PKCS8_WITH_LF:
        modifiedKey = base64Pem.encodeToString(key.getEncoded());
        break;

    case PKCS8_WITH_HEADER_FOOTER_LF:
        modifiedKey = "-----BEGIN PUBLIC KEY-----\n" + base64Pem.encodeToString(key.getEncoded())
                + "-----END PUBLIC KEY-----";
        break;

    case PKCS8_WITH_HEADER_FOOTER_LF_ENDING_LF:
        modifiedKey = transformKeyByPayload(PayloadType.PKCS8_WITH_HEADER_FOOTER_LF, key) + "\n";
        break;

    case PKCS8:
    default:
        modifiedKey = Base64.encodeBase64String(key.getEncoded());
        break;
    }

    return modifiedKey;
}

From source file:org.wso2.carbon.identity.user.store.ws.util.FileUtil.java

/**
 * Copy Public key to temporary location
 *
 * This method throws General Exception since current keyStoreManager.getDefaultPublicKey() throws Exception
 * @param publicKeyPath/*w  w w  .  jav a2 s .com*/
 * @throws Exception
 */
public void copyPublicKey(String publicKeyPath) throws Exception {
    int tenantID = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId();
    String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain();
    KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantID);
    DataOutputStream dos = null;
    KeyStore keyStore;
    PublicKey publicKey;

    try {
        File file = new File(publicKeyPath);
        FileOutputStream fos = new FileOutputStream(file);
        dos = new DataOutputStream(fos);

        if (tenantID != MultitenantConstants.SUPER_TENANT_ID) {
            keyStore = keyStoreManager.getKeyStore(generateKSNameFromDomainName(tenantDomain));
            Certificate publicCert = keyStore.getCertificate(tenantDomain); //Default keystore alias = tenantDomain name
            publicKey = publicCert.getPublicKey();
        } else {
            publicKey = keyStoreManager.getDefaultPublicKey();

        }

        byte[] keyBytes = publicKey.getEncoded();
        BASE64Encoder encoder = new BASE64Encoder();
        String encoded = encoder.encodeBuffer(keyBytes);
        dos.writeBytes(encoded);
        dos.flush();
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
            log.error("Error occurred while closing data stream", e);
        }
    }
}

From source file:org.wso2.carbon.security.util.ServerCrypto.java

@Override
/**/*from w w w . ja v  a  2 s  . c om*/
 * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate)
 */
public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException {
    /*
     * Gets the DER-encoded OCTET string for the extension value (extnValue)
     * identified by the passed-in oid String. The oid string is represented
     * by a set of positive whole numbers separated by periods.
     */
    byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);

    if (cert.getVersion() < 3 || derEncodedValue == null) {
        PublicKey key = cert.getPublicKey();
        if (!(key instanceof RSAPublicKey)) {
            throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" });
        }
        byte[] encoded = key.getEncoded();
        // remove 22-byte algorithm ID and header
        byte[] value = new byte[encoded.length - 22];
        System.arraycopy(encoded, 22, value, 0, value.length);
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException ex) {
            throw new WSSecurityException(1, "noSKIHandling",
                    new Object[] { "Wrong certificate version (<3) and no " + "SHA1 message digest availabe" });
        }
        sha.reset();
        sha.update(value);
        return sha.digest();
    }

    /**
     * Strip away first four bytes from the DerValue (tag and length of
     * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
     */
    byte abyte0[] = new byte[derEncodedValue.length - 4];

    System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
    return abyte0;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * /*from  w  w  w. j a  v  a  2s. c  o m*/
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:org.apache.ws.security.components.crypto.CryptoBase.java

/**
 * Reads the SubjectKeyIdentifier information from the certificate.
 * <p/>//from  w  ww . j a va2  s .  com
 * If the the certificate does not contain a SKI extension then
 * try to compute the SKI according to RFC3280 using the
 * SHA-1 hash value of the public key. The second method described
 * in RFC3280 is not support. Also only RSA public keys are supported.
 * If we cannot compute the SKI throw a WSSecurityException.
 *
 * @param cert The certificate to read SKI
 * @return The byte array containing the binary SKI data
 */
public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException {
    //
    // Gets the DER-encoded OCTET string for the extension value (extnValue)
    // identified by the passed-in oid String. The oid string is represented
    // by a set of positive whole numbers separated by periods.
    //
    byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);

    if (cert.getVersion() < 3 || derEncodedValue == null) {
        PublicKey key = cert.getPublicKey();
        if (!(key instanceof RSAPublicKey)) {
            throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" });
        }
        byte[] encoded = key.getEncoded();
        // remove 22-byte algorithm ID and header
        byte[] value = new byte[encoded.length - 22];
        System.arraycopy(encoded, 22, value, 0, value.length);
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException ex) {
            throw new WSSecurityException(WSSecurityException.UNSUPPORTED_SECURITY_TOKEN, "noSKIHandling",
                    new Object[] { "Wrong certificate version (<3) and no SHA1 message digest availabe" }, ex);
        }
        sha.reset();
        sha.update(value);
        return sha.digest();
    }

    //
    // Strip away first four bytes from the DerValue (tag and length of
    // ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
    //
    byte abyte0[] = new byte[derEncodedValue.length - 4];

    System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
    return abyte0;
}

From source file:org.wso2.carbon.webapp.ext.cxf.crypto.CXFServerCrypto.java

/**
 * @see org.apache.ws.security.components.crypto.Crypto#getSKIBytesFromCert(java.security.cert.X509Certificate)
 *///from  w ww .  j a  v  a  2 s . c o m
public byte[] getSKIBytesFromCert(X509Certificate cert) throws WSSecurityException {
    /*
     * Gets the DER-encoded OCTET string for the extension value (extnValue)
     * identified by the passed-in oid String. The oid string is represented
     * by a set of positive whole numbers separated by periods.
     */
    byte[] derEncodedValue = cert.getExtensionValue(SKI_OID);

    if (cert.getVersion() < 3 || derEncodedValue == null) {
        PublicKey key = cert.getPublicKey();
        if (!(key instanceof RSAPublicKey)) {
            throw new WSSecurityException(1, "noSKIHandling", new Object[] { "Support for RSA key only" });
        }
        byte[] encoded = key.getEncoded();
        // remove 22-byte algorithm ID and header
        byte[] value = new byte[encoded.length - 22];
        System.arraycopy(encoded, 22, value, 0, value.length);
        MessageDigest sha;
        try {
            sha = MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException ex) {
            throw new WSSecurityException(1, "noSKIHandling",
                    new Object[] { "Wrong certificate version (<3) and no " + "SHA1 message digest availabe" });
        }
        sha.reset();
        sha.update(value);
        return sha.digest();
    }

    /**
     * Strip away first four bytes from the DerValue (tag and length of
     * ExtensionValue OCTET STRING and KeyIdentifier OCTET STRING)
     */
    byte abyte0[] = new byte[derEncodedValue.length - 4];

    System.arraycopy(derEncodedValue, 4, abyte0, 0, abyte0.length);
    return abyte0;
}

From source file:org.cesecore.certificates.ca.catoken.CATokenTestBase.java

protected void doCaTokenECC(CryptoToken cryptoToken)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        CryptoTokenOfflineException, NoSuchProviderException, InvalidKeyException, SignatureException,
        CryptoTokenAuthenticationFailedException, InvalidAlgorithmParameterException {
    CAToken catoken = new CAToken(cryptoToken);
    try {//  w  w  w.  j  a v  a  2s. c o  m
        // Set key sequence so that next sequence will be 00001 (this is the default though so not really needed here)
        catoken.setKeySequence(CAToken.DEFAULT_KEYSEQUENCE);
        catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setSignatureAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA);
        catoken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_RSA);

        // First we start by deleting all old entries
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00001");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00003");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00001");

        // Try to delete something that does not exist, it should work without error
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "sdkfjhsdkfjhsd4447");

        assertEquals("SHA256withECDSA", catoken.getTokenInfo().getSignatureAlgorithm());
        assertEquals("SHA256WithRSA", catoken.getTokenInfo().getEncryptionAlgorithm());
        assertEquals(getProvider(), catoken.getCryptoToken().getSignProviderName());

        catoken.getCryptoToken().activate(tokenpin.toCharArray());
        // Should still be offline, because we don't have any keys matching our labels
        assertEquals(CryptoToken.STATUS_OFFLINE, catoken.getTokenStatus());
        assertEquals(CAToken.DEFAULT_KEYSEQUENCE, catoken.getTokenInfo().getKeySequence());

        // Generate the first key, will get name rsatest+nextsequence = rsatest00001
        Integer seq = Integer.valueOf(CAToken.DEFAULT_KEYSEQUENCE);
        catoken.generateKeys(tokenpin.toCharArray(), false, true);
        seq += 1;
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        PrivateKey priv = null;
        PublicKey pub = null;
        String keyhash = null;
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        assertEquals("ECDSA", AlgorithmTools.getKeyAlgorithm(pub));
        keyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        // There should exist an encryption key when we have generated keys with renew = false
        // Encryption key should be an RSA key with 2048 bit, since signature key is ECDSA
        PublicKey encPub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        assertEquals(2048, KeyTools.getKeyLength(encPub));

        // Generate new keys, moving the old ones to "previous key"
        catoken.generateKeys(tokenpin.toCharArray(), true, true);
        Properties p = catoken.getTokenInfo().getProperties();
        String previousSequence = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        assertEquals(seq, Integer.valueOf(previousSequence));
        seq += 1;
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String newkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertFalse("New kays are same as old keys, should not be...", keyhash.equals(newkeyhash));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String previouskeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(keyhash, previouskeyhash);

        // Generate new keys, not activating them, this should create a "next key", keeping the current and previous as they are
        // Generate new keys, moving the old ones to "previous key"
        catoken.generateKeys(tokenpin.toCharArray(), true, false);
        p = catoken.getTokenInfo().getProperties();
        String previousSequence2 = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        assertEquals(previousSequence, previousSequence2);
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String newkeyhash2 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(newkeyhash, newkeyhash2);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String previouskeyhash2 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(previouskeyhash, previouskeyhash2);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        String nextkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertFalse(newkeyhash2.equals(nextkeyhash));
        String nextSequence = p.getProperty(CryptoToken.NEXT_SEQUENCE_PROPERTY);
        Integer nextseq = seq + 1;
        assertEquals(nextseq, Integer.valueOf(nextSequence));
        // Make sure the properties was set correctly so we did not get the "default" key as next
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);

        // finally activate the "next key" moving that to current and moving the current to previous
        catoken.activateNextSignKey(tokenpin.toCharArray());
        p = catoken.getTokenInfo().getProperties();
        String previousSequence3 = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        assertEquals(seq, Integer.valueOf(previousSequence3));
        assertEquals(nextseq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String currentkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(nextkeyhash, currentkeyhash);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(256, KeyTools.getKeyLength(pub));
        String previouskeyhash3 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(newkeyhash2, previouskeyhash3);
        try {
            catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
            assertTrue("Should have thrown because the key should not exist", false);
        } catch (CryptoTokenOfflineException e) {
            // NOPMD: ignore this
        }
        // Next should now return the encryption key instead, since it is the default
        // There exist an RSA encryption key
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT);
        KeyTools.testKey(priv, encPub, catoken.getCryptoToken().getSignProviderName());
        // There exist an RSA encryption key
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        assertEquals(2048, KeyTools.getKeyLength(pub));
    } finally {
        // Clean up and delete our generated keys
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00000");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00001");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest00003");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00001");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest0000000002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "ecctest0000000003");
    }
}

From source file:org.panbox.core.keymgmt.JDBCHelperNonRevokeable.java

private void loadShareKeys(Connection con, ShareMetaData smd) throws SQLException, SignatureException {
    if (smd.shareKeys == null) {
        smd.shareKeys = new ShareKeyDB();
    }//from w w w .  j av a2s . c  om

    PreparedStatement s = con.prepareStatement(QUERY_SHARE_KEYS);
    ResultSet rs = s.executeQuery();
    while (rs.next()) {
        PublicKey key = CryptCore.createPublicKeyFromBytes(rs.getBytes(COL_DEV_PUB_KEY));
        int keyID = rs.getInt(COL_KEY_ID);
        byte[] encKey = rs.getBytes(COL_ENC_KEY);
        ShareKeyDBEntry entry = smd.shareKeys.getEntry(keyID);
        if (entry == null) {
            logger.debug("Creating new ShareKeyEntry: " + keyID);
            entry = new ShareKeyDBEntry(smd.shareKeyAlgorithm, keyID);
            smd.shareKeys.add(keyID, entry);
        }
        logger.debug("Adding ShareKey to entry " + keyID + " for key " + DigestUtils.md2Hex(key.getEncoded()));
        entry.addEncryptedKey(encKey, key);
        logger.debug("Number of keys in entry: " + entry.size());
    }
    rs.close();
}

From source file:org.cesecore.certificates.ca.catoken.CATokenTestBase.java

protected void doCaTokenRSA(CryptoToken cryptoToken)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        CryptoTokenOfflineException, NoSuchProviderException, InvalidKeyException, SignatureException,
        CryptoTokenAuthenticationFailedException, InvalidAlgorithmParameterException {
    CAToken catoken = new CAToken(cryptoToken);
    try {//from  w ww .j  av  a  2  s  . co  m
        // Set key sequence so that next sequence will be 00001 (this is the default though so not really needed here)
        catoken.setKeySequence(CAToken.DEFAULT_KEYSEQUENCE);
        catoken.setKeySequenceFormat(StringTools.KEY_SEQUENCE_FORMAT_NUMERIC);
        catoken.setSignatureAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_RSA);
        catoken.setEncryptionAlgorithm(AlgorithmConstants.SIGALG_SHA256_WITH_RSA);

        // First we start by deleting all old entries
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00001");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00003");

        // Try to delete something that does not exist, it should work without error
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "sdkfjhsdkfjhsd777");

        // We have no keys generated according to the labels above, so the status will be offline
        assertEquals(CryptoToken.STATUS_OFFLINE, catoken.getTokenStatus());
        assertEquals("SHA256WithRSA", catoken.getTokenInfo().getSignatureAlgorithm());
        assertEquals("SHA256WithRSA", catoken.getTokenInfo().getEncryptionAlgorithm());
        assertEquals(getProvider(), catoken.getCryptoToken().getSignProviderName());

        catoken.getCryptoToken().activate(tokenpin.toCharArray());
        // Should still be offline, because we don't have any keys matching our labels
        assertEquals(CryptoToken.STATUS_OFFLINE, catoken.getTokenStatus());
        assertEquals(CAToken.DEFAULT_KEYSEQUENCE, catoken.getTokenInfo().getKeySequence());
        // Generate the first key, will get name of the certsign property when generating with renew=false
        // also a encryption key with default alias will be generated
        Integer seq = Integer.valueOf(CAToken.DEFAULT_KEYSEQUENCE); // Default sequence is 0
        catoken.generateKeys(tokenpin.toCharArray(), false, true);
        Properties p = catoken.getTokenInfo().getProperties();
        assertEquals("00000", p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY));
        assertEquals("rsatest00000", p.getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING));
        assertEquals("rsatest00000", p.getProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING));
        assertEquals("rsatest00001", p.getProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING));
        assertEquals(null, p.getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS));
        // Now sequence should be 1, generated and activated new keys
        seq += 1;
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        // When generating keys with renew = false, we generate initial keys, which means generating the key aliases
        // we have specified for signature and encryption keys
        // After this all needed CAToken keys are generated and status will be active
        assertEquals(CryptoToken.STATUS_ACTIVE, catoken.getTokenStatus());
        PrivateKey priv = null;
        PublicKey pub = null;
        String keyhash = null;
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        assertEquals("RSA", AlgorithmTools.getKeyAlgorithm(pub));
        keyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        PrivateKey privenc = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        PublicKey pubenc = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        assertEquals(1024, KeyTools.getKeyLength(pubenc));
        assertEquals("RSA", AlgorithmTools.getKeyAlgorithm(pubenc));
        KeyTools.testKey(privenc, pubenc, catoken.getCryptoToken().getSignProviderName());
        try {
            KeyTools.testKey(privenc, pub, catoken.getCryptoToken().getSignProviderName());
            assertTrue("Should have thrown because the encryption key and signature key should not be the same",
                    false);
        } catch (InvalidKeyException e) {
            // NOPMD: ignore this is what we want
        }
        try {
            catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
            assertTrue("Should have thrown because the key should not exist", false);
        } catch (CryptoTokenOfflineException e) {
            // NOPMD: ignore this is what we want         
        }
        try {
            catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
            assertTrue("Should have thrown because the key should not exist", false);
        } catch (CryptoTokenOfflineException e) {
            // NOPMD: ignore this is what we want         
        }

        // Generate new keys, moving the old ones to "previous key"
        catoken.generateKeys(tokenpin.toCharArray(), true, true);
        // Now we move away the rsatest0000 key alias from our mappings, so we are now active
        assertEquals(CryptoToken.STATUS_ACTIVE, catoken.getTokenStatus());
        p = catoken.getTokenInfo().getProperties();
        assertEquals("00001", p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY));
        assertEquals("rsatest0000000002", p.getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING));
        assertEquals("rsatest0000000002", p.getProperty(CATokenConstants.CAKEYPURPOSE_CRLSIGN_STRING));
        assertEquals("rsatest00001", p.getProperty(CATokenConstants.CAKEYPURPOSE_DEFAULT_STRING));
        assertEquals("rsatest00000", p.getProperty(CATokenConstants.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS));
        assertNull(p.getProperty(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT_STRING));
        assertEquals("1024", p.getProperty(CryptoToken.KEYSPEC_PROPERTY));
        String previousSequence = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        assertEquals(seq, Integer.valueOf(previousSequence));
        // Now sequence should be 2, generated and activated new keys
        seq += 1;
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String newkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertFalse("New kays are same as old keys, should not be...", keyhash.equals(newkeyhash));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String previouskeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(keyhash, previouskeyhash);

        // Generate new keys, not activating them, this should create a "next key", keeping the current and previous as they are
        // Generate new keys, moving the old ones to "previous key"
        catoken.generateKeys(tokenpin.toCharArray(), true, false);
        p = catoken.getTokenInfo().getProperties();
        String previousSequence2 = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        assertEquals(previousSequence, previousSequence2);
        // Now sequence should still be 2, generated but did not activate the new keys
        assertEquals(seq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String newkeyhash2 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(newkeyhash, newkeyhash2);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String previouskeyhash2 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(previouskeyhash, previouskeyhash2);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        String nextkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertFalse(newkeyhash2.equals(nextkeyhash));
        String nextSequence = p.getProperty(CryptoToken.NEXT_SEQUENCE_PROPERTY);
        // Next sequence, for the non-activated key should be 3
        Integer nextseq = seq + 1;
        assertEquals(nextseq, Integer.valueOf(nextSequence));
        // Make sure the properties was set correctly so we did not get the "default" key as next
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_NEXT);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        try {
            KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
            assertTrue("Should throw", false);
        } catch (InvalidKeyException e) {
            // NOPMD
        }

        // finally activate the "next key" moving that to current and moving the current to previous
        catoken.activateNextSignKey(tokenpin.toCharArray());
        p = catoken.getTokenInfo().getProperties();
        String previousSequence3 = p.getProperty(CryptoToken.PREVIOUS_SEQUENCE_PROPERTY);
        // The former active sequence (2) should have been moved to "previous sequence" now
        assertEquals(seq, Integer.valueOf(previousSequence3));
        assertEquals(nextseq, Integer.valueOf(catoken.getTokenInfo().getKeySequence()));
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String currentkeyhash = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(nextkeyhash, currentkeyhash);
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_CERTSIGN_PREVIOUS);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        String previouskeyhash3 = CertTools.getFingerprintAsString(pub.getEncoded());
        assertEquals(newkeyhash2, previouskeyhash3);
        // Next should now return the encryption key instead, since it is the default
        priv = catoken.getPrivateKey(CATokenConstants.CAKEYPURPOSE_HARDTOKENENCRYPT);
        pub = catoken.getPublicKey(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT);
        KeyTools.testKey(priv, pub, catoken.getCryptoToken().getSignProviderName());
        assertEquals(1024, KeyTools.getKeyLength(pub));
        assertEquals(CryptoToken.STATUS_ACTIVE, catoken.getTokenStatus());
    } finally {
        // Clean up and delete our generated keys
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00000");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00001");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest00003");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest0000000002");
        catoken.getCryptoToken().deleteEntry(tokenpin.toCharArray(), "rsatest0000000003");
    }
}