Example usage for javax.crypto SecretKey getEncoded

List of usage examples for javax.crypto SecretKey getEncoded

Introduction

In this page you can find the example usage for javax.crypto SecretKey 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:com.billing.ng.crypto.profile.hash.PBEKeySpecProfile.java

@Override
public byte[] digest(String plainText, String salt) {
    KeySpec spec = new PBEKeySpec(plainText.toCharArray(), salt.getBytes(), getWorkFactor(), getKeyLength());

    SecretKey key;
    try {//from w  w w .j  a  va 2  s  . co  m
        key = getSecretKeyFactory().generateSecret(spec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("Key generator algorithm not supported by the JCE provider.");
    }
    return key.getEncoded();
}

From source file:org.apache.ws.security.message.EncryptionAlgorithmSuiteTest.java

@org.junit.Test
public void testSymmetricEncryption() throws Exception {

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);//from  w  w w  .j  av  a  2  s  . c o m
    SecretKey key = keyGen.generateKey();
    byte[] keyData = key.getEncoded();

    WSSecEncrypt builder = new WSSecEncrypt();
    builder.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
    builder.setSymmetricKey(key);
    builder.setEncryptSymmKey(false);

    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);
    WSSecHeader secHeader = new WSSecHeader();
    secHeader.insertSecurityHeader(doc);

    Document encryptedDoc = builder.build(doc, crypto, secHeader);

    if (LOG.isDebugEnabled()) {
        String outputString = XMLUtils.PrettyDocumentToString(encryptedDoc);
        LOG.debug(outputString);
    }

    byte[] encodedBytes = WSSecurityUtil.generateDigest(keyData);
    String identifier = Base64.encode(encodedBytes);
    SecretKeyCallbackHandler secretKeyCallbackHandler = new SecretKeyCallbackHandler();
    secretKeyCallbackHandler.addSecretKey(identifier, keyData);

    Element securityHeader = WSSecurityUtil.getSecurityHeader(encryptedDoc, null);
    AlgorithmSuite algorithmSuite = createAlgorithmSuite();

    WSSecurityEngine secEngine = new WSSecurityEngine();
    RequestData data = new RequestData();
    data.setDecCrypto(crypto);
    data.setCallbackHandler(secretKeyCallbackHandler);

    data.setAlgorithmSuite(algorithmSuite);

    algorithmSuite.addEncryptionMethod(WSConstants.AES_128);
    secEngine.processSecurityHeader(securityHeader, data);

    algorithmSuite.setMinimumSymmetricKeyLength(256);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }

    algorithmSuite.setMinimumSymmetricKeyLength(64);
    algorithmSuite.setMaximumSymmetricKeyLength(120);
    try {
        secEngine.processSecurityHeader(securityHeader, data);
        fail("Expected failure as a 128 bit key is not allowed");
    } catch (WSSecurityException ex) {
        // expected
    }
}

From source file:wssec.TestWSSecurityNew17.java

/**
 * Setup method//  w  w w  . jav a2  s.  c o  m
 * <p/>
 * 
 * @throws Exception Thrown when there is a problem in setup
 */
protected void setUp() throws Exception {
    AxisClient tmpEngine = new AxisClient(new NullProvider());
    msgContext = new MessageContext(tmpEngine);
    message = getSOAPMessage();

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(128);
    SecretKey key = keyGen.generateKey();
    keyData = key.getEncoded();
}

From source file:se.vgregion.portal.cs.util.CryptoUtilImpl.java

/**
 * Encrypt a value and generate a keyfile. if the keyfile is not found then a new one is created
 * /*from  ww  w.  j a  va  2  s. com*/
 * @param value
 *            - value to be encrypted
 * @throws GeneralSecurityException
 *             - security exception
 * @return Encrypted value
 */
@Override
public String encrypt(String value) throws GeneralSecurityException {
    if (!keyFile.exists()) {
        KeyGenerator keyGen = KeyGenerator.getInstance(AES);
        keyGen.init(KEY_SIZE);
        SecretKey sk = keyGen.generateKey();
        FileWriter fw = null;
        try {
            fw = new FileWriter(keyFile);
            fw.write(byteArrayToHexString(sk.getEncoded()));
            fw.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    SecretKeySpec sks = getSecretKeySpec();

    Cipher cipher = Cipher.getInstance(AES);
    cipher.init(Cipher.ENCRYPT_MODE, sks, cipher.getParameters());
    byte[] encrypted = cipher.doFinal(value.getBytes());
    return byteArrayToHexString(encrypted);
}

From source file:com.projectsontracks.model.CaribooKey.java

/**
 * Creates a new AES key/*from   w  ww .  j  a v  a  2s . c  o  m*/
 *
 * @throws java.security.NoSuchAlgorithmException
 */
public void createKey() throws NoSuchAlgorithmException {
    // Initialize the key generator
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(this.size);
    // Generates the key
    SecretKey skey = kgen.generateKey();
    // Returns the key in its primary encoding format, or null if this key does not support encoding.
    key = skey.getEncoded();
    //used to construct a SecretKey from a byte array, without having to go through a (provider-based) SecretKeyFactory.
    keySpec = new SecretKeySpec(key, "AES");
}

From source file:net.alegen.datpass.library.crypto.CryptoManager.java

public String decrypt(EncryptionOutput encryptionOutput, String password) {
    final String ctext = encryptionOutput.getCypherText();
    final String salt = encryptionOutput.getSalt();
    final String iv = encryptionOutput.getIV();
    try {/* www  . j a v a  2  s.  com*/
        // set up the decryption key
        byte[] saltBytes = Base64.decodeBase64(salt.getBytes("UTF-8"));
        SecretKey key = this.derivateKey(KeyDerivationFunctions.PBKDF2_HMAC_SHA1, password, saltBytes,
                AES_KEY_LENGTH, DEFAULT_ITERATIONS);
        key = new SecretKeySpec(key.getEncoded(), "AES");

        // decrypt cipher text with AES using generated key
        byte[] cipherBytes = Base64.decodeBase64(ctext.getBytes("UTF-8"));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iVBytes = Base64.decodeBase64(iv.getBytes("UTF-8"));
        cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iVBytes));
        byte[] plaintext = cipher.doFinal(cipherBytes);

        // return plaintext
        return new String(plaintext, "UTF-8");
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException
            | BadPaddingException | UnsupportedEncodingException | InvalidAlgorithmParameterException e) {
        log.error("An error occured while decrypting the message.");
        return null;
    }
}

From source file:com.thoughtworks.go.server.util.EncryptionHelperTest.java

@Test
void shouldEncryptAndDecryptChunkUsingAESandRSA() throws Exception {
    String chunk = StringUtils.repeat("Encryption is awesome!", 150);

    File privateKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-private.pem").getFile());
    File publicKeyFile = new File(
            getClass().getClassLoader().getResource("rsa/subordinate-public.pem").getFile());

    SecretKey secretKey = EncryptionHelper.generateAESKey();

    String aesEncryptedData = EncryptionHelper.encryptUsingAES(secretKey, chunk);
    String rsaEncryptedAESKey = EncryptionHelper.encryptUsingRSA(
            Base64.getEncoder().encodeToString(secretKey.getEncoded()),
            FileUtils.readFileToString(publicKeyFile, "utf8"));

    String secretKeyContent = EncryptionHelper.decryptUsingRSA(rsaEncryptedAESKey,
            FileUtils.readFileToString(privateKeyFile, "utf8"));
    byte[] decryptedKey = Base64.getDecoder().decode(secretKeyContent);
    secretKey = new SecretKeySpec(decryptedKey, 0, decryptedKey.length, "AES");

    String decryptedData = EncryptionHelper.decryptUsingAES(secretKey, aesEncryptedData);

    assertThat(chunk, is(decryptedData));
}

From source file:ai.serotonin.backup.Base.java

SecretKey createSecretKey(final byte[] salt) throws Exception {
    final String password = getArchivePassword();
    final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    final KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256);
    final SecretKey tmp = factory.generateSecret(spec);
    final SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
    return secret;
}

From source file:com.thoughtworks.go.domain.AccessTokenTest.java

@Test
void hashToken_shouldHashTheProvidedString() throws Exception {
    AccessToken.AccessTokenWithDisplayValue token = AccessToken.create(null, null, null, new TestingClock());

    SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
            .generateSecret(new PBEKeySpec(token.getDisplayValue().substring(8).toCharArray(),
                    token.getSaltValue().getBytes(StandardCharsets.UTF_8), 4096, 256));

    assertThat(token.getValue()).isEqualTo(Hex.encodeHexString(key.getEncoded()));
}

From source file:TDS.Shared.Web.Encryption.java

/**
 * initializes ciphers and adds jce provider if provided
 * /*from w w  w .  j ava2  s.  c  om*/
 * @throws TDSEncryptionException
 */
@PostConstruct
protected void init() {
    final String encryptionKey = configurationManager.getAppSettings().get("EncryptionKey");

    if (encryptionKey == null || StringUtils.isBlank(encryptionKey)
            || encryptionKey.length() < MINIMUM_KEY_LENGTH) {
        throw new TDSEncryptionException(
                String.format("Number of characters for key must be greater than %s", MINIMUM_KEY_LENGTH));
    }

    if (_jceProvider != null) {
        try {
            Security.addProvider(((Provider) Class.forName(_jceProviderClass).newInstance()));
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
            _logger.error(e.getMessage(), e);
            throw new TDSEncryptionException("JCE Provider class name is not valid");
        }
    }

    try {

        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBE_KEY_ALGORITHM);
        KeySpec keySpec = new PBEKeySpec(encryptionKey.toCharArray(), PBE_SALT, PBE_NUM_ITERATIONS,
                PBE_KEY_LENGTH);
        SecretKey secretKeyTemp;
        secretKeyTemp = secretKeyFactory.generateSecret(keySpec);
        _secretKey = new SecretKeySpec(secretKeyTemp.getEncoded(), CIPHER_ALGORITHM);
        if (_jceProvider == null) {
            _encryptCipher = Cipher.getInstance(TRANSFORMATION);
            _decryptCipher = Cipher.getInstance(TRANSFORMATION);
        } else {
            _encryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider);
            _decryptCipher = Cipher.getInstance(TRANSFORMATION, _jceProvider);
        }
        _encryptCipher.init(Cipher.ENCRYPT_MODE, _secretKey);
    } catch (NoSuchAlgorithmException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Algorithm is not available");
    } catch (InvalidKeySpecException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key specification is not valid");
    } catch (NoSuchPaddingException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Padding is not valid");
    } catch (NoSuchProviderException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Provider is not available");
    } catch (InvalidKeyException e) {
        _logger.error("Encyption.initCipher: " + e.getMessage(), e);
        throw new TDSEncryptionException("Key is not valid");
    }
}