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:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * Generates a fingerprint for the given key.
 *
 * @param  key  Key to fingerprint.//from w w  w .j av  a2s  .c o  m
 *
 * @return  Hashed representation of encoded key bytes.
 *
 * @throws  CryptException  On hash calculation errors.
 */
private String fingerPrint(final Key key) throws CryptException {
    final MD2 hash = new MD2();
    return hash.digest(key.getEncoded(), new HexConverter());
}

From source file:org.obiba.mica.micaConfig.service.MicaConfigService.java

private String generateSecretKey() {
    Key key = cipherService.generateNewKey();
    return Hex.encodeToString(key.getEncoded());
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

protected void validateKey(Key key) throws InvalidKeyException, NoSuchAlgorithmException {
    String algorithm = key.getAlgorithm();
    int size = key.getEncoded().length * 8;
    if (!KEY_ALGORITHM.equalsIgnoreCase(algorithm)) {
        String msg = "Expected key of type: " + KEY_ALGORITHM + ", instead it was: " + algorithm;
        log.error(msg);/*from w w w. j av a2 s . com*/
        throw new InvalidKeyException(msg);
    } else if (size > Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM)) {
        String msg = "Illegal key size, max platform support for " + KEY_ALGORITHM + " keys is "
                + Cipher.getMaxAllowedKeyLength(KEY_ALGORITHM);
        log.error(msg);
        throw new InvalidKeyException(msg);
    }
}

From source file:org.apache.accumulo.core.security.crypto.CachingHDFSSecretKeyEncryptionStrategy.java

private void doKeyEncryptionOperation(int encryptionMode, CryptoModuleParameters params) throws IOException {
    Cipher cipher = DefaultCryptoModuleUtils
            .getCipher(params.getAllOptions().get(Property.CRYPTO_DEFAULT_KEY_STRATEGY_CIPHER_SUITE.getKey()));

    try {//  ww  w. ja  v  a2 s.  c om
        cipher.init(encryptionMode,
                new SecretKeySpec(secretKeyCache.getKeyEncryptionKey(), params.getAlgorithmName()));
    } catch (InvalidKeyException e) {
        log.error("{}", e.getMessage(), e);
        throw new RuntimeException(e);
    }

    if (Cipher.UNWRAP_MODE == encryptionMode) {
        try {
            Key plaintextKey = cipher.unwrap(params.getEncryptedKey(), params.getAlgorithmName(),
                    Cipher.SECRET_KEY);
            params.setPlaintextKey(plaintextKey.getEncoded());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }
    } else {
        Key plaintextKey = new SecretKeySpec(params.getPlaintextKey(), params.getAlgorithmName());
        try {
            byte[] encryptedSecretKey = cipher.wrap(plaintextKey);
            params.setEncryptedKey(encryptedSecretKey);
            params.setOpaqueKeyEncryptionKeyID(secretKeyCache.getPathToKeyName());
        } catch (InvalidKeyException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        } catch (IllegalBlockSizeException e) {
            log.error("{}", e.getMessage(), e);
            throw new RuntimeException(e);
        }

    }
}

From source file:org.apache.qpid.server.security.NonJavaKeyStoreTest.java

private File[] extractResourcesFromTestKeyStore(boolean pem) throws Exception {
    java.security.KeyStore ks = java.security.KeyStore.getInstance(java.security.KeyStore.getDefaultType());
    try (InputStream is = getClass().getResourceAsStream("/java_broker_keystore.jks")) {
        ks.load(is, KEYSTORE_PASSWORD.toCharArray());
    }//from w  w  w. j ava2s  .  c o  m

    File privateKeyFile = TestFileUtils.createTempFile(this, ".private-key.der");
    try (FileOutputStream kos = new FileOutputStream(privateKeyFile)) {
        Key pvt = ks.getKey("java-broker", KEYSTORE_PASSWORD.toCharArray());
        if (pem) {
            kos.write("-----BEGIN PRIVATE KEY-----\n".getBytes());
            kos.write(Base64.encodeBase64(pvt.getEncoded(), true));
            kos.write("\n-----END PRIVATE KEY-----".getBytes());
        } else {
            kos.write(pvt.getEncoded());
        }
        kos.flush();
    }

    File certificateFile = TestFileUtils.createTempFile(this, ".certificate.der");

    try (FileOutputStream cos = new FileOutputStream(certificateFile)) {
        Certificate pub = ks.getCertificate("rootca");
        if (pem) {
            cos.write("-----BEGIN CERTIFICATE-----\n".getBytes());
            cos.write(Base64.encodeBase64(pub.getEncoded(), true));
            cos.write("\n-----END CERTIFICATE-----".getBytes());
        } else {
            cos.write(pub.getEncoded());
        }
        cos.flush();
    }

    return new File[] { privateKeyFile, certificateFile };
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

@Override
public String getFingerPrint(Key privKey) {
    return getFingerPrint(privKey.getEncoded());
}

From source file:org.apigw.commons.crypto.ApigwCrypto.java

@PostConstruct
public void init() throws Exception {
    log.debug("Initializing...");
    if (useEncryption) {
        securityProvider = new BouncyCastleProvider();
        Security.addProvider(securityProvider);
        keyStore = initKeyStore(keyStoreFile, keyStorePassword, keyStoreType);
        saltKeyStore = initKeyStore(saltKeyKeyStoreFile, saltKeyKeyStorePassword, saltKeyKeyStoreType);
        salt = initSalt();/*  w w w  .j  a v  a 2  s .co  m*/
        Key key = keyStore.getKey(alias, keyStorePassword.toCharArray());
        validateKey(key);
        String algorithm = key.getAlgorithm();
        int size = key.getEncoded().length * 8;
        log.debug("operations will be performed using {} key with size {}", algorithm, size);

    } else {
        keyStore = null;
        log.warn("No keystore file specified, will not encrypt messages");
    }
    log.debug("Finished initializing");
}

From source file:org.apache.ws.security.message.DerivedKeyTest.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)//w  ww . j  av a2  s  .  co  m
 */
@org.junit.Test
public void testSignatureThumbprintSHA1() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SecurityTokenReference secToken = new SecurityTokenReference(doc);
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("wss40");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    secToken.setKeyIdentifierThumb(certs[0]);

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

    sigBuilder.prependDKElementToHeader(secHeader);

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

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

From source file:org.apache.ws.security.message.DerivedKeyTest.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)/*  www  . j av a  2 s  . c  o m*/
 */
@org.junit.Test
public void testSignatureSKI() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    SecurityTokenReference secToken = new SecurityTokenReference(doc);
    CryptoType cryptoType = new CryptoType(CryptoType.TYPE.ALIAS);
    cryptoType.setAlias("wss40");
    X509Certificate[] certs = crypto.getX509Certificates(cryptoType);
    secToken.setKeyIdentifierSKI(certs[0], crypto);

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

    sigBuilder.prependDKElementToHeader(secHeader);

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

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

From source file:org.apigw.commons.crypto.ApigwCrypto.java

/**
 * Will init the global salt / IV, this salt should not be stored together with encrypted values.
 *//*from   w  w w  . j a  v  a 2 s  .c  om*/
private byte[] initSalt() throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException,
        NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException {
    byte[] encryptedSalt = Base64.decodeBase64(encodedEncryptedSalt.getBytes());
    Key saltKey = saltKeyStore.getKey(saltKeyAlias, saltKeyPassword.toCharArray());
    validateKey(saltKey);
    String algorithm = saltKey.getAlgorithm();
    int size = saltKey.getEncoded().length * 8;
    log.debug("initializing salt using {} key with size {}", algorithm, size);
    SecretKeySpec skeySpec = new SecretKeySpec(saltKey.getEncoded(), KEY_ALGORITHM);

    IvParameterSpec ivParameterSpec = new IvParameterSpec(getIV(encryptedSalt));
    Cipher decryptCipher = Cipher.getInstance(TRANSFORMATION, securityProvider);
    decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec, ivParameterSpec);
    byte[] decryptedSalt = decryptCipher.doFinal(encryptedSalt);
    return removeIV(decryptedSalt);
}