java.security.Key Java Examples
The following examples show how to use
java.security.Key.
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: KeyProtector.java From jdk8u60 with GNU General Public License v2.0 | 7 votes |
/** * Seals the given cleartext key, using the password provided at * construction time */ SealedObject seal(Key key) throws Exception { // create a random salt (8 bytes) byte[] salt = new byte[8]; SunJCE.getRandom().nextBytes(salt); // create PBE parameters from salt and iteration count PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20); // create PBE key from password PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password); SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES"); pbeKeySpec.clearPassword(); // seal key Cipher cipher; PBEWithMD5AndTripleDESCipher cipherSpi; cipherSpi = new PBEWithMD5AndTripleDESCipher(); cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(), "PBEWithMD5AndTripleDES"); cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec); return new SealedObjectForKeyProtector(key, cipher); }
Example #2
Source File: ToolAES.java From protools with Apache License 2.0 | 6 votes |
/** * 加密 * * @param data * 待加密数据 * @param key * 密钥 * * @return byte[] 加密数据 * * @throws Exception */ public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { // 还原密钥 Key k = toKey(key); /* * 实例化 使用PKCS7Padding填充方式,按如下方式实现 Cipher.getInstance(CIPHER_ALGORITHM, * "BC"); */ Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM); // 初始化,设置为加密模式 cipher.init(Cipher.ENCRYPT_MODE, k); // 执行操作 return cipher.doFinal(data); }
Example #3
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 #4
Source File: ClientServerExample.java From opc-ua-stack with Apache License 2.0 | 6 votes |
public KeyStoreLoader load() throws Exception { KeyStore keyStore = KeyStore.getInstance("PKCS12"); keyStore.load(getClass().getClassLoader().getResourceAsStream("example-keystore.pfx"), PASSWORD); Key serverPrivateKey = keyStore.getKey(SERVER_ALIAS, PASSWORD); if (serverPrivateKey instanceof PrivateKey) { serverCertificate = (X509Certificate) keyStore.getCertificate(SERVER_ALIAS); PublicKey serverPublicKey = serverCertificate.getPublicKey(); serverKeyPair = new KeyPair(serverPublicKey, (PrivateKey) serverPrivateKey); } Key clientPrivateKey = keyStore.getKey(CLIENT_ALIAS, PASSWORD); if (clientPrivateKey instanceof PrivateKey) { clientCertificate = (X509Certificate) keyStore.getCertificate(CLIENT_ALIAS); PublicKey clientPublicKey = clientCertificate.getPublicKey(); clientKeyPair = new KeyPair(clientPublicKey, (PrivateKey) clientPrivateKey); } return this; }
Example #5
Source File: SignatureBaseRSA.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
/** @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } }
Example #6
Source File: DES.java From AndroidStudyDemo with GNU General Public License v2.0 | 6 votes |
/** * DES算法,加密 * @param data 待加密字符串 * @param key 加密私钥,长度不能够小于8位 * @return 加密后的字节数组,一般结合Base64编码使用 * @throws Exception */ public static String encode(String key, String data) { if (data == null) return null; try { DESKeySpec dks = new DESKeySpec(key.getBytes()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); // key的长度不能够小于8位字节 Key secretKey = keyFactory.generateSecret(dks); Cipher cipher = Cipher.getInstance(ALGORITHM_DES); IvParameterSpec iv = new IvParameterSpec("12345678".getBytes()); AlgorithmParameterSpec paramSpec = iv; cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); byte[] bytes = cipher.doFinal(data.getBytes()); return byte2String(bytes); } catch (Exception e) { e.printStackTrace(); return data; } }
Example #7
Source File: Main.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Changes a key password. */ private void doChangeKeyPasswd(String alias) throws Exception { if (alias == null) { alias = keyAlias; } Pair<Key,char[]> objs = recoverKey(alias, storePass, keyPass); Key privKey = objs.fst; if (keyPass == null) { keyPass = objs.snd; } if (keyPassNew == null) { MessageFormat form = new MessageFormat (rb.getString("key.password.for.alias.")); Object[] source = {alias}; keyPassNew = getNewPasswd(form.format(source), keyPass); } keyStore.setKeyEntry(alias, privKey, keyPassNew, keyStore.getCertificateChain(alias)); }
Example #8
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 6 votes |
private static String createToken(Key key, JsonObject jsonClaims) { JwtClaims claims = new JwtClaims(); claims.setSubject(jsonClaims.toString()); claims.setIssuedAtToNow(); claims.setExpirationTime(NumericDate.fromSeconds(NumericDate.now().getValue() + JWT_TOKEN_EXPIRES_TIME)); JsonWebSignature jws = new JsonWebSignature(); jws.setDoKeyValidation(false); jws.setPayload(claims.toJson()); jws.setKey(key); jws.setAlgorithmHeaderValue(ALG); try { return jws.getCompactSerialization(); } catch (JoseException ex) { LOGGER.log(Level.SEVERE, null, ex); } return null; }
Example #9
Source File: EncryptionServiceImplTest.java From seed with Mozilla Public License 2.0 | 6 votes |
/** * Test method for {@link EncryptionServiceImpl#decrypt(byte[])}. * * @throws Exception if an error occurred */ @Test public void testDecrypt(@Mocked final Key key, @Mocked final Cipher cipher) throws Exception { final String toDecrypt = "ADEF0985C"; EncryptionServiceImpl asymetricCrypting = new EncryptionServiceImpl("alias", null, key); asymetricCrypting.decrypt(toDecrypt.getBytes()); new Verifications() { { cipher.doFinal(toDecrypt.getBytes()); times = 1; } }; }
Example #10
Source File: IntegrityHmac.java From openjdk-8 with GNU General Public License v2.0 | 6 votes |
/** * Method engineInitSign * * @param secretKey * @throws XMLSignatureException */ protected void engineInitSign(Key secretKey) throws XMLSignatureException { if (!(secretKey instanceof SecretKey)) { String supplied = secretKey.getClass().getName(); String needed = SecretKey.class.getName(); Object exArgs[] = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { this.macAlgorithm.init(secretKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } }
Example #11
Source File: ConstructKeys.java From openjdk-8-source with GNU General Public License v2.0 | 6 votes |
static final Key constructKey(byte[] encoding, String keyAlgorithm, int keyType) throws InvalidKeyException, NoSuchAlgorithmException { Key result = null; switch (keyType) { case Cipher.SECRET_KEY: result = ConstructKeys.constructSecretKey(encoding, keyAlgorithm); break; case Cipher.PRIVATE_KEY: result = ConstructKeys.constructPrivateKey(encoding, keyAlgorithm); break; case Cipher.PUBLIC_KEY: result = ConstructKeys.constructPublicKey(encoding, keyAlgorithm); break; } return result; }
Example #12
Source File: JsonWebSignature.java From swim with Apache License 2.0 | 6 votes |
public boolean verifyMac(Key symmetricKey) { final String algorithm = algorithm(); try { if ("HS256".equals(algorithm)) { return verifyMac(Mac.getInstance("HmacSHA256"), symmetricKey); } else if ("HS384".equals(algorithm)) { return verifyMac(Mac.getInstance("HmacSHA384"), symmetricKey); } else if ("HS512".equals(algorithm)) { return verifyMac(Mac.getInstance("HmacSHA512"), symmetricKey); } else { return false; } } catch (GeneralSecurityException cause) { throw new RuntimeException(cause); } }
Example #13
Source File: SSLAlgorithmConstraints.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
@Override public boolean permits(Set<CryptoPrimitive> primitives, Key key) { boolean permitted = true; if (peerAlgConstraints != null) { permitted = peerAlgConstraints.permits(primitives, key); } if (permitted && userAlgConstraints != null) { permitted = userAlgConstraints.permits(primitives, key); } if (permitted) { permitted = tlsDisabledAlgConstraints.permits(primitives, key); } if (permitted && enabledX509DisabledAlgConstraints) { permitted = x509DisabledAlgConstraints.permits(primitives, key); } return permitted; }
Example #14
Source File: Crypt.java From projectforge-webapp with GNU General Public License v3.0 | 6 votes |
/** * Encrypts the given str with AES. The password is first converted using SHA-256. * @param password * @param str * @return The base64 encoded result (url safe). */ public static String encrypt(final String password, final String data) { initialize(); try { // AES is sometimes not part of Java, therefore use bouncy castle provider: final Cipher cipher = Cipher.getInstance(CRYPTO_ALGORITHM); final byte[] keyValue = getPassword(password); final Key key = new SecretKeySpec(keyValue, "AES"); cipher.init(Cipher.ENCRYPT_MODE, key); final byte[] encVal = cipher.doFinal(data.getBytes("UTF-8")); final String encryptedValue = Base64.encodeBase64URLSafeString(encVal); return encryptedValue; } catch (final Exception ex) { log.error("Exception encountered while trying to encrypt with Algorithm 'AES' and the given password: " + ex.getMessage(), ex); return null; } }
Example #15
Source File: SignatureBaseRSA.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** @inheritDoc */ protected void engineInitSign(Key privateKey) throws XMLSignatureException { if (!(privateKey instanceof PrivateKey)) { String supplied = privateKey.getClass().getName(); String needed = PrivateKey.class.getName(); Object exArgs[] = { supplied, needed }; throw new XMLSignatureException("algorithms.WrongKeyForThisOperation", exArgs); } try { this.signatureAlgorithm.initSign((PrivateKey) privateKey); } catch (InvalidKeyException ex) { throw new XMLSignatureException("empty", ex); } }
Example #16
Source File: PasswordUtil.java From jeewx with Apache License 2.0 | 6 votes |
/** * 根据PBE密码生成一把密钥 * * @param password * 生成密钥时所使用的密码 * @return Key PBE算法密钥 * */ private static Key getPBEKey(String password) { // 实例化使用的算法 SecretKeyFactory keyFactory; SecretKey secretKey = null; try { keyFactory = SecretKeyFactory.getInstance(ALGORITHM); // 设置PBE密钥参数 PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); // 生成密钥 secretKey = keyFactory.generateSecret(keySpec); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return secretKey; }
Example #17
Source File: EncryptUtil.java From UtilsLib with MIT License | 5 votes |
/** * 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * * @param arrBTmp 构成该字符串的字节数组 * @return 生成的密钥 * @throws java.lang.Exception */ private Key getKey(byte[] arrBTmp) throws Exception { // 创建一个空的8位字节数组(默认值为0) byte[] arrB = new byte[8]; // 将原始字节数组转换为8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密钥 return new javax.crypto.spec.SecretKeySpec(arrB, "DES"); }
Example #18
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 #19
Source File: JwksAuthenticatorTest.java From trellis with Apache License 2.0 | 5 votes |
@Test void testAuthenticateJwksInvalidKeyLocation() throws Exception { final String webid = "https://people.apache.org/~acoburn/#i"; final Key key = KeyFactory.getInstance("RSA").generatePrivate(new RSAPrivateKeySpec(modulus, exponent)); final String token = Jwts.builder().setHeaderParam(JwsHeader.KEY_ID, keyid).setSubject(webid) .signWith(key).compact(); final Authenticator authenticator = new JwksAuthenticator("https://www.trellisldp.org/tests/non-existent"); assertThrows(SecurityException.class, () -> authenticator.authenticate(token), "Unexpected principal!"); }
Example #20
Source File: Authentication.java From zeppelin with Apache License 2.0 | 5 votes |
private Key generateKey() { try { KeyGenerator kgen = KeyGenerator.getInstance(CIPHER_ALGORITHM); kgen.init(128, new SecureRandom()); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); return new SecretKeySpec(enCodeFormat, CIPHER_ALGORITHM); } catch (Exception e) { LOG.warn("Cannot generate key for decryption", e); } return null; }
Example #21
Source File: TokenProviderUnitTest.java From tutorials with MIT License | 5 votes |
private String createTokenWithDifferentSignature() { Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); return Jwts.builder() .setSubject("anonymous") .signWith(otherKey, SignatureAlgorithm.HS512) .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) .compact(); }
Example #22
Source File: PrivateKeyResolver.java From jdk8u_jdk with GNU General Public License v2.0 | 5 votes |
private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException { log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?"); Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (keyStore.isKeyEntry(alias)) { Certificate cert = keyStore.getCertificate(alias); if (cert instanceof X509Certificate) { XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert); if (certSKI.equals(x509SKI)) { log.log(java.util.logging.Level.FINE, "match !!! "); try { Key key = keyStore.getKey(alias, password); if (key instanceof PrivateKey) { return (PrivateKey) key; } } catch (Exception e) { log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); // Keep searching } } } } } return null; }
Example #23
Source File: JWTokenFactory.java From eplmp with Eclipse Public License 1.0 | 5 votes |
public static String createAuthToken(Key key, UserGroupMapping userGroupMapping) { JsonObjectBuilder subjectBuilder = Json.createObjectBuilder(); subjectBuilder.add(SUBJECT_LOGIN, userGroupMapping.getLogin()); subjectBuilder.add(SUBJECT_GROUP_NAME, userGroupMapping.getGroupName()); JsonObject build = subjectBuilder.build(); return createToken(key, build); }
Example #24
Source File: DefaultCipherExecutor.java From nano-framework with Apache License 2.0 | 5 votes |
/** * Prepare json web token key. * * @param secret the secret * @return the key */ private Key prepareJsonWebTokenKey(final String secret) { try { final Map<String, Object> keys = new HashMap<>(2); keys.put("kty", "oct"); keys.put("k", secret); final JsonWebKey jwk = JsonWebKey.Factory.newJwk(keys); return jwk.getKey(); } catch (final Exception e) { throw new IllegalArgumentException(e.getMessage(), e); } }
Example #25
Source File: RSAUtils.java From danyuan-application with Apache License 2.0 | 5 votes |
/** * <p> * 公钥加密 * </p> * @param data 源数据 * @param publicKey 公钥(BASE64编码) * @return * @throws Exception */ public static byte[] encryptByPublicKey(byte[] data, byte[] publicKey) throws Exception { byte[] keyBytes = Base64Utils.decode(publicKey); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); Key publicK = keyFactory.generatePublic(x509KeySpec); // 对数据加密 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, publicK); int inputLen = data.length; ByteArrayOutputStream out = new ByteArrayOutputStream(); int offSet = 0; byte[] cache; int i = 0; // 对数据分段加密 while (inputLen - offSet > 0) { if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); } else { cache = cipher.doFinal(data, offSet, inputLen - offSet); } out.write(cache, 0, cache.length); i++; offSet = i * MAX_ENCRYPT_BLOCK; } byte[] encryptedData = out.toByteArray(); out.close(); return encryptedData; }
Example #26
Source File: InternalEncryptionService.java From credhub with Apache License 2.0 | 5 votes |
public String decrypt(final Key key, final byte[] encryptedValue, final byte[] nonce) throws Exception { final CipherWrapper decryptionCipher = getCipher(); final AlgorithmParameterSpec parameterSpec = generateParameterSpec(nonce); decryptionCipher.init(Cipher.DECRYPT_MODE, key, parameterSpec); return new String(decryptionCipher.doFinal(encryptedValue), CHARSET); }
Example #27
Source File: KeySelector.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException { return new KeySelectorResult() { public Key getKey() { return key; } }; }
Example #28
Source File: TokenProviderTest.java From alchemy with Apache License 2.0 | 5 votes |
private String createTokenWithDifferentSignature() { Key otherKey = Keys.hmacShaKeyFor(Decoders.BASE64 .decode("Xfd54a45s65fds737b9aafcb3412e07ed99b267f33413274720ddbb7f6c5e64e9f14075f2d7ed041592f0b7657baf8")); return Jwts.builder() .setSubject("anonymous") .signWith(otherKey, SignatureAlgorithm.HS512) .setExpiration(new Date(new Date().getTime() + ONE_MINUTE)) .compact(); }
Example #29
Source File: KeyProviderForTesting.java From hbase with Apache License 2.0 | 5 votes |
@Override public Key[] getKeys(String[] aliases) { Key[] result = new Key[aliases.length]; for (int i = 0; i < aliases.length; i++) { result[i] = new SecretKeySpec(Encryption.hash128(aliases[i]), "AES"); } return result; }
Example #30
Source File: PasswordBasedKeyProxy.java From credhub with Apache License 2.0 | 5 votes |
public Key deriveKey(final List<Byte> salt) { final Byte[] saltArray = salt.toArray(new Byte[0]); final PBEKeySpec pbeSpec = new PBEKeySpec(password.toCharArray(), toPrimitive(saltArray), numIterations, EncryptionConstants.KEY_BIT_LENGTH); try { final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA384"); final SecretKey pbeKey = keyFactory.generateSecret(pbeSpec); return new SecretKeySpec(pbeKey.getEncoded(), "AES"); } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) { throw new RuntimeException(e); } }