Java Code Examples for java.security.Key#getEncoded()
The following examples show how to use
java.security.Key#getEncoded() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DirectKmsMaterialProviderTest.java From aws-dynamodb-encryption-java with Apache License 2.0 | 6 votes |
@Test public void simple() throws GeneralSecurityException { DirectKmsMaterialProvider prov = new DirectKmsMaterialProvider(kms, keyId); EncryptionMaterials eMat = prov.getEncryptionMaterials(ctx); SecretKey encryptionKey = eMat.getEncryptionKey(); assertNotNull(encryptionKey); Key signingKey = eMat.getSigningKey(); assertNotNull(signingKey); DecryptionMaterials dMat = prov.getDecryptionMaterials(ctx(eMat)); assertEquals(encryptionKey, dMat.getDecryptionKey()); assertEquals(signingKey, dMat.getVerificationKey()); String expectedEncAlg = encryptionKey.getAlgorithm() + "/" + (encryptionKey.getEncoded().length * 8); String expectedSigAlg = signingKey.getAlgorithm() + "/" + (signingKey.getEncoded().length * 8); Map<String, String> kmsCtx = kms.getSingleEc(); assertEquals(expectedEncAlg, kmsCtx.get("*" + WrappedRawMaterials.CONTENT_KEY_ALGORITHM + "*")); assertEquals(expectedSigAlg, kmsCtx.get("*amzn-ddb-sig-alg*")); }
Example 2
Source File: KeyValidationSupport.java From Jose4j with Apache License 2.0 | 6 votes |
public static void validateAesWrappingKey(Key managementKey, String joseAlg, int expectedKeyByteLength) throws InvalidKeyException { KeyValidationSupport.notNull(managementKey); String alg = managementKey.getAlgorithm(); if (!AesKey.ALGORITHM.equals(alg)) { throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected an " + AesKey.ALGORITHM+ " key but an " + alg + " key was provided."); } if (managementKey.getEncoded() != null) { int managementKeyByteLength = managementKey.getEncoded().length; if (managementKeyByteLength != expectedKeyByteLength) { throw new InvalidKeyException("Invalid key for JWE " + joseAlg + ", expected a " + ByteUtil.bitLength(expectedKeyByteLength)+ " bit key but a " + ByteUtil.bitLength(managementKeyByteLength) + " bit key was provided."); } } }
Example 3
Source File: CipherWithWrappingSpi.java From dragonwell8_jdk with GNU General Public License v2.0 | 6 votes |
/** * Wrap a key. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block * cipher, no padding has been requested, and the length of the * encoding of the key to be wrapped is not a * multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software only cipher). */ protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] result = null; try { byte[] encodedKey = key.getEncoded(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidKeyException("Cannot get an encoding of " + "the key to be wrapped"); } result = engineDoFinal(encodedKey, 0, encodedKey.length); } catch (BadPaddingException e) { // Should never happen } return result; }
Example 4
Source File: CipherWithWrappingSpi.java From hottub with GNU General Public License v2.0 | 6 votes |
/** * Wrap a key. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block * cipher, no padding has been requested, and the length of the * encoding of the key to be wrapped is not a * multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software only cipher). */ protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] result = null; try { byte[] encodedKey = key.getEncoded(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidKeyException("Cannot get an encoding of " + "the key to be wrapped"); } result = engineDoFinal(encodedKey, 0, encodedKey.length); } catch (BadPaddingException e) { // Should never happen } return result; }
Example 5
Source File: BcKeyStoreSpi.java From ripple-lib-java with ISC License | 6 votes |
private void encodeKey( Key key, DataOutputStream dOut) throws IOException { byte[] enc = key.getEncoded(); if (key instanceof PrivateKey) { dOut.write(KEY_PRIVATE); } else if (key instanceof PublicKey) { dOut.write(KEY_PUBLIC); } else { dOut.write(KEY_SECRET); } dOut.writeUTF(key.getFormat()); dOut.writeUTF(key.getAlgorithm()); dOut.writeInt(enc.length); dOut.write(enc); }
Example 6
Source File: RSACipher.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 6 votes |
protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException { byte[] encoded = key.getEncoded(); // TODO - unextractable key if ((encoded == null) || (encoded.length == 0)) { throw new InvalidKeyException("Could not obtain encoded key"); } if (encoded.length > buffer.length) { throw new InvalidKeyException("Key is too long for wrapping"); } update(encoded, 0, encoded.length); try { return doFinal(); } catch (BadPaddingException e) { // should not occur throw new InvalidKeyException("Wrapping failed", e); } }
Example 7
Source File: CipherWithWrappingSpi.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Wrap a key. * * @param key the key to be wrapped. * * @return the wrapped key. * * @exception IllegalBlockSizeException if this cipher is a block * cipher, no padding has been requested, and the length of the * encoding of the key to be wrapped is not a * multiple of the block size. * * @exception InvalidKeyException if it is impossible or unsafe to * wrap the key with this cipher (e.g., a hardware protected key is * being passed to a software only cipher). */ protected final byte[] engineWrap(Key key) throws IllegalBlockSizeException, InvalidKeyException { byte[] result = null; try { byte[] encodedKey = key.getEncoded(); if ((encodedKey == null) || (encodedKey.length == 0)) { throw new InvalidKeyException("Cannot get an encoding of " + "the key to be wrapped"); } result = engineDoFinal(encodedKey, 0, encodedKey.length); } catch (BadPaddingException e) { // Should never happen } return result; }
Example 8
Source File: EncryptionUtil.java From hbase with Apache License 2.0 | 5 votes |
/** * Protect a key by encrypting it with the secret key of the given subject. * The configuration must be set up correctly for key alias resolution. * @param conf configuration * @param subject subject key alias * @param key the key * @return the encrypted key bytes */ public static byte[] wrapKey(Configuration conf, String subject, Key key) throws IOException { // Wrap the key with the configured encryption algorithm. String algorithm = conf.get(HConstants.CRYPTO_KEY_ALGORITHM_CONF_KEY, HConstants.CIPHER_AES); Cipher cipher = Encryption.getCipher(conf, algorithm); if (cipher == null) { throw new RuntimeException("Cipher '" + algorithm + "' not available"); } EncryptionProtos.WrappedKey.Builder builder = EncryptionProtos.WrappedKey.newBuilder(); builder.setAlgorithm(key.getAlgorithm()); byte[] iv = null; if (cipher.getIvLength() > 0) { iv = new byte[cipher.getIvLength()]; RNG.nextBytes(iv); builder.setIv(UnsafeByteOperations.unsafeWrap(iv)); } byte[] keyBytes = key.getEncoded(); builder.setLength(keyBytes.length); builder.setHash(UnsafeByteOperations.unsafeWrap(Encryption.hash128(keyBytes))); ByteArrayOutputStream out = new ByteArrayOutputStream(); Encryption.encryptWithSubjectKey(out, new ByteArrayInputStream(keyBytes), subject, conf, cipher, iv); builder.setData(UnsafeByteOperations.unsafeWrap(out.toByteArray())); // Build and return the protobuf message out.reset(); builder.build().writeDelimitedTo(out); return out.toByteArray(); }
Example 9
Source File: AesCbcHmacShaEncryptionProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void verifyAndDecodeJwe(JWE jwe) throws IOException, GeneralSecurityException { Key aesKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.ENCRYPTION, false); if (aesKey == null) { throw new IllegalArgumentException("AES CEK key not present"); } Key hmacShaKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.SIGNATURE, false); if (hmacShaKey == null) { throw new IllegalArgumentException("HMAC CEK key not present"); } int expectedAesKeyLength = getExpectedAesKeyLength(); if (expectedAesKeyLength != aesKey.getEncoded().length) { throw new IllegalStateException("Length of aes key should be " + expectedAesKeyLength +", but was " + aesKey.getEncoded().length); } byte[] aad = jwe.getBase64Header().getBytes(StandardCharsets.UTF_8); byte[] authenticationTag = computeAuthenticationTag(aad, jwe.getInitializationVector(), jwe.getEncryptedContent(), hmacShaKey); byte[] expectedAuthTag = jwe.getAuthenticationTag(); boolean digitsEqual = MessageDigest.isEqual(expectedAuthTag, authenticationTag); if (!digitsEqual) { throw new IllegalArgumentException("Signature validations failed"); } byte[] contentBytes = decryptBytes(jwe.getEncryptedContent(), jwe.getInitializationVector(), aesKey); jwe.content(contentBytes); }
Example 10
Source File: EncryptRSA.java From translationstudio8 with GNU General Public License v2.0 | 5 votes |
public EncryptRSA() throws Exception { SecureRandom sr = new SecureRandom(); KeyPairGenerator kpg = KeyPairGenerator.getInstance(algorithm); kpg.initialize(key_size, sr); KeyPair kp = kpg.generateKeyPair(); Key keyPublic = kp.getPublic(); publicKey = keyPublic.getEncoded(); Key keyPrivate = kp.getPrivate(); privateKey = keyPrivate.getEncoded(); }
Example 11
Source File: TestKeyStoreKeyProvider.java From hbase with Apache License 2.0 | 5 votes |
@Test public void testKeyStoreKeyProviderWithPassword() throws Exception { KeyProvider provider = new KeyStoreKeyProvider(); provider.init("jceks://" + storeFile.toURI().getPath() + "?password=" + PASSWORD); Key key = provider.getKey(ALIAS); assertNotNull(key); byte[] keyBytes = key.getEncoded(); assertEquals(keyBytes.length, KEY.length); for (int i = 0; i < KEY.length; i++) { assertEquals(keyBytes[i], KEY[i]); } }
Example 12
Source File: AES.java From aes-rsa-java with Apache License 2.0 | 5 votes |
public static byte[] genarateRandomKey() { KeyGenerator keygen = null; try { keygen = KeyGenerator.getInstance(ConfigureEncryptAndDecrypt.AES_ALGORITHM); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(" genarateRandomKey fail!", e); } SecureRandom random = new SecureRandom(); keygen.init(random); Key key = keygen.generateKey(); return key.getEncoded(); }
Example 13
Source File: KeyFactory.java From ripple-lib-java with ISC License | 5 votes |
protected KeySpec engineGetKeySpec(Key key, Class keySpec) throws InvalidKeySpecException { if (keySpec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) { return new PKCS8EncodedKeySpec(key.getEncoded()); } else if (keySpec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) { return new X509EncodedKeySpec(key.getEncoded()); } throw new InvalidKeySpecException("not implemented yet " + key + " " + keySpec); }
Example 14
Source File: AesCbcHmacShaEncryptionProvider.java From keycloak with Apache License 2.0 | 5 votes |
@Override public void encodeJwe(JWE jwe) throws IOException, GeneralSecurityException { byte[] contentBytes = jwe.getContent(); byte[] initializationVector = JWEUtils.generateSecret(16); Key aesKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.ENCRYPTION, false); if (aesKey == null) { throw new IllegalArgumentException("AES CEK key not present"); } Key hmacShaKey = jwe.getKeyStorage().getCEKKey(JWEKeyStorage.KeyUse.SIGNATURE, false); if (hmacShaKey == null) { throw new IllegalArgumentException("HMAC CEK key not present"); } int expectedAesKeyLength = getExpectedAesKeyLength(); if (expectedAesKeyLength != aesKey.getEncoded().length) { throw new IllegalStateException("Length of aes key should be " + expectedAesKeyLength +", but was " + aesKey.getEncoded().length); } byte[] cipherBytes = encryptBytes(contentBytes, initializationVector, aesKey); byte[] aad = jwe.getBase64Header().getBytes(StandardCharsets.UTF_8); byte[] authenticationTag = computeAuthenticationTag(aad, initializationVector, cipherBytes, hmacShaKey); jwe.setEncryptedContentInfo(initializationVector, cipherBytes, authenticationTag); }
Example 15
Source File: BaseCipherSpi.java From RipplePower with Apache License 2.0 | 4 votes |
protected int engineGetKeySize( Key key) { return key.getEncoded().length; }
Example 16
Source File: PemFile.java From bouncycastle-rsa-pem-write with MIT License | 4 votes |
public PemFile (Key key, String description) { this.pemObject = new PemObject(description, key.getEncoded()); }
Example 17
Source File: BaseWrapCipher.java From ripple-lib-java with ISC License | 4 votes |
protected void engineInit( int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { CipherParameters param; if (key instanceof BCPBEKey) { BCPBEKey k = (BCPBEKey)key; if (params instanceof PBEParameterSpec) { param = PBE.Util.makePBEParameters(k, params, wrapEngine.getAlgorithmName()); } else if (k.getParam() != null) { param = k.getParam(); } else { throw new InvalidAlgorithmParameterException("PBE requires PBE parameters to be set."); } } else { param = new KeyParameter(key.getEncoded()); } if (params instanceof IvParameterSpec) { IvParameterSpec iv = (IvParameterSpec) params; param = new ParametersWithIV(param, iv.getIV()); } if (param instanceof KeyParameter && ivSize != 0) { iv = new byte[ivSize]; random.nextBytes(iv); param = new ParametersWithIV(param, iv); } if (random != null) { param = new ParametersWithRandom(param, random); } switch (opmode) { case Cipher.WRAP_MODE: wrapEngine.init(true, param); break; case Cipher.UNWRAP_MODE: wrapEngine.init(false, param); break; case Cipher.ENCRYPT_MODE: case Cipher.DECRYPT_MODE: throw new IllegalArgumentException("engine only valid for wrapping"); default: System.out.println("eeek!"); } }
Example 18
Source File: PemFile.java From WeEvent with Apache License 2.0 | 4 votes |
public PemFile(Key key, String desc) { this.pemObject = new PemObject(desc, key.getEncoded()); }
Example 19
Source File: ElGamalTest2.java From java_security with MIT License | 2 votes |
/** * 取得公钥 * @param keyMap 密钥map * @return byte[] 公钥 * */ public static byte[] getPublicKey(Map<String,Object> keyMap) throws Exception{ Key key=(Key) keyMap.get(PUBLIC_KEY); return key.getEncoded(); }
Example 20
Source File: ToolECDSA.java From protools with Apache License 2.0 | 2 votes |
/** * 取得公钥 * * @param keyMap * 密钥Map * * @return byte[] 公钥 * * @throws Exception */ public static byte[] getPublicKey(Map<String, Object> keyMap) { Key key = (Key) keyMap.get(PUBLIC_KEY); return key.getEncoded(); }