public static InputStream createFor(MasterSecret masterSecret, File file) throws IOException { try { if (file.length() <= IV_LENGTH + MAC_LENGTH) { throw new IOException("File too short"); } verifyMac(masterSecret, file); FileInputStream fileStream = new FileInputStream(file); byte[] ivBytes = new byte[IV_LENGTH]; readFully(fileStream, ivBytes); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); IvParameterSpec iv = new IvParameterSpec(ivBytes); cipher.init(Cipher.DECRYPT_MODE, masterSecret.getEncryptionKey(), iv); return new CipherInputStreamWrapper(new LimitedInputStream(fileStream, file.length() - MAC_LENGTH - IV_LENGTH), cipher); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException e) { throw new AssertionError(e); } }
public Transform newTransform(String algorithm, TransformParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { TransformService spi; if (getProvider() == null) { spi = TransformService.getInstance(algorithm, "DOM"); } else { try { spi = TransformService.getInstance(algorithm, "DOM", getProvider()); } catch (NoSuchAlgorithmException nsae) { spi = TransformService.getInstance(algorithm, "DOM"); } } spi.init(params); return new DOMTransform(spi); }
@Override protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(genParamSpec instanceof DHGenParameterSpec)) { throw new InvalidAlgorithmParameterException("DH parameter generator requires a DHGenParameterSpec for initialisation"); } DHGenParameterSpec spec = (DHGenParameterSpec)genParamSpec; this.strength = spec.getPrimeSize(); this.l = spec.getExponentSize(); this.random = random; }
/** * Initializes this parameter generator with a set of * algorithm-specific parameter generation values. * * @param genParamSpec the set of algorithm-specific parameter * generation values * @param random the source of randomness * * @exception InvalidAlgorithmParameterException if the given parameter * generation values are inappropriate for this parameter generator */ @Override protected void engineInit(AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { if (!(genParamSpec instanceof DSAGenParameterSpec)) { throw new InvalidAlgorithmParameterException("Invalid parameter"); } DSAGenParameterSpec dsaGenParams = (DSAGenParameterSpec)genParamSpec; // directly initialize using the already validated values this.valueL = dsaGenParams.getPrimePLength(); this.valueN = dsaGenParams.getSubprimeQLength(); this.seedLen = dsaGenParams.getSeedLength(); this.random = random; }
public static String encrypt(String str) { if (str == null) return null; Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] encrypted = cipher.doFinal(str.getBytes("UTF-8")); String Str = new String(Base64.encodeBase64(encrypted)); return Str; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
/** * Create a new key in the Keystore */ private void createNewKey(){ try { final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore); keyStore.load(null); final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore); // Build one key to be used for encrypting and decrypting the file keyGenerator.init( new KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) .build()); keyGenerator.generateKey(); Log.i(TAG, "Key created in Keystore"); }catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException kS){ Log.e(TAG, kS.getMessage()); } }
public byte[] encrypt(int version, byte[] data) { CryptVersion cryptVersion = cryptVersion(version); try { int cryptedLength = cryptVersion.encryptedLength.apply(data.length); byte[] result = new byte[cryptedLength + cryptVersion.saltLength + 1]; result[0] = toSignedByte(version); byte[] random = urandomBytes(cryptVersion.saltLength); IvParameterSpec iv_spec = new IvParameterSpec(random); System.arraycopy(random, 0, result, 1, cryptVersion.saltLength); Cipher cipher = cipher(cryptVersion.cipher); cipher.init(Cipher.ENCRYPT_MODE, cryptVersion.key, iv_spec); int len = cipher.doFinal(data, 0, data.length, result, cryptVersion.saltLength + 1); if (len < cryptedLength) LOG.info("len was " + len + " instead of " + cryptedLength); return result; } catch (ShortBufferException | IllegalBlockSizeException | BadPaddingException | InvalidAlgorithmParameterException | InvalidKeyException e) { throw new RuntimeException("JCE exception caught while encrypting with version " + version, e); } }
public static String decrypt(String str) { if (str == null) return null; Cipher cipher; try { cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(ips.getBytes("UTF-8"))); byte[] byteStr = Base64.decodeBase64(str.getBytes()); return new String(cipher.doFinal(byteStr), "UTF-8"); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException e) { e.printStackTrace(); } return null; }
ValidatorParams(PKIXParameters params) throws InvalidAlgorithmParameterException { if (params instanceof PKIXExtendedParameters) { timestamp = ((PKIXExtendedParameters) params).getTimestamp(); variant = ((PKIXExtendedParameters) params).getVariant(); } this.anchors = params.getTrustAnchors(); // Make sure that none of the trust anchors include name constraints // (not supported). for (TrustAnchor anchor : this.anchors) { if (anchor.getNameConstraints() != null) { throw new InvalidAlgorithmParameterException ("name constraints in trust anchor not supported"); } } this.params = params; }
@BeforeClass(enabled = false) public void registerUser() throws CipherException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException { dsp = createNewMember(2, 100) .thenApply(papyrusMember -> { allTransactionsMinedAsync(asList(papyrusMember.refillTransaction, papyrusMember.mintTransaction)); return papyrusMember; }).join(); dspRegistrar = createNewMember(2, 100) .thenApply(papyrusMember -> { allTransactionsMinedAsync(asList(papyrusMember.refillTransaction, papyrusMember.mintTransaction)); return papyrusMember; }).join(); dao = loadDaoContract(dsp.transactionManager); daoRegistrar = loadDaoContract(dspRegistrar.transactionManager); token = asCf(dao.token()).thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(), dsp.transactionManager)).join(); tokenRegistrar = asCf(daoRegistrar.token()) .thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(), dspRegistrar.transactionManager) ).join(); dspRegistry = asCf(daoRegistrar.dspRegistry()) .thenApply(dspRegistryAddress -> loadDspRegistry(dspRegistryAddress.toString(), dsp.transactionManager)) .join(); initDepositContract(); }
@TargetApi(Build.VERSION_CODES.M) public SecretKey getSymmetricKey(String alias) throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, CertificateException, KeyStoreException, UnrecoverableEntryException { ESLog.v("%s=>getSymmetricKey(%s)", getClass().getSimpleName(), alias); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { KeyStore ks = KeyStore.getInstance(KEYSTORE_PROVIDER); ks.load(null); Key key = ks.getKey(alias, null); if (key != null) { ESLog.i("SecretKey found in KeyStore."); return (SecretKey) key; } ESLog.w("SecretKey not found in KeyStore."); return null; } UnsupportedOperationException unsupportedOperationException = new UnsupportedOperationException(); ESLog.wtf("Unsupported operation. This code should be called only from M onwards.", unsupportedOperationException.getCause()); throw unsupportedOperationException; }
/** * Sets the {@code Set} of most-trusted CAs. * <p> * Note that the {@code Set} is copied to protect against * subsequent modifications. * * @param trustAnchors a {@code Set} of {@code TrustAnchor}s * @throws InvalidAlgorithmParameterException if the specified * {@code Set} is empty {@code (trustAnchors.isEmpty() == true)} * @throws NullPointerException if the specified {@code Set} is * {@code null} * @throws ClassCastException if any of the elements in the set * are not of type {@code java.security.cert.TrustAnchor} * * @see #getTrustAnchors */ public void setTrustAnchors(Set<TrustAnchor> trustAnchors) throws InvalidAlgorithmParameterException { if (trustAnchors == null) { throw new NullPointerException("the trustAnchors parameters must" + " be non-null"); } if (trustAnchors.isEmpty()) { throw new InvalidAlgorithmParameterException("the trustAnchors " + "parameter must be non-empty"); } for (Iterator<TrustAnchor> i = trustAnchors.iterator(); i.hasNext(); ) { if (!(i.next() instanceof TrustAnchor)) { throw new ClassCastException("all elements of set must be " + "of type java.security.cert.TrustAnchor"); } } this.unmodTrustAnchors = Collections.unmodifiableSet (new HashSet<>(trustAnchors)); }
private void checkParams(PKIXBuilderParameters params) throws InvalidAlgorithmParameterException { CertSelector sel = targetCertConstraints(); if (!(sel instanceof X509CertSelector)) { throw new InvalidAlgorithmParameterException("the " + "targetCertConstraints parameter must be an " + "X509CertSelector"); } if (params instanceof SunCertPathBuilderParameters) { buildForward = ((SunCertPathBuilderParameters)params).getBuildForward(); } this.params = params; this.targetSubject = getTargetSubject( certStores(), (X509CertSelector)targetCertConstraints()); }
@BeforeClass(enabled = false) public void registerUser() throws CipherException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException, IOException { auditor = createNewMember(2, 100) .thenApply(papyrusMember -> { allTransactionsMinedAsync(asList(papyrusMember.refillTransaction, papyrusMember.mintTransaction)); return papyrusMember; }).join(); auditorRegistrar = createNewMember(2, 100) .thenApply(papyrusMember -> { allTransactionsMinedAsync(asList(papyrusMember.refillTransaction, papyrusMember.mintTransaction)); return papyrusMember; }).join(); dao = loadDaoContract(auditor.transactionManager); daoRegistrar = loadDaoContract(auditorRegistrar.transactionManager); token = asCf(dao.token()).thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(), auditor.transactionManager)).join(); tokenRegistrar = asCf(daoRegistrar.token()) .thenApply(tokenAddress -> loadTokenContract(tokenAddress.toString(), auditorRegistrar.transactionManager) ).join(); auditorRegistry = asCf(daoRegistrar.auditorRegistry()) .thenApply(auditorRegistryAddress -> loadAuditorRegistry(auditorRegistryAddress.toString(), auditor.transactionManager)) .join(); initDepositContract(); }
private void actionMenuNotRegistered(final int choice) throws ClassNotFoundException, IOException, FileNotFoundException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, InvalidParameterSpecException { switch (choice) { case 1: signIn(); break; case 2: signUp(); break; case 3: // close with condition in while break; default: System.out.println("Unknow choice " + choice + "\n"); break; } }
private static void testDSAGenParameterSpec(DataTuple dataTuple) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidParameterSpecException, InvalidAlgorithmParameterException { System.out.printf("Test case: primePLen=%d, " + "subprimeQLen=%d%n", dataTuple.primePLen, dataTuple.subprimeQLen); AlgorithmParameterGenerator apg = AlgorithmParameterGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME); DSAGenParameterSpec genParamSpec = createGenParameterSpec(dataTuple); // genParamSpec will be null if IllegalAE is thrown when expected. if (genParamSpec == null) { return; } try { apg.init(genParamSpec, null); AlgorithmParameters param = apg.generateParameters(); checkParam(param, genParamSpec); System.out.println("Test case passed"); } catch (InvalidParameterException ipe) { throw new RuntimeException("Test case failed.", ipe); } }
public static KeyPair generateRSAKeypair(int keysize, BigInteger publicExponent, SecureRandom random) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { BigInteger tmpPublicExponent = publicExponent; if (tmpPublicExponent == null) { tmpPublicExponent = RSAKeyGenParameterSpec.F4; } AlgorithmParameterSpec params = new RSAKeyGenParameterSpec(keysize, tmpPublicExponent); KeyPairGenerator kpGen = getKeyPairGenerator("RSA"); synchronized (kpGen) { if (random == null) { kpGen.initialize(params); } else { kpGen.initialize(params, random); } return kpGen.generateKeyPair(); } }
@Test public void testKeyPairGeneratorEccInitializeWithKeySize() throws NoSuchProviderException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { /* try initializing KPG for all supported key sizes */ for (int i = 0; i < enabledKeySizes.size(); i++) { KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "wolfJCE"); kpg.initialize(enabledKeySizes.get(i)); /* bad key size should fail */ try { kpg.initialize(9999); } catch (WolfCryptException e) {} } }
public void initialize( int strength, SecureRandom random) { this.strength = strength; this.random = random; if (ecParams != null) { try { initialize((ECGenParameterSpec)ecParams, random); } catch (InvalidAlgorithmParameterException e) { throw new InvalidParameterException("key size not configurable."); } } else { throw new InvalidParameterException("unknown key size."); } }
public WalletClient(final File f, final char[] userPassword) throws IOException, FileNotFoundException, ClassNotFoundException, InvalidKeySpecException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, InstantiationException { super(f, userPassword); acceptedTransactionsList = new ArrayList<>(); unacceptedTransactionsList = new ArrayList<>(); }
@Override protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for CAST5 parameter generation."); }
public GameServerTable() throws SQLException, NoSuchAlgorithmException, InvalidAlgorithmParameterException { loadServerNames(); _log.info("Loaded "+_serverNames.size()+" server names"); loadRegisteredGameServers(); _log.info("Loaded "+_gameServerTable.size()+" registered Game Servers"); loadRSAKeys(); _log.info("Cached "+_keyPairs.length+" RSA keys for Game Server communication."); }
/** * Creates a <code>DOMDigestMethod</code> from an element. This constructor * invokes the abstract {@link #unmarshalParams unmarshalParams} method to * unmarshal any algorithm-specific input parameters. * * @param dmElem a DigestMethod element */ DOMDigestMethod(Element dmElem) throws MarshalException { Element paramsElem = DOMUtils.getFirstChildElement(dmElem); if (paramsElem != null) { params = unmarshalParams(paramsElem); } try { checkParams(params); } catch (InvalidAlgorithmParameterException iape) { throw new MarshalException(iape); } }
@Override protected void engineInit( AlgorithmParameterSpec genParamSpec, SecureRandom random) throws InvalidAlgorithmParameterException { if (genParamSpec instanceof RC2ParameterSpec) { spec = (RC2ParameterSpec)genParamSpec; return; } throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for RC2 parameter generation."); }
/** * @inheritDoc */ protected void engineSetParameter(AlgorithmParameterSpec params) throws XMLSignatureException { try { this.signatureAlgorithm.setParameter(params); } catch (InvalidAlgorithmParameterException ex) { throw new XMLSignatureException("empty", ex); } }
public static String encryptAES256PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
public static String decryptAES256PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.DECRYPT_MODE, generateKeyAES256(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return new String(cipher.doFinal(Base64.decode(src))); }
private static SecretKey generateKeyAES256(String key) throws InvalidAlgorithmParameterException, UnsupportedEncodingException { if (key.getBytes().length != 32){ throw new InvalidAlgorithmParameterException("Key length must be 32 bytes"); } return new SecretKeySpec(key.getBytes(TEXT_ENCODING), KEY_ENCODING); }
public static String decryptAES128PKCS5Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, IOException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.DECRYPT_MODE, generateKeyAES128(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return new String(cipher.doFinal(Base64.decode(src))); }
public static String encryptAES128PKCS7Padding(String key, String src) throws NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException, InvalidAlgorithmParameterException, InvalidKeyException { Cipher cipher = Cipher.getInstance(ALGORITHM_ENCODING); cipher.init(Cipher.ENCRYPT_MODE, generateKeyAES128(key), new IvParameterSpec(new byte[cipher.getBlockSize()])); return Base64.encodeBytes(cipher.doFinal(src.getBytes())); }
private static void checkParam(AlgorithmParameters param, DSAGenParameterSpec genParam) throws InvalidParameterSpecException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { String algorithm = param.getAlgorithm(); if (!algorithm.equalsIgnoreCase(ALGORITHM_NAME)) { throw new RuntimeException( "Unexpected type of parameters: " + algorithm); } DSAParameterSpec spec = param.getParameterSpec(DSAParameterSpec.class); int valueL = spec.getP().bitLength(); int strengthP = genParam.getPrimePLength(); if (strengthP != valueL) { System.out.printf("P: Expected %d but actual %d%n", strengthP, valueL); throw new RuntimeException("Wrong P strength"); } int valueN = spec.getQ().bitLength(); int strengthQ = genParam.getSubprimeQLength(); if (strengthQ != valueN) { System.out.printf("Q: Expected %d but actual %d%n", strengthQ, valueN); throw new RuntimeException("Wrong Q strength"); } if (genParam.getSubprimeQLength() != genParam.getSeedLength()) { System.out.println("Defaut seed length should be the same as Q."); throw new RuntimeException("Wrong seed length"); } KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM_NAME, PROVIDER_NAME); keyGen.initialize(spec); }
@Test public void notEqualsIsCorrect() throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { SecureString secureString1 = new SecureString(KEY, "dummy test"); SecureString secureString2 = new SecureString(KEY, "different dummy test"); assertFalse(secureString1.isEqualTo(secureString2)); }
@Test public void isEmptyIsCorrect() throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException { SecureString secureString1 = new SecureString(KEY, ""); assertTrue(secureString1.isEmpty()); }
CipherGenerator(String algo) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, NoSuchPaddingException, InvalidKeySpecException { // Do initialization byte[] salt = TestUtilities.generateBytes(IV_LENGTH); int iterCnt = 6; SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]); SecretKey key = skf .generateSecret(new PBEKeySpec(PASSWD.toCharArray())); AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iterCnt); initCiphers(algo, key, aps); }
private byte[] encrypt(byte[] plainText, byte[] key, byte[] initialVector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Cipher cipher = Cipher.getInstance(cipherTransformation); SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm); IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); plainText = cipher.doFinal(plainText); return plainText; }
protected void engineInit( int opmode, Key key, SecureRandom random) throws InvalidKeyException { try { engineInit(opmode, key, (AlgorithmParameterSpec)null, random); } catch (InvalidAlgorithmParameterException e) { throw new InvalidKeyException(e.getMessage()); } }
@Override protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { try { engineInit(opmode, key, params.getParameterSpec(AlgorithmParameterSpec.class), random); } catch (InvalidParameterSpecException e) { throw new InvalidAlgorithmParameterException(e); } }
private void wolfCryptSetIV(AlgorithmParameterSpec spec, SecureRandom random) throws InvalidAlgorithmParameterException { /* store AlgorithmParameterSpec for class reset */ this.storedSpec = spec; /* RSA doesn't need an IV */ if (this.cipherType == CipherType.WC_RSA) return; /* store IV, or generate random IV if not available */ if (spec == null) { this.iv = new byte[this.blockSize]; if (random != null) { random.nextBytes(this.iv); } else { SecureRandom rand = new SecureRandom(); rand.nextBytes(this.iv); } } else { if (!(spec instanceof IvParameterSpec)) { throw new InvalidAlgorithmParameterException( "AlgorithmParameterSpec must be of type IvParameterSpec"); } IvParameterSpec ivSpec = (IvParameterSpec)spec; /* IV should be of block size length */ if (ivSpec.getIV().length != this.blockSize) { throw new InvalidAlgorithmParameterException( "Bad IV length (" + ivSpec.getIV().length + "), must be " + blockSize + " bytes long"); } this.iv = ivSpec.getIV(); } }