Example usage for java.security Key getEncoded

List of usage examples for java.security Key getEncoded

Introduction

In this page you can find the example usage for java.security Key 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:mitm.common.security.KeyEncoderTest.java

@Test
public void testDeSerializePublicKey() throws Exception {
    Key key = KeyEncoder.decode(Base64.decodeBase64(MiscStringUtils.toAsciiBytes(BASE64_ENCODED_PUBLIC_KEY)),
            encryptor);/*  w  w  w  .  j  a  va  2 s. c  o m*/

    assertTrue(key instanceof PublicKey);

    assertTrue(ArrayUtils.isEquals(publicKey.getEncoded(), key.getEncoded()));
}

From source file:wssec.TestWSSecurityNewDK.java

/**
 * A test for WSS-211 - "WSS4J does not support ThumbprintSHA1 in DerivedKeyTokens".
 * Here we're signing the SOAP body, where the signature refers to a DerivedKeyToken
 * which uses a Thumbprint-SHA1 reference to the encoded certificate (which is in the
 * keystore)// www .j  a v  a2 s  .co  m
 */
public void testSignatureThumbprintSHA1() throws Exception {
    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SecurityTokenReference secToken = new SecurityTokenReference(doc);
    X509Certificate[] certs = crypto.getCertificates("wss40");
    secToken.setKeyIdentifierThumb(certs[0]);
    secToken.getElement();

    WSSecDKSign sigBuilder = new WSSecDKSign();
    java.security.Key key = crypto.getPrivateKey("wss40", "security");
    sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
    sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
    sigBuilder.build(doc, secHeader);

    sigBuilder.appendSigToHeader(secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Encrypted message: ThumbprintSHA1 + DerivedKeys");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        LOG.debug(outputString);
    }

    Vector results = verify(doc);

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    assertTrue(actionResult != null);
    assertFalse(actionResult.isEmpty());

    assertTrue(actionResult.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY) != null);
}

From source file:wssec.TestWSSecurityNewDK.java

/**
 * Here we're signing the SOAP body, where the signature refers to a DerivedKeyToken
 * which uses an SKI reference to the encoded certificate (which is in the
 * keystore)//from   w ww  . j  av  a2s  . c  o  m
 */
public void testSignatureSKI() throws Exception {
    SOAPEnvelope unsignedEnvelope = message.getSOAPEnvelope();
    Document doc = unsignedEnvelope.getAsDocument();
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SecurityTokenReference secToken = new SecurityTokenReference(doc);
    X509Certificate[] certs = crypto.getCertificates("wss40");
    secToken.setKeyIdentifierSKI(certs[0], crypto);
    secToken.getElement();

    WSSecDKSign sigBuilder = new WSSecDKSign();
    java.security.Key key = crypto.getPrivateKey("wss40", "security");
    sigBuilder.setExternalKey(key.getEncoded(), secToken.getElement());
    sigBuilder.setSignatureAlgorithm(XMLSignature.ALGO_ID_MAC_HMAC_SHA1);
    sigBuilder.build(doc, secHeader);

    sigBuilder.appendSigToHeader(secHeader);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Encrypted message: SKI + DerivedKeys");
        String outputString = org.apache.ws.security.util.XMLUtils.PrettyDocumentToString(doc);
        LOG.debug(outputString);
    }

    Vector results = verify(doc);

    WSSecurityEngineResult actionResult = WSSecurityUtil.fetchActionResult(results, WSConstants.SIGN);
    assertTrue(actionResult != null);
    assertFalse(actionResult.isEmpty());

    assertTrue(actionResult.get(WSSecurityEngineResult.TAG_DECRYPTED_KEY) != null);
}

From source file:mitm.common.security.KeyEncoderTest.java

@Test
public void testSerializeSecretKey() throws Exception {
    PBEKeySpec keySpec = new PBEKeySpec("test".toCharArray(), new byte[] { 1 }, 1);

    SecretKeyFactory secretKeyFactory = securityFactory
            .createSecretKeyFactory("PBEWITHSHA256AND128BITAES-CBC-BC");

    Key secretKey = secretKeyFactory.generateSecret(keySpec);

    byte[] serialized = KeyEncoder.encode(secretKey, encryptor);

    assertNotNull(serialized);/*from   ww  w  .jav a2  s .  c  om*/

    Key key = KeyEncoder.decode(serialized, encryptor);

    assertTrue(key instanceof SecretKey);

    assertTrue(ArrayUtils.isEquals(secretKey.getEncoded(), key.getEncoded()));
}

From source file:net.sourceforge.jencrypt.lib.CryptoWrapper.java

/**
 * Save the generated en/decryption key.
 *///from  w  ww  .ja v a 2  s. co m
public void saveKeyFile(String file, Key k) throws IOException {
    BufferedWriter bw = null;
    try {
        FileWriter fw = new FileWriter(file);
        bw = new BufferedWriter(fw);
        bw.write(Hex.encodeHexString(k.getEncoded()));
        bw.flush();
    } catch (IOException e) {
        throw new IOException("Error saving key file :'" + file + "': " + e.getMessage());
    } finally {
        bw.close();
    }
}

From source file:org.apache.ofbiz.entity.util.EntityCrypto.java

protected void createKey(String originalKeyName, StorageHandler handler, EncryptMethod encryptMethod)
        throws EntityCryptoException {
    String hashedKeyName = handler.getHashedKeyName(originalKeyName);
    Key key = handler.generateNewKey();
    final GenericValue newValue = delegator.makeValue("EntityKeyStore");
    try {/*from   w w w. jav a2  s .  c  o m*/
        newValue.set("keyText", handler.encodeKey(key.getEncoded()));
    } catch (GeneralException e) {
        throw new EntityCryptoException(e);
    }
    newValue.set("keyName", hashedKeyName);

    try {
        TransactionUtil.doNewTransaction(new Callable<Void>() {
            public Void call() throws Exception {
                delegator.create(newValue);
                return null;
            }
        }, "storing encrypted key", 0, true);
    } catch (GenericEntityException e) {
        throw new EntityCryptoException(e);
    }
}

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

private void init(String args[]) {

    FileInputStream file_inputstream;
    try {/*w  w w .j  a v  a2s . 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();
    }

}

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 {//from w w  w  .  j  a  va2 s . c  o m
        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.concursive.connect.web.modules.admin.actions.AdminSync.java

public String executeCommandStartSync(ActionContext context) {
    if (!getUser(context).getAccessAdmin()) {
        return "PermissionError";
    }//from   w  w w  . jav a  2 s .c  om
    if (!hasMatchingFormToken(context)) {
        return "TokenError";
    }
    boolean isValid = false;
    String serverURL = null;
    String apiClientId = null;
    String apiCode = null;
    String startSync = null;
    String saveConnectionDetails = null;
    Connection db = null;
    try {

        Scheduler scheduler = (Scheduler) context.getServletContext().getAttribute(Constants.SCHEDULER);
        Vector syncStatus = (Vector) scheduler.getContext().get("CRMSyncStatus");

        String syncListings = context.getRequest().getParameter("syncListings");
        startSync = context.getRequest().getParameter("startSync");
        if ("true".equals(startSync)) {
            isValid = true;
            if (syncStatus != null && syncStatus.size() == 0) {
                // Trigger the sync job
                triggerJob(context, "syncSystem", syncListings);
            } else {
                // Do nothing as a sync is already in progress.
            }
        }

        saveConnectionDetails = context.getRequest().getParameter("saveConnectionDetails");
        if ("true".equals(saveConnectionDetails)) {

            ApplicationPrefs prefs = this.getApplicationPrefs(context);

            serverURL = context.getRequest().getParameter("serverURL");
            apiClientId = context.getRequest().getParameter("apiClientId");
            apiCode = context.getRequest().getParameter("apiCode");
            String domainAndPort = "";
            if (serverURL.indexOf("http://") != -1) {
                domainAndPort = serverURL.substring(7).split("/")[0];
            } else if (serverURL.indexOf("https://") != -1) {
                domainAndPort = serverURL.substring(8).split("/")[0];
            }
            String domain = domainAndPort;
            if (domainAndPort.indexOf(":") != -1) {
                domain = domainAndPort.split(":")[0];
            }

            if (StringUtils.hasText(serverURL) && StringUtils.hasText(domain)
                    && StringUtils.hasText(apiClientId) && StringUtils.hasText(apiCode)) {
                if (testConnection(serverURL, domain, apiCode, apiClientId)) {

                    isValid = true;

                    prefs.add("CONCURSIVE_CRM.SERVER", serverURL);
                    prefs.add("CONCURSIVE_CRM.ID", domain);
                    prefs.add("CONCURSIVE_CRM.CODE", apiCode);
                    prefs.add("CONCURSIVE_CRM.CLIENT", apiClientId);
                    prefs.save();

                    triggerJob(context, "syncSystem", syncListings);

                    //Set the connect user performing the first sync to have crm admin role
                    db = this.getConnection(context);
                    User user = getUser(context);
                    user.setConnectCRMAdmin(true);
                    user.update(db);

                    //Add a sync client and send that information over to the Mgmt CRM Server
                    Key key = (Key) context.getServletContext().getAttribute(ApplicationPrefs.TEAM_KEY);
                    SyncClient syncClient = new SyncClient();
                    syncClient.setType(prefs.get(ApplicationPrefs.PURPOSE));
                    syncClient.setCode(new String(Hex.encodeHex(key.getEncoded())));
                    syncClient.setEnabled(true);
                    syncClient.setEnteredBy(user.getId());
                    syncClient.setModifiedBy(user.getId());
                    boolean recorded = syncClient.insert(db);
                    if (recorded) {
                        CRMConnection connection = new CRMConnection();
                        connection.setUrl(serverURL);
                        connection.setId(domain);
                        connection.setCode(apiCode);
                        connection.setClientId(apiClientId);

                        DataRecord record = new DataRecord();
                        record.setName(MAP);
                        record.setAction(SAVE_CONNECT_SYNC_INFO_SERVICE);
                        record.addField("connectURL", getServerUrl(context));
                        if (StringUtils.hasText(prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME))) {
                            record.addField("connectDomain", prefs.get(ApplicationPrefs.WEB_DOMAIN_NAME));
                        } else {
                            record.addField("connectDomain", context.getRequest().getServerName());
                        }
                        record.addField("connectSyncClientId", syncClient.getId());
                        record.addField("connectSyncClientCode", syncClient.getCode());
                        connection.save(record);
                        if (!connection.hasError()) {
                            LOG.debug(
                                    "Connect Sync connection information has been successfully transmitted...");
                        } else {
                            LOG.debug("Connect Sync connection information transmission failed...");
                        }
                    }
                }
            }
        }
    } catch (Exception e) {
        context.getRequest().setAttribute("Error", e);
        return ("SystemError");
    } finally {
        this.freeConnection(context, db);
    }
    if (!isValid && "true".equals(saveConnectionDetails)) {
        context.getRequest().setAttribute("serverURL", context.getRequest().getParameter("serverURL"));
        context.getRequest().setAttribute("apiClientId", context.getRequest().getParameter("apiClientId"));
        context.getRequest().setAttribute("apiCode", context.getRequest().getParameter("apiCode"));

        context.getRequest().setAttribute("actionError", "Could not connect to the CRM");
        return executeCommandDefault(context);
    }
    return "StartSyncOK";
}

From source file:test.integ.be.fedict.commons.eid.client.JCATest.java

@Test
public void testSoftwareRSAKeyWrapping() throws Exception {
    final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    final KeyPair keyPair = keyPairGenerator.generateKeyPair();

    final KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
    final SecretKey secretKey = keyGenerator.generateKey();
    LOG.debug("secret key algo: " + secretKey.getAlgorithm());

    final Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.WRAP_MODE, keyPair.getPublic());
    LOG.debug("cipher security provider: " + cipher.getProvider().getName());
    LOG.debug("cipher type: " + cipher.getClass().getName());
    final byte[] wrappedKey = cipher.wrap(secretKey);

    cipher.init(Cipher.UNWRAP_MODE, keyPair.getPrivate());
    final Key resultKey = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

    assertArrayEquals(secretKey.getEncoded(), resultKey.getEncoded());

}