public static void main(String[] args) throws Exception { Provider provider = Security.getProvider("SunJCE"); if (provider == null) { throw new RuntimeException("SunJCE provider not exist"); } // generate no-padding cipher with secret key Cipher c = Cipher.getInstance("DES/CBC/NoPadding", provider); KeyGenerator kgen = KeyGenerator.getInstance("DES", provider); SecretKey skey = kgen.generateKey(); // this is the improperly padded plaintext c.init(Cipher.ENCRYPT_MODE, skey); // encrypt plaintext byte[] cipher = c.doFinal(PLAIN_TEXT); AlgorithmParameters params = c.getParameters(); // generate cipher that enforces PKCS5 padding c = Cipher.getInstance("DES/CBC/PKCS5Padding", provider); c.init(Cipher.DECRYPT_MODE, skey, params); try { c.doFinal(cipher); throw new RuntimeException( "ERROR: Expected BadPaddingException not thrown"); } catch (BadPaddingException expected) { out.println("Expected BadPaddingException thrown"); } }
private void runGCMWithSeparateArray(int mode, byte[] AAD, byte[] text, int txtOffset, int lenght, int offset, AlgorithmParameters params) throws Exception { // first, generate the cipher text at an allocated buffer Cipher cipher = createCipher(mode, params); cipher.updateAAD(AAD); byte[] outputText = cipher.doFinal(text, txtOffset, lenght); // new cipher for encrypt operation Cipher anotherCipher = createCipher(mode, params); anotherCipher.updateAAD(AAD); // next, generate cipher text again at the same buffer of plain text int myoff = offset; int off = anotherCipher.update(text, txtOffset, lenght, text, myoff); anotherCipher.doFinal(text, myoff + off); // check if two resutls are equal if (!isEqual(text, myoff, outputText, 0, outputText.length)) { throw new RuntimeException("Two results not equal, mode:" + mode); } }
static void cbc_shortStream() throws Exception { Cipher c; AlgorithmParameters params; byte[] read = new byte[200]; System.out.println("Running cbc_shortStream"); // Encrypt 97 byte with AES/CBC/PKCS5Padding byte[] ct = encryptedText("CBC", 97); // Create stream with only 96 bytes of encrypted data CipherInputStream in = getStream("CBC", ct, 96); try { int size = in.read(read); in.close(); if (size != 80) { throw new RuntimeException("Fail: CipherInputStream.read() " + "returned " + size + ". Should have been 80"); } System.out.println(" Pass."); } catch (IOException e) { System.out.println(" Fail: " + e.getMessage()); throw new RuntimeException(e.getCause()); } }
public static void main(String[] args) throws Exception { PBEKeySpec ks = new PBEKeySpec(PASSWORD); for (int i = 0; i < PBE_ALGOS.length; i++) { String algo = PBE_ALGOS[i]; SecretKeyFactory skf = SecretKeyFactory.getInstance(algo); SecretKey key = skf.generateSecret(ks); Cipher c = Cipher.getInstance(algo, "SunJCE"); c.init(Cipher.ENCRYPT_MODE, key); c.doFinal(new byte[10]); // force the generation of parameters AlgorithmParameters params = c.getParameters(); if (!params.getAlgorithm().equalsIgnoreCase(algo)) { throw new Exception("expect: " + algo + ", but got: " + params.getAlgorithm()); } System.out.println(algo + "...done..."); } System.out.println("Test Passed"); }
/** * Run the test in case when AAD and text are placed in the same byte * array. */ private void doTestWithSameArrays(int offset, AlgorithmParameters params) throws Exception { // prepare buffers to test Cipher c = createCipher(Cipher.ENCRYPT_MODE, params); int outputLength = c.getOutputSize(textLength); int outputBufSize = AADLength + outputLength + offset * 2; byte[] AAD_and_text = Helper.generateBytes(outputBufSize); // do the test runGCMWithSameArray(Cipher.ENCRYPT_MODE, AAD_and_text, AADLength + offset, textLength, params); int tagLength = c.getParameters() .getParameterSpec(GCMParameterSpec.class).getTLen() / 8; runGCMWithSameArray(Cipher.DECRYPT_MODE, AAD_and_text, AADLength + offset, textLength + tagLength, params); }
private void doTestWithSameBuffer(int offset, AlgorithmParameters params) throws Exception { // calculate output length Cipher c = createCipher(Cipher.ENCRYPT_MODE, params); int outputLength = c.getOutputSize(textLength); // prepare byte buffer contained AAD and plain text int bufSize = AADLength + offset + outputLength; byte[] AAD_and_Text = Helper.generateBytes(bufSize); ByteBuffer AAD_and_Text_Buf = ByteBuffer.allocate(bufSize); AAD_and_Text_Buf.put(AAD_and_Text, 0, AAD_and_Text.length); // do test runGCMWithSameBuffer(Cipher.ENCRYPT_MODE, AAD_and_Text_Buf, offset, textLength, params); int tagLength = c.getParameters() .getParameterSpec(GCMParameterSpec.class).getTLen() / 8; AAD_and_Text_Buf.limit(AADLength + offset + textLength + tagLength); runGCMWithSameBuffer(Cipher.DECRYPT_MODE, AAD_and_Text_Buf, offset, textLength + tagLength, params); }
public AlgorithmParameters engineGetParameters() { if (engineParam == null && engineSpec != null) { try { engineParam = AlgorithmParameters.getInstance("IES", BouncyCastleProvider.PROVIDER_NAME); engineParam.init(engineSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } return engineParam; }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = AlgorithmParameters.getInstance("OAEP", BouncyCastleProvider.PROVIDER_NAME); engineParams.init(paramSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
private static boolean isAvailableCurve(int curveId) { String oid = idToOidMap.get(curveId); if (oid != null) { AlgorithmParameters params = null; try { params = JsseJce.getAlgorithmParameters("EC"); params.init(new ECGenParameterSpec(oid)); } catch (Exception e) { return false; } // cache the parameters idToParams.put(curveId, params); return true; } return false; }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (paramSpec != null) { try { engineParams = AlgorithmParameters.getInstance("PSS", BouncyCastleProvider.PROVIDER_NAME); engineParams.init(paramSpec); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
public void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { try { paramSpec = params.getParameterSpec(IESParameterSpec.class); } catch (Exception e) { throw new InvalidAlgorithmParameterException("cannot recognise parameters: " + e.toString()); } } engineParam = params; engineInit(opmode, key, paramSpec, random); }
@Override public boolean permits(AlgorithmParameters parameters) { String paramAlg = parameters.getAlgorithm(); if (!algorithm.equalsIgnoreCase(parameters.getAlgorithm())) { // Consider the impact of the algorithm aliases. Collection<String> aliases = AlgorithmDecomposer.getAliases(algorithm); if (!aliases.contains(paramAlg)) { return true; } } int keySize = KeyUtil.getKeySize(parameters); if (keySize == 0) { return false; } else if (keySize > 0) { return !((keySize < minSize) || (keySize > maxSize) || (prohibitedSize == keySize)); } // Otherwise, the key size is not accessible or determined. // Conservatively, please don't disable such keys. return true; }
private void runGCMWithSameArray(int mode, byte[] array, int txtOffset, int length, AlgorithmParameters params) throws Exception { // first, generate cipher text at an allocated buffer Cipher cipher = createCipher(mode, params); cipher.updateAAD(array, 0, AADLength); byte[] outputText = cipher.doFinal(array, txtOffset, length); // new cipher for encrypt operation Cipher anotherCipher = createCipher(mode, params); anotherCipher.updateAAD(array, 0, AADLength); // next, generate cipher text again at the same buffer of plain text int off = anotherCipher.update(array, txtOffset, length, array, txtOffset); anotherCipher.doFinal(array, txtOffset + off); // check if two results are equal or not if (!isEqual(array, txtOffset, outputText, 0, outputText.length)) { throw new RuntimeException( "Two results are not equal, mode:" + mode); } }
private void combination_12(List<byte[]> results, int mode, byte[] AAD, byte[] plainText, AlgorithmParameters params) throws Exception { // prepare ByteBuffer to test ByteBuffer buf = ByteBuffer.allocate(AAD.length); buf.put(AAD); buf.position(0); buf.limit(AAD.length); Cipher ci = createCipher(mode, params); ci.updateAAD(buf); // prepare an empty ByteBuffer ByteBuffer emptyBuf = ByteBuffer.allocate(0); emptyBuf.put(new byte[0]); ci.updateAAD(emptyBuf); byte[] part12_1 = new byte[ci.getOutputSize(plainText.length)]; int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0; int len12 = ci.update(plainText, 0, plainText.length - offset, part12_1, 0); int rest12 = ci.doFinal(plainText, plainText.length - offset, offset, part12_1, len12); byte[] outputText12 = new byte[len12 + rest12]; System.arraycopy(part12_1, 0, outputText12, 0, outputText12.length); results.add(outputText12); }
protected AlgorithmParameterSpec generateParameterSpec(ASN1ObjectIdentifier macOID, SecretKey encKey) throws CMSException { try { if (macOID.equals(PKCSObjectIdentifiers.RC2_CBC)) { byte[] iv = new byte[8]; random.nextBytes(iv); return new RC2ParameterSpec(encKey.getEncoded().length * 8, iv); } AlgorithmParameterGenerator pGen = helper.createAlgorithmParameterGenerator(macOID); AlgorithmParameters p = pGen.generateParameters(); return p.getParameterSpec(IvParameterSpec.class); } catch (GeneralSecurityException e) { return null; } }
private AlgorithmParameters getAlgorithmParameters(String algorithm) throws IOException { AlgorithmParameters algParams = null; // create PBE parameters from salt and iteration count PBEParameterSpec paramSpec = new PBEParameterSpec(getSalt(), iterationCount); try { algParams = AlgorithmParameters.getInstance(algorithm); algParams.init(paramSpec); } catch (Exception e) { throw new IOException("getAlgorithmParameters failed: " + e.getMessage(), e); } return algParams; }
private void combination_9(List<byte[]> results, int mode, byte[] AAD, byte[] plainText, AlgorithmParameters params) throws Exception { // prepare ByteBuffer to test ByteBuffer buf = ByteBuffer.allocate(AAD.length); buf.put(AAD); buf.position(0); buf.limit(AAD.length); // Get Cipher object and do the combination Cipher c = createCipher(mode, params); c.updateAAD(buf); byte[] part91 = c.update(plainText, 0, plainText.length); int part91_length = part91 == null ? 0 : part91.length; byte[] part92 = c.doFinal(); byte[] outputText9 = new byte[part91_length + part92.length]; // form result of the combination if (part91 != null) { System.arraycopy(part91, 0, outputText9, 0, part91_length); } System.arraycopy(part92, 0, outputText9, part91_length, part92.length); results.add(outputText9); }
/** * Returns the DSA parameters associated with this key, or null if the * parameters could not be parsed. */ public DSAParams getParams() { try { if (algid instanceof DSAParams) { return (DSAParams)algid; } else { DSAParameterSpec paramSpec; AlgorithmParameters algParams = algid.getParameters(); if (algParams == null) { return null; } paramSpec = algParams.getParameterSpec(DSAParameterSpec.class); return (DSAParams)paramSpec; } } catch (InvalidParameterSpecException e) { return null; } }
/** * Returns the ECPublicKey instance from its encoded raw bytes. * The first byte has the fixed value 0x04 indicating the uncompressed form. * Therefore, the byte array must be of form: [0x04, x coord of point (32 bytes), y coord of point (32 bytes)] * * @param publicKeyBytes The byte array representing the encoded raw bytes of the public key * @return The ECPublicKey instance */ public static ECPublicKey getPublicKey(byte[] publicKeyBytes) { // First we separate x and y of coordinates into separate variables byte[] x = new byte[32]; byte[] y = new byte[32]; System.arraycopy(publicKeyBytes, 1, x, 0, 32); System.arraycopy(publicKeyBytes, 33, y, 0, 32); try { KeyFactory kf = KeyFactory.getInstance("EC"); AlgorithmParameters parameters = AlgorithmParameters.getInstance("EC"); parameters.init(new ECGenParameterSpec("secp256r1")); ECParameterSpec ecParameterSpec = parameters.getParameterSpec(ECParameterSpec.class); ECPublicKeySpec ecPublicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), new BigInteger(y)), ecParameterSpec); ECPublicKey ecPublicKey = (ECPublicKey) kf.generatePublic(ecPublicKeySpec); return ecPublicKey; } catch (NoSuchAlgorithmException | InvalidParameterSpecException | InvalidKeySpecException e) { getLogger().error(e.getClass().getSimpleName() + " occurred when trying to get public key from raw bytes", e); return null; } }
private void combination_2(List<byte[]> results, int mode, byte[] AAD, byte[] plainText, AlgorithmParameters params) throws Exception { Cipher c = createCipher(mode, params); c.updateAAD(AAD); int t = 0; int offset = 0; if (plainText.length > ARRAY_OFFSET) { t = plainText.length - ARRAY_OFFSET; offset = ARRAY_OFFSET; } byte[] part21 = c.update(plainText, 0, t); byte[] part22 = new byte[c.getOutputSize(plainText.length)]; int len2 = c.doFinal(plainText, t, offset, part22, 0); int part21Length = part21 != null ? part21.length : 0; byte[] outputText2 = new byte[part21Length + len2]; if (part21 != null) { System.arraycopy(part21, 0, outputText2, 0, part21Length); } System.arraycopy(part22, 0, outputText2, part21Length, len2); results.add(outputText2); }
/** * {@inheritDoc} */ @Override public byte[] decryptBody(HttpServletRequest req) throws IOException { if(req.getMethod().equals("POST")) { InputStream bodyStream = req.getInputStream(); if(bodyStream != null) { // expect algorithParameters header AlgorithmParameters p = decodeAlgorithmParameters(req); // decrypt the body InputStream in = encryptor.decrypt(KeyProvider.ALIAS_SOLR, p, bodyStream); return IOUtils.toByteArray(in); } else { return null; } } else { return null; } }
protected Cipher createCipher(int mode, String algorithm, String provider, Key key, AlgorithmParameters params) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, InvalidAlgorithmParameterException { Cipher cipher = null; if (cipherProvider == null) { cipher = Cipher.getInstance(algorithm); } else { cipher = Cipher.getInstance(algorithm, provider); } cipher.init(mode, key, params); return cipher; }
@Override final public boolean permits(Set<CryptoPrimitive> primitives, String algorithm, Key key, AlgorithmParameters parameters) { if (algorithm == null || algorithm.length() == 0) { throw new IllegalArgumentException("No algorithm name specified"); } return checkConstraints(primitives, algorithm, key, parameters); }
protected void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { for (int i = 0; i != availableSpecs.length; i++) { try { paramSpec = params.getParameterSpec(availableSpecs[i]); break; } catch (Exception e) { // try again if possible } } if (paramSpec == null) { throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); } } engineInit(opmode, key, paramSpec, random); engineParams = params; }
private static String mapPBEParamsToAlgorithm(ObjectIdentifier algorithm, AlgorithmParameters algParams) throws NoSuchAlgorithmException { // Check for PBES2 algorithms if (algorithm.equals(pbes2_OID) && algParams != null) { return algParams.toString(); } return algorithm.toString(); }
protected void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { for (int i = 0; i != availableSpecs.length; i++) { try { paramSpec = params.getParameterSpec(availableSpecs[i]); break; } catch (Exception e) { continue; } } if (paramSpec == null) { throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); } } engineInit(opmode, key, paramSpec, random); engineParams = params; }
private void combination_4(List<byte[]> results, int mode, byte[] AAD, byte[] plainText, AlgorithmParameters params) throws Exception { Cipher ci = createCipher(mode, params); ci.updateAAD(AAD); byte[] part41 = new byte[ci.getOutputSize(plainText.length)]; int offset = plainText.length > ARRAY_OFFSET ? ARRAY_OFFSET : 0; int len = ci.update(plainText, 0, plainText.length - offset, part41, 0); int rest4 = ci.doFinal(plainText, plainText.length - offset, offset, part41, len); byte[] outputText4 = new byte[len + rest4]; System.arraycopy(part41, 0, outputText4, 0, outputText4.length); results.add(outputText4); }
@Override byte[] decrypt(byte[] key, byte[] data) { try { // Sun's impelemntation of GCM uses a custom algorithm name. We handle this odd (potentially incorrect) behavior here. AlgorithmParameters params = AlgorithmParameters.getInstance(isInstanceOfSunProvidedGCM ? "GCM" : "AES"); // Read the metadata. ByteArrayInputStream stream = new ByteArrayInputStream(data); DataInput in = new DataInputStream(stream); int metadataLength = WritableUtils.readVInt(in); byte[] metadata = new byte[metadataLength]; in.readFully(metadata); params.init(metadata); // Decrypt the remaining data. SecretKeySpec keySpec = new SecretKeySpec(key, AES); cipher.init(Cipher.DECRYPT_MODE, keySpec, params); byte[] ciphertext = new byte[stream.available()]; in.readFully(ciphertext); cipher.init(Cipher.DECRYPT_MODE, keySpec, params); return cipher.doFinal(ciphertext); } catch (NoSuchAlgorithmException | InvalidAlgorithmParameterException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | IOException e) { throw new EncryptionException(e); } }
protected AlgorithmParameters engineGetParameters() { if (engineParams == null) { if (ivParam != null) { String name = cipher.getUnderlyingCipher().getAlgorithmName(); if (name.indexOf('/') >= 0) { name = name.substring(0, name.indexOf('/')); } try { engineParams = AlgorithmParameters.getInstance(name, BouncyCastleProvider.PROVIDER_NAME); engineParams.init(ivParam.getIV()); } catch (Exception e) { throw new RuntimeException(e.toString()); } } } return engineParams; }
private AlgorithmParameters parseAlgParameters(ObjectIdentifier algorithm, DerInputStream in) throws IOException { AlgorithmParameters algParams = null; try { DerValue params; if (in.available() == 0) { params = null; } else { params = in.getDerValue(); if (params.tag == DerValue.tag_Null) { params = null; } } if (params != null) { if (algorithm.equals((Object)pbes2_OID)) { algParams = AlgorithmParameters.getInstance("PBES2"); } else { algParams = AlgorithmParameters.getInstance("PBE"); } algParams.init(params.toByteArray()); } } catch (Exception e) { throw new IOException("parseAlgParameters failed: " + e.getMessage(), e); } return algParams; }
/** * Encrypt plaintext. * @param str Plaintext to encrypt * @return Cipher text */ public String encrypt(final String str) { if (str == null) { throw new NullPointerException("Argument cannot be null"); } try { final SecureRandom random = new SecureRandom(); final byte[] salt = new byte[16]; random.nextBytes(salt); final SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); final KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 65536, 128); final SecretKey tmp = factory.generateSecret(spec); final SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); final Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret); final AlgorithmParameters params = cipher.getParameters(); final byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV(); final byte[] encryptedText = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8)); // concatenate salt + iv + ciphertext final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(salt); outputStream.write(iv); outputStream.write(encryptedText); // properly encode the complete cipher text return DatatypeConverter.printBase64Binary(outputStream.toByteArray()); } catch (final Exception exception) { throw new RuntimeException(exception.getMessage(), exception); } }
protected void engineInit( int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { AlgorithmParameterSpec paramSpec = null; if (params != null) { for (int i = 0; i != availableSpecs.length; i++) { try { paramSpec = params.getParameterSpec(availableSpecs[i]); break; } catch (Exception e) { // try next spec } } if (paramSpec == null) { throw new InvalidAlgorithmParameterException("can't handle parameter " + params.toString()); } } engineParams = params; engineInit(opmode, key, paramSpec, random); }
/** * Check the signature algorithm with the specified public key. * * @param key the public key to verify the CRL signature * @param crl the target CRL */ static void check(PublicKey key, AlgorithmId algorithmId) throws CertPathValidatorException { String sigAlgName = algorithmId.getName(); AlgorithmParameters sigAlgParams = algorithmId.getParameters(); if (!certPathDefaultConstraints.permits( SIGNATURE_PRIMITIVE_SET, sigAlgName, key, sigAlgParams)) { throw new CertPathValidatorException( "algorithm check failed: " + sigAlgName + " is disabled", null, null, -1, BasicReason.ALGORITHM_CONSTRAINED); } }
protected AlgorithmParameters engineGenerateParameters() { GOST3410ParametersGenerator pGen = new GOST3410ParametersGenerator(); if (random != null) { pGen.init(strength, 2, random); } else { pGen.init(strength, 2, new SecureRandom()); } GOST3410Parameters p = pGen.generateParameters(); AlgorithmParameters params; try { params = AlgorithmParameters.getInstance("GOST3410", BouncyCastleProvider.PROVIDER_NAME); params.init(new GOST3410ParameterSpec(new GOST3410PublicKeyParameterSetSpec(p.getP(), p.getQ(), p.getA()))); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } return params; }
@Override protected synchronized void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { reset(); nc.engineInit(opmode, key, params, random); }