Search in sources :

Example 21 with Key

use of java.security.Key in project sonarqube by SonarSource.

the class AesCipherTest method loadSecretKeyFromFile_trim_content.

@Test
public void loadSecretKeyFromFile_trim_content() throws Exception {
    URL resource = getClass().getResource("/org/sonar/api/config/AesCipherTest/non_trimmed_secret_key.txt");
    String path = new File(resource.toURI()).getCanonicalPath();
    AesCipher cipher = new AesCipher(null);
    Key secretKey = cipher.loadSecretFileFromFile(path);
    assertThat(secretKey.getAlgorithm()).isEqualTo("AES");
    assertThat(secretKey.getEncoded().length).isGreaterThan(10);
}
Also used : File(java.io.File) URL(java.net.URL) Key(java.security.Key) Test(org.junit.Test)

Example 22 with Key

use of java.security.Key in project Openfire by igniterealtime.

the class AesEncryptor method cipher.

/**
	 * Symmetric encrypt/decrypt routine.
	 *
	 * @param attribute The value to be converted
	 * @param key The encryption key
	 * @param mode The cipher mode (encrypt or decrypt)
	 * @return The converted attribute, or null if conversion fails
	 */
private byte[] cipher(byte[] attribute, byte[] key, int mode) {
    byte[] result = null;
    try {
        // Create AES encryption key
        Key aesKey = new SecretKeySpec(key, "AES");
        // Create AES Cipher
        Cipher aesCipher = Cipher.getInstance(ALGORITHM);
        // Initialize AES Cipher and convert
        aesCipher.init(mode, aesKey, new IvParameterSpec(INIT_PARM));
        result = aesCipher.doFinal(attribute);
    } catch (Exception e) {
        log.error("AES cipher failed", e);
    }
    return result;
}
Also used : SecretKeySpec(javax.crypto.spec.SecretKeySpec) IvParameterSpec(javax.crypto.spec.IvParameterSpec) Cipher(javax.crypto.Cipher) Key(java.security.Key)

Example 23 with Key

use of java.security.Key in project jjwt by jwtk.

the class DefaultJwtBuilder method compact.

@Override
public String compact() {
    if (payload == null && Collections.isEmpty(claims)) {
        throw new IllegalStateException("Either 'payload' or 'claims' must be specified.");
    }
    if (payload != null && !Collections.isEmpty(claims)) {
        throw new IllegalStateException("Both 'payload' and 'claims' cannot both be specified. Choose either one.");
    }
    if (key != null && keyBytes != null) {
        throw new IllegalStateException("A key object and key bytes cannot both be specified. Choose either one.");
    }
    Header header = ensureHeader();
    Key key = this.key;
    if (key == null && !Objects.isEmpty(keyBytes)) {
        key = new SecretKeySpec(keyBytes, algorithm.getJcaName());
    }
    JwsHeader jwsHeader;
    if (header instanceof JwsHeader) {
        jwsHeader = (JwsHeader) header;
    } else {
        jwsHeader = new DefaultJwsHeader(header);
    }
    if (key != null) {
        jwsHeader.setAlgorithm(algorithm.getValue());
    } else {
        //no signature - plaintext JWT:
        jwsHeader.setAlgorithm(SignatureAlgorithm.NONE.getValue());
    }
    if (compressionCodec != null) {
        jwsHeader.setCompressionAlgorithm(compressionCodec.getAlgorithmName());
    }
    String base64UrlEncodedHeader = base64UrlEncode(jwsHeader, "Unable to serialize header to json.");
    String base64UrlEncodedBody;
    if (compressionCodec != null) {
        byte[] bytes;
        try {
            bytes = this.payload != null ? payload.getBytes(Strings.UTF_8) : toJson(claims);
        } catch (JsonProcessingException e) {
            throw new IllegalArgumentException("Unable to serialize claims object to json.");
        }
        base64UrlEncodedBody = TextCodec.BASE64URL.encode(compressionCodec.compress(bytes));
    } else {
        base64UrlEncodedBody = this.payload != null ? TextCodec.BASE64URL.encode(this.payload) : base64UrlEncode(claims, "Unable to serialize claims object to json.");
    }
    String jwt = base64UrlEncodedHeader + JwtParser.SEPARATOR_CHAR + base64UrlEncodedBody;
    if (key != null) {
        //jwt must be signed:
        JwtSigner signer = createSigner(algorithm, key);
        String base64UrlSignature = signer.sign(jwt);
        jwt += JwtParser.SEPARATOR_CHAR + base64UrlSignature;
    } else {
        // no signature (plaintext), but must terminate w/ a period, see
        // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-25#section-6.1
        jwt += JwtParser.SEPARATOR_CHAR;
    }
    return jwt;
}
Also used : JwtSigner(io.jsonwebtoken.impl.crypto.JwtSigner) DefaultJwtSigner(io.jsonwebtoken.impl.crypto.DefaultJwtSigner) Header(io.jsonwebtoken.Header) JwsHeader(io.jsonwebtoken.JwsHeader) SecretKeySpec(javax.crypto.spec.SecretKeySpec) JwsHeader(io.jsonwebtoken.JwsHeader) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Key(java.security.Key)

Example 24 with Key

use of java.security.Key in project platformlayer by platformlayer.

the class ManagedKeystore method insertKey.

private void insertKey(KeyStore keystore, ManagedSecretKey key) throws OpsException {
    String keyPassword = KeyStoreUtils.DEFAULT_KEYSTORE_SECRET;
    X509Certificate[] certificate = key.getCertificateChain();
    List<X509Certificate> certificateChain = Lists.newArrayList();
    certificateChain.addAll(Arrays.asList(certificate));
    ensureIsCompleteCertificateChain(certificateChain);
    addAll(keystore, certificateChain);
    Key privateKey = key.getPrivateKey();
    X509Certificate[] certificateChainArray = certificateChain.toArray(new X509Certificate[certificateChain.size()]);
    try {
        keystore.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), certificateChainArray);
    } catch (KeyStoreException e) {
        throw new OpsException("Error while installing private key", e);
    }
}
Also used : OpsException(org.platformlayer.ops.OpsException) KeyStoreException(java.security.KeyStoreException) X509Certificate(java.security.cert.X509Certificate) PublicKey(java.security.PublicKey) PlatformLayerKey(org.platformlayer.core.model.PlatformLayerKey) Key(java.security.Key)

Example 25 with Key

use of java.security.Key in project robovm by robovm.

the class AlgorithmParameterSymmetricHelper method test.

@Override
public void test(AlgorithmParameters parameters) {
    KeyGenerator generator = null;
    try {
        generator = KeyGenerator.getInstance(algorithmName);
    } catch (NoSuchAlgorithmException e) {
        Assert.fail(e.getMessage());
    }
    generator.init(keySize);
    Key key = generator.generateKey();
    Cipher cipher = null;
    try {
        String transformation = algorithmName;
        if (blockmode != null) {
            transformation += "/" + blockmode;
        }
        cipher = Cipher.getInstance(transformation);
    } catch (NoSuchAlgorithmException e) {
        Assert.fail(e.getMessage());
    } catch (NoSuchPaddingException e) {
        Assert.fail(e.getMessage());
    }
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key, parameters);
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        Assert.fail(e.getMessage());
    }
    byte[] bs = null;
    try {
        bs = cipher.doFinal(plainData.getBytes());
    } catch (IllegalBlockSizeException e) {
        Assert.fail(e.getMessage());
    } catch (BadPaddingException e) {
        Assert.fail(e.getMessage());
    }
    try {
        cipher.init(Cipher.DECRYPT_MODE, key, parameters);
    } catch (InvalidKeyException e) {
        Assert.fail(e.getMessage());
    } catch (InvalidAlgorithmParameterException e) {
        Assert.fail(e.getMessage());
    }
    byte[] decrypted = null;
    try {
        decrypted = cipher.doFinal(bs);
    } catch (IllegalBlockSizeException e) {
        Assert.fail(e.getMessage());
    } catch (BadPaddingException e) {
        Assert.fail(e.getMessage());
    }
    Assert.assertTrue(Arrays.equals(plainData.getBytes(), decrypted));
}
Also used : InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) IllegalBlockSizeException(javax.crypto.IllegalBlockSizeException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) Cipher(javax.crypto.Cipher) BadPaddingException(javax.crypto.BadPaddingException) InvalidKeyException(java.security.InvalidKeyException) KeyGenerator(javax.crypto.KeyGenerator) Key(java.security.Key)

Aggregations

Key (java.security.Key)268 PrivateKey (java.security.PrivateKey)108 SecretKey (javax.crypto.SecretKey)77 KeyStore (java.security.KeyStore)62 PublicKey (java.security.PublicKey)58 X509Certificate (java.security.cert.X509Certificate)56 Cipher (javax.crypto.Cipher)54 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)46 IOException (java.io.IOException)39 ByteArrayInputStream (java.io.ByteArrayInputStream)38 Certificate (java.security.cert.Certificate)36 KeyFactory (java.security.KeyFactory)35 InvalidKeyException (java.security.InvalidKeyException)31 KeyGenerator (javax.crypto.KeyGenerator)31 SecretKeySpec (javax.crypto.spec.SecretKeySpec)27 PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)26 Test (org.junit.Test)26 KeyStoreException (java.security.KeyStoreException)21 SecureRandom (java.security.SecureRandom)21 IvParameterSpec (javax.crypto.spec.IvParameterSpec)18