Refine search
/** * Decrypt private key * * @param passphrase To decrypt */ private byte[] decrypt(final byte[] key, final String passphrase) throws IOException { try { final Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); final byte[] expanded = this.toKey(passphrase); cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(expanded, 0, 32, "AES"), new IvParameterSpec(new byte[16])); // initial vector=0 return cipher.doFinal(key); } catch (GeneralSecurityException e) { throw new IOException(e.getMessage(), e); } }
public SingleCertTrustManager(InputStream in) throws IOException, GeneralSecurityException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); // Note: KeyStore requires it be loaded even if you don't load anything into it: ks.load(null); CertificateFactory cf = CertificateFactory.getInstance("X509"); cert = (X509Certificate) cf.generateCertificate(in); ks.setCertificateEntry(UUID.randomUUID().toString(), cert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); for (TrustManager tm : tmf.getTrustManagers()) { if (tm instanceof X509TrustManager) { trustManager = (X509TrustManager) tm; break; } } if (trustManager == null) { throw new GeneralSecurityException(GT.tr("No X509TrustManager found")); } }
/** * Hmac加密模板 * * @param data 数据 * @param key 秘钥 * @param algorithm 加密算法 * @return 密文字节数组 */ private static byte[] hmacTemplate(byte[] data, byte[] key, String algorithm) { if (data == null || data.length == 0 || key == null || key.length == 0) return null; try { SecretKeySpec secretKey = new SecretKeySpec(key, algorithm); Mac mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (InvalidKeyException | NoSuchAlgorithmException e) { e.printStackTrace(); return null; } }
@Override public final GeneralSecurityException tooManyKerberosTicketsFound() { final GeneralSecurityException result = new GeneralSecurityException(String.format(getLoggingLocale(), tooManyKerberosTicketsFound$str())); final StackTraceElement[] st = result.getStackTrace(); result.setStackTrace(Arrays.copyOfRange(st, 1, st.length)); return result; } private static final String wrongBase64InPBCompatibleMode = "ELY03032: Base64 string created with unsupported PicketBox version \"%s\"";
private static byte[] hmacSha256(byte[] key, String value) { try { Mac mac = Mac.getInstance("HmacSHA256"); mac.init(new SecretKeySpec(key, "HmacSHA256")); return mac.doFinal(value.getBytes(StandardCharsets.UTF_8)); } catch (NoSuchAlgorithmException | InvalidKeyException e) { throw new UnsupportedOperationException(e.getMessage(), e); } }
} else if (matcherTrans.find()) { paramsAlgo = matcherTrans.group(1); secretKey = new SecretKeySpec(keyBase.getEncoded(), paramsAlgo); } else { throw new GeneralSecurityException(MessageFormat.format( JGitText.get().unsupportedEncryptionAlgorithm, cipherAlgo)); cipher.init(Cipher.ENCRYPT_MODE, secretKey); cipher.doFinal();
public static byte[] calculateHMac(String token, PublicKey publicKey) throws GeneralSecurityException { if (token == null) { throw new IllegalArgumentException("Token cannot be null"); } byte[] tokenBytes = token.getBytes(StandardCharsets.UTF_8); if (tokenBytes.length < 16) { throw new GeneralSecurityException("Token does not meet minimum size of 16 bytes."); } SecretKeySpec keySpec = new SecretKeySpec(tokenBytes, "RAW"); Mac mac = Mac.getInstance("Hmac-SHA256", BouncyCastleProvider.PROVIDER_NAME); mac.init(keySpec); return mac.doFinal(getKeyIdentifier(publicKey)); }
public static String encryptPassword(String password) { try { Cipher encryptCipher = Cipher.getInstance("AES"); encryptCipher.init(Cipher.ENCRYPT_MODE, cipherKey); return DatatypeConverter.printBase64Binary(encryptCipher.doFinal(password.getBytes())); } catch (GeneralSecurityException e) { throw new RuntimeException("unable to encrypt password: " + e.toString(), e); } }
OutputStream fos = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); fis = new FileInputStream(ks); char[] pwchars = ksPW != null ? ksPW.toCharArray() : null; keyStore.load(fis, pwchars); try { fis.close(); } catch (IOException ioe) {} fis = null; throw new GeneralSecurityException("no private keys found"); PrivateKey pk = (PrivateKey) keyStore.getKey(alias, keypwchars); if (pk == null) throw new GeneralSecurityException("private key not found: " + alias); Certificate[] certs = keyStore.getCertificateChain(alias); if (certs.length != 1) throw new GeneralSecurityException("Bad cert chain length"); X509Certificate cert = (X509Certificate) certs[0]; Object[] rv = SelfSignedGenerator.renew(cert, pk, validDays);
protected Key extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey) throws CMSException { Cipher keyEncryptionCipher = helper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm()); try { IvParameterSpec ivSpec = new IvParameterSpec(ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets()); keyEncryptionCipher.init(Cipher.UNWRAP_MODE, new SecretKeySpec(derivedKey, keyEncryptionCipher.getAlgorithm()), ivSpec); return keyEncryptionCipher.unwrap(encryptedContentEncryptionKey, contentEncryptionAlgorithm.getAlgorithm().getId(), Cipher.SECRET_KEY); } catch (GeneralSecurityException e) { throw new CMSException("cannot process content encryption key: " + e.getMessage(), e); } }
/** * Export the private key and certificate chain (if any) out of a keystore. * Does NOT close the output stream. Throws on all errors. * * @param ks path to the keystore * @param ksPW the keystore password, may be null * @param alias the name of the key * @param keyPW the key password, must be at least 6 characters * @since 0.9.25 */ public static void exportPrivateKey(File ks, String ksPW, String alias, String keyPW, OutputStream out) throws GeneralSecurityException, IOException { InputStream fis = null; try { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); fis = new FileInputStream(ks); char[] pwchars = ksPW != null ? ksPW.toCharArray() : null; keyStore.load(fis, pwchars); char[] keypwchars = keyPW.toCharArray(); PrivateKey pk = (PrivateKey) keyStore.getKey(alias, keypwchars); if (pk == null) throw new GeneralSecurityException("private key not found: " + alias); Certificate[] certs = keyStore.getCertificateChain(alias); CertUtil.exportPrivateKey(pk, certs, out); } finally { if (fis != null) try { fis.close(); } catch (IOException ioe) {} } }
public AESSensitivePropertyProvider(String keyHex) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException { byte[] key = validateKey(keyHex); try { cipher = Cipher.getInstance(ALGORITHM, PROVIDER); // Only store the key if the cipher was initialized successfully this.key = new SecretKeySpec(key, "AES"); } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) { logger.error("Encountered an error initializing the {}: {}", IMPLEMENTATION_NAME, e.getMessage()); throw new SensitivePropertyProtectionException("Error initializing the protection cipher", e); } }
public DbKeyStoreSocketFactory() throws DbKeyStoreSocketException { KeyStore keys; char[] password; try { keys = KeyStore.getInstance("JKS"); password = getKeyStorePassword(); keys.load(getKeyStoreStream(), password); } catch (java.security.GeneralSecurityException gse) { throw new DbKeyStoreSocketException("Failed to load keystore: " + gse.getMessage()); } catch (java.io.FileNotFoundException fnfe) { throw new DbKeyStoreSocketException("Failed to find keystore file." + fnfe.getMessage()); } catch (java.io.IOException ioe) { throw new DbKeyStoreSocketException("Failed to read keystore file: " + ioe.getMessage()); } try { KeyManagerFactory keyfact = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyfact.init(keys, password); TrustManagerFactory trustfact = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustfact.init(keys); SSLContext ctx = SSLContext.getInstance("SSL"); ctx.init(keyfact.getKeyManagers(), trustfact.getTrustManagers(), null); _factory = ctx.getSocketFactory(); } catch (java.security.GeneralSecurityException gse) { throw new DbKeyStoreSocketException( "Failed to set up database socket factory: " + gse.getMessage()); } }
private ByteBuf decryptData(SecretKey dataKeySecret, MessageMetadata msgMetadata, ByteBuf payload) { // unpack iv and encrypted data ByteString ivString = msgMetadata.getEncryptionParam(); ivString.copyTo(iv, 0); GCMParameterSpec gcmParams = new GCMParameterSpec(tagLen, iv); ByteBuf targetBuf = null; try { cipher.init(Cipher.DECRYPT_MODE, dataKeySecret, gcmParams); ByteBuffer sourceNioBuf = payload.nioBuffer(payload.readerIndex(), payload.readableBytes()); int maxLength = cipher.getOutputSize(payload.readableBytes()); targetBuf = PooledByteBufAllocator.DEFAULT.buffer(maxLength, maxLength); ByteBuffer targetNioBuf = targetBuf.nioBuffer(0, maxLength); int decryptedSize = cipher.doFinal(sourceNioBuf, targetNioBuf); targetBuf.writerIndex(decryptedSize); } catch (InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | ShortBufferException e) { log.error("{} Failed to decrypt message {}", logCtx, e.getMessage()); if (targetBuf != null) { targetBuf.release(); targetBuf = null; } } return targetBuf; }
private static byte[] encryptHMAC(String data, String secret) throws IOException { byte[] bytes = null; try { SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), "HmacMD5"); Mac mac = Mac.getInstance(secretKey.getAlgorithm()); mac.init(secretKey); bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8)); } catch (GeneralSecurityException gse) { throw new IOException(gse.toString()); } return bytes; }
conf.get(resolvePropertyName(mode, SSL_KEYSTORE_TYPE_TPL_KEY), DEFAULT_KEYSTORE_TYPE); KeyStore keystore = KeyStore.getInstance(keystoreType); String keystoreKeyPassword = null; if (requireClientCert || mode == SSLFactory.Mode.SERVER) { String keystoreLocation = conf.get(locationProperty, ""); if (keystoreLocation.isEmpty()) { throw new GeneralSecurityException("The property '" + locationProperty + "' has not been set in the ssl configuration file."); String keystorePassword = getPassword(conf, passwordProperty, ""); if (keystorePassword.isEmpty()) { throw new GeneralSecurityException("The property '" + passwordProperty + "' has not been set in the ssl configuration file."); keystore.load(is, keystorePassword.toCharArray()); } finally { is.close(); keystore.load(null, null);
keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); Enumeration<String> aliases = keyStore.aliases(); List<String> keyAliases = new ArrayList<>(); while (aliases.hasMoreElements()) { e.printStackTrace();
for (int i = nSize -1; i >= 0 ; i--) { X509Certificate x509certificate = x509Certificates[i]; Principal principalIssuer = x509certificate.getIssuerDN(); Principal principalSubject = x509certificate.getSubjectDN(); if (principalLast != null) { if (principalIssuer.equals(principalLast)) { try { PublicKey publickey = x509Certificates[i + 1].getPublicKey(); x509Certificates[i].verify(publickey); Enumeration<String> aliases = trustStore.aliases(); while(aliases.hasMoreElements()) { String alias = aliases.nextElement(); X509Certificate tCert = (X509Certificate) trustStore.getCertificate(alias); if(x509Certificates[nSize - 1].equals(tCert)) { try { throw new CertificateException("certificate path failed: "+e.getMessage()); } catch(Exception e) { Log.debug("ClientTrustManager:",e);
throw new GeneralSecurityException(JGitText.get().encryptionOnlyPBE); cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec); cipher.doFinal();
cipher = Cipher.getInstance(AESGCM, BouncyCastleProvider.PROVIDER_NAME); int aesKeyLength = Cipher.getMaxAllowedKeyLength("AES"); if (aesKeyLength <= 128) { log.warn( log.error("{} MessageCrypto initialization Failed {}", logCtx, e.getMessage());