public static void main(String[] args) throws InvalidKeyException, DataLengthException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, IllegalStateException, InvalidCipherTextException { try { UIManager.setLookAndFeel("com.pagosoft.plaf.PgsLookAndFeel"); } catch (Exception e) { ; } GUI MainGUI = new GUI(); MainGUI.ConstructGUI(); // String CT = TextEncrypt.CBCDecrypt("8mjf2sqScPChi5lJQut6U5phB6IW8ze90WdqDm+ulLU1NWI2ODZlYzVmMjYxYTA5", "secret", 256, 0, "Q"); // // System.out.println(CT); }
public static String CBCEncrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { String res = ""; byte[] plain = loadFile(inFile); Encryptor enc = new Encryptor(); enc.setParameters(KeySize, alg); enc.setEncParameters(alg, pwd, KeySize, mode); byte[] bytesRes = enc.CBCEncrypt(plain, alg); save2File(inFile + ".enc", bytesRes); res = "Done! file contents encrypted and saved to a corresponding enc file!"; return res; }
public static String CBCDecrypt(int alg, int KeySize, String inFile, String pwd, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException, IOException { String res = ""; if (checkFile(inFile.substring(0, inFile.lastIndexOf(".")))) { res = "A file with the same name already exists! Rename or move it to avoid losing your data!"; return res; } byte[] Encrypted = loadFile(inFile); Encryptor enc = new Encryptor(); enc.setParameters(KeySize, alg); enc.setDecParameters(Encrypted, alg, pwd, KeySize, mode); byte[] bytesRes = enc.CBCDecrypt(Encrypted, alg); save2File(inFile.substring(0, inFile.lastIndexOf(".")), bytesRes); res = "Done! file contents decrypted and saved to the specified directory!"; return res; }
/** * return the number of pad bytes present in the block. */ public int padCount(byte[] in) throws InvalidCipherTextException { int count = in[in.length - 1] & 0xff; if (count > in.length || count == 0) { throw new InvalidCipherTextException("pad block corrupted"); } for (int i = 1; i <= count; i++) { if (in[in.length - i] != count) { throw new InvalidCipherTextException("pad block corrupted"); } } return count; }
public GenericKey generateUnwrappedKey(AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey) throws OperatorException { AsymmetricBlockCipher keyCipher = createAsymmetricUnwrapper(this.getAlgorithmIdentifier().getAlgorithm()); keyCipher.init(false, privateKey); try { byte[] key = keyCipher.processBlock(encryptedKey, 0, encryptedKey.length); if (encryptedKeyAlgorithm.getAlgorithm().equals(PKCSObjectIdentifiers.des_EDE3_CBC)) { return new GenericKey(encryptedKeyAlgorithm, key); } else { return new GenericKey(encryptedKeyAlgorithm, key); } } catch (InvalidCipherTextException e) { throw new OperatorException("unable to recover secret key: " + e.getMessage(), e); } }
public byte[] processBlock(byte[] in, int inOff, int len) throws InvalidCipherTextException { byte[] tmp = new byte[len]; System.arraycopy(in, inOff, tmp, 0, len); if (forEncryption) { return encrypt(tmp, pubKey); } else { return decrypt(tmp, privKey); } }
public byte[] decryptPreMasterSecret(byte[] encryptedPreMasterSecret) throws IOException { PKCS1Encoding encoding = new PKCS1Encoding(new RSABlindedEngine()); encoding.init(false, new ParametersWithRandom(this.privateKey, context.getSecureRandom())); try { return encoding.processBlock(encryptedPreMasterSecret, 0, encryptedPreMasterSecret.length); } catch (InvalidCipherTextException e) { throw new TlsFatalAlert(AlertDescription.illegal_parameter); } }
/** * return the number of pad bytes present in the block. */ public int padCount(byte[] in) throws InvalidCipherTextException { int count = in.length; while (count > 0) { if (in[count - 1] != 0) { break; } count--; } return in.length - count; }
/** * return the number of pad bytes present in the block. */ public int padCount(byte[] in) throws InvalidCipherTextException { int count = in.length - 1; while (count > 0 && in[count] == 0) { count--; } if (in[count] != (byte)0x80) { throw new InvalidCipherTextException("pad block corrupted"); } return in.length - count; }
protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { if (inputLen != 0) { buffer.write(input, inputOffset, inputLen); } try { byte[] buf = buffer.toByteArray(); buffer.reset(); return cipher.processBlock(buf, 0, buf.length); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } }
protected byte[] engineDoFinal( byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException { cipher.processBytes(input, inputOffset, inputLen); try { return cipher.doFinal(); } catch (InvalidCipherTextException e) { throw new BadPaddingException(e.getMessage()); } }
protected KeyParameter extractSecretKey(AlgorithmIdentifier keyEncryptionAlgorithm, AlgorithmIdentifier contentEncryptionAlgorithm, byte[] derivedKey, byte[] encryptedContentEncryptionKey) throws CMSException { Wrapper keyEncryptionCipher = EnvelopedDataHelper.createRFC3211Wrapper(keyEncryptionAlgorithm.getAlgorithm()); keyEncryptionCipher.init(false, new ParametersWithIV(new KeyParameter(derivedKey), ASN1OctetString.getInstance(keyEncryptionAlgorithm.getParameters()).getOctets())); try { return new KeyParameter(keyEncryptionCipher.unwrap(encryptedContentEncryptionKey, 0, encryptedContentEncryptionKey.length)); } catch (InvalidCipherTextException e) { throw new CMSException("unable to unwrap key: " + e.getMessage(), e); } }
public static byte[] aesEncrypt(byte[] plaintext, byte[] myPrivateKey, byte[] theirPublicKey, byte[] nonce) { try { byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); for (int i = 0; i < 32; i++) { dhSharedSecret[i] ^= nonce[i]; } byte[] key = sha256().digest(dhSharedSecret); byte[] iv = new byte[16]; secureRandom.get().nextBytes(iv); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(true, ivAndKey); byte[] output = new byte[aes.getOutputSize(plaintext.length)]; int ciphertextLength = aes.processBytes(plaintext, 0, plaintext.length, output, 0); ciphertextLength += aes.doFinal(output, ciphertextLength); byte[] result = new byte[iv.length + ciphertextLength]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(output, 0, result, iv.length, ciphertextLength); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
/** * Finishes and voids this cipher output stream. * Calling this method causes all remaining buffered bytes to get written * and padded if necessary. * Afterwards, this stream will behave as if it had been closed, although * the decorated stream may still be open. * * @throws IOException If {@code out} or {@code cipher} aren't properly * initialized, an I/O error occurs or the cipher * text is invalid because some required padding is missing. */ public void finish() throws IOException { final BufferedBlockCipher cipher = this.cipher; if (null == cipher) return; this.cipher = null; int cipherLen = cipher.getOutputSize(0); byte[] cipherOut = this.buffer; if (cipherLen > cipherOut.length) this.buffer = cipherOut = new byte[cipherLen]; try { cipherLen = cipher.doFinal(cipherOut, 0); } catch (InvalidCipherTextException ex) { throw new IOException(ex); } out.write(cipherOut, 0, cipherLen); }
public static byte[] aesDecrypt(byte[] ivCiphertext, byte[] myPrivateKey, byte theirPublicKey[]) { try { if (ivCiphertext.length < 16 || ivCiphertext.length % 16 != 0) { throw new InvalidCipherTextException("invalid ciphertext"); } byte[] iv = Arrays.copyOfRange(ivCiphertext, 0, 16); byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, 16, ivCiphertext.length); byte[] dhSharedSecret = new byte[32]; Curve25519.curve(dhSharedSecret, myPrivateKey, theirPublicKey); byte[] key = sha256().digest(dhSharedSecret); PaddedBufferedBlockCipher aes = new PaddedBufferedBlockCipher(new CBCBlockCipher( new AESEngine())); CipherParameters ivAndKey = new ParametersWithIV(new KeyParameter(key), iv); aes.init(false, ivAndKey); byte[] output = new byte[aes.getOutputSize(ciphertext.length)]; int plaintextLength = aes.processBytes(ciphertext, 0, ciphertext.length, output, 0); plaintextLength += aes.doFinal(output, plaintextLength); byte[] result = new byte[plaintextLength]; System.arraycopy(output, 0, result, 0, result.length); return result; } catch (InvalidCipherTextException e) { throw new RuntimeException(e.getMessage(), e); } }
protected byte[] encryptSessionInfo(int encAlgorithm, byte[] key, byte[] sessionInfo) throws PGPException { try { BlockCipher engine = BcImplProvider.createBlockCipher(encAlgorithm); BufferedBlockCipher cipher = BcUtil.createSymmetricKeyWrapper(true, engine, key, new byte[engine.getBlockSize()]); byte[] out = new byte[sessionInfo.length]; int len = cipher.processBytes(sessionInfo, 0, sessionInfo.length, out, 0); len += cipher.doFinal(out, len); return out; } catch (InvalidCipherTextException e) { throw new PGPException("encryption failed: " + e.getMessage(), e); } }
/** * Process a packet of data for either CCM decryption or encryption. * * @param in data for processing. * @param inOff offset at which data starts in the input array. * @param inLen length of the data in the input array. * @return a byte array containing the processed input.. * @throws IllegalStateException if the cipher is not appropriately set up. * @throws InvalidCipherTextException if the input data is truncated or the mac check fails. */ public byte[] processPacket(byte[] in, int inOff, int inLen) throws IllegalStateException, InvalidCipherTextException { byte[] output; if (forEncryption) { output = new byte[inLen + macSize]; } else { if (inLen < macSize) { throw new InvalidCipherTextException("data too short"); } output = new byte[inLen - macSize]; } processPacket(in, inOff, inLen, output, 0); return output; }
protected static byte[][] encaps(CipherParameters publicKey, Element[] x) { try { KeyEncapsulationMechanism kem = new FEKEMEngine(); kem.init(true, new FEEncryptionParameters( (FEPublicKeyParameters) publicKey, x)); byte[] ciphertext = kem.processBlock(new byte[0], 0, 0); byte[] key = Arrays.copyOfRange(ciphertext, 0, kem.getKeyBlockSize()); byte[] ct = Arrays.copyOfRange(ciphertext, kem.getKeyBlockSize(), ciphertext.length); return new byte[][] { key, ct }; } catch (InvalidCipherTextException e) { e.printStackTrace(); } return null; }
public byte[] decrypt(Recipient whom) throws CoseException, InvalidCipherTextException { byte[] rgbKey = null; AlgorithmID alg = AlgorithmID.FromCBOR(findAttribute(HeaderKeys.Algorithm)); for (Recipient r : recipientList) { if (r == whom) { rgbKey = r.decrypt(alg, whom); break; } else if (r.recipientList.size() > 0) { rgbKey = r.decrypt(alg, whom); if (rgbKey != null) break; } } if (rgbKey == null) throw new CoseException("Recipient key not found"); return super.decryptWithKey(rgbKey); }
@Test public void roundTripDetached() throws CoseException, IllegalStateException, InvalidCipherTextException { Encrypt0Message msg = new Encrypt0Message(true, false); msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED); msg.addAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attribute.UNPROTECTED); msg.SetContent(rgbContent); msg.encrypt(rgbKey128); byte[] content = msg.getEncryptedContent(); byte[] rgb = msg.EncodeToBytes(); msg = (Encrypt0Message) Message.DecodeFromBytes(rgb); msg.setEncryptedContent(content); msg.decrypt(rgbKey128); }
private void doEax(byte[] key, byte[] iv, byte[] pt, byte[] aad, int tagLength, byte[] expected) throws InvalidCipherTextException { EAXBlockCipher c = new EAXBlockCipher(new SerpentEngine()); c.init(true, new AEADParameters(new KeyParameter(key), tagLength, iv, aad)); byte[] out = new byte[expected.length]; int len = c.processBytes(pt, 0, pt.length, out, 0); c.doFinal(out, len); if (!Arrays.areEqual(expected, out)) { fail("EAX test failed"); } }
private void heapIssueTest() { byte[] key = Hex.decode("d305ef52a6b9e72c810b821261d2d678"); byte[] ciphertext = Hex.decode("d2b2906d209a46261d8f6794eca3179d"); Wrapper aes = new AESWrapPadEngine(); aes.init(false, new KeyParameter(key)); try { byte[] result = aes.unwrap(ciphertext, 0, ciphertext.length); fail("incorrect pad not detected"); } catch (InvalidCipherTextException e) { // ignore } }
private void checkVectors( int count, CCMBlockCipher ccm, byte[] k, int macSize, byte[] n, byte[] a, byte[] p, byte[] t, byte[] c) throws InvalidCipherTextException { byte[] fa = new byte[a.length / 2]; byte[] la = new byte[a.length - (a.length / 2)]; System.arraycopy(a, 0, fa, 0, fa.length); System.arraycopy(a, fa.length, la, 0, la.length); checkVectors(count, ccm, "all initial associated data", k, macSize, n, a, null, p, t, c); checkVectors(count, ccm, "subsequent associated data", k, macSize, n, null, a, p, t, c); checkVectors(count, ccm, "split associated data", k, macSize, n, fa, la, p, t, c); checkVectors(count, ccm, "reuse key", null, macSize, n, fa, la, p, t, c); }
private void basicTrial(BufferedBlockCipher cipher, KeyParameter param) throws InvalidCipherTextException { cipher.init(true, param); byte[] out = new byte[input.length]; int len1 = cipher.processBytes(input, 0, input.length, out, 0); cipher.doFinal(out, len1); if (!areEqual(out, output)) { fail("failed - " + "expected " + new String(Hex.encode(output)) + " got " + new String(Hex.encode(out))); } }
@Test public void noContentForDecrypt() throws CoseException, IllegalStateException, InvalidCipherTextException { Encrypt0Message msg = new Encrypt0Message(true, false); thrown.expect(CoseException.class); thrown.expectMessage("No Encrypted Content Specified"); msg.addAttribute(HeaderKeys.Algorithm, AlgorithmID.AES_GCM_128.AsCBOR(), Attribute.PROTECTED); msg.addAttribute(HeaderKeys.IV, CBORObject.FromObject(rgbIV96), Attribute.UNPROTECTED); msg.SetContent(rgbContent); msg.encrypt(rgbKey128); byte[] rgb = msg.EncodeToBytes(); msg = (Encrypt0Message) Message.DecodeFromBytes(rgb); msg.decrypt(rgbKey128); }
private void runTestCase(String[] testVector, int macLength) throws InvalidCipherTextException { int pos = 0; String testName = testVector[pos++]; byte[] K = Hex.decode(testVector[pos++]); byte[] P = Hex.decode(testVector[pos++]); byte[] A = Hex.decode(testVector[pos++]); byte[] IV = Hex.decode(testVector[pos++]); byte[] C = Hex.decode(testVector[pos++]); // For short MAC, take leading bytes byte[] t = Hex.decode(testVector[pos++]); byte[] T = new byte[macLength]; System.arraycopy(t, 0, T, 0, T.length); // Default multiplier runTestCase(null, null, testName, K, IV, A, P, C, T); runTestCase(new BasicGCMMultiplier(), new BasicGCMMultiplier(), testName, K, IV, A, P, C, T); runTestCase(new Tables8kGCMMultiplier(), new Tables8kGCMMultiplier(), testName, K, IV, A, P, C, T); runTestCase(new Tables64kGCMMultiplier(), new Tables64kGCMMultiplier(), testName, K, IV, A, P, C, T); }
private void checkVectors( int count, byte[] k, int macSize, byte[] n, byte[] a, byte[] p, byte[] t, byte[] c) throws InvalidCipherTextException { byte[] fa = new byte[a.length / 2]; byte[] la = new byte[a.length - (a.length / 2)]; System.arraycopy(a, 0, fa, 0, fa.length); System.arraycopy(a, fa.length, la, 0, la.length); checkVectors(count, "all initial associated data", k, macSize, n, a, null, p, t, c); checkVectors(count, "subsequent associated data", k, macSize, n, null, a, p, t, c); checkVectors(count, "split associated data", k, macSize, n, fa, la, p, t, c); }
private void testReset(StreamCipher cipher1, StreamCipher cipher2, CipherParameters params) throws InvalidCipherTextException { cipher1.init(true, params); byte[] plaintext = new byte[1023]; byte[] ciphertext = new byte[plaintext.length]; // Establish baseline answer cipher1.processBytes(plaintext, 0, plaintext.length, ciphertext, 0); // Test encryption resets checkReset(cipher1, params, true, plaintext, ciphertext); // Test decryption resets with fresh instance cipher2.init(false, params); checkReset(cipher2, params, false, ciphertext, plaintext); }
private byte[] processCipher( BufferedBlockCipher cipher, byte[] input ) { byte[] output = new byte[cipher.getOutputSize( input.length )]; int cursor = cipher.processBytes( input, 0, input.length, output, 0 ); try { // cursor += cipher.doFinal( output, cursor ); if ( cursor != output.length ) { throw new InvalidCipherTextException( "Output size did not match cursor" ); } } catch ( InvalidCipherTextException e ) { LOGGER.error( "Could not encrypt/decrypt to/from cipher-text", e ); return null; } return output; }
public static String CBCEncrypt(String plain, String pwd, int KeySize, int alg, String mode) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, DataLengthException, IllegalStateException, InvalidCipherTextException { String res = ""; Encryptor enc = new Encryptor(); enc.setParameters(KeySize, alg); enc.setEncParameters(alg, pwd, KeySize, mode); byte[] bytesRes = enc.CBCEncrypt(plain.getBytes("UTF-8"), alg); res = new String(Base64.encodeBase64(bytesRes)); return res; }
public static String CBCDecrypt(String CText, String pwd, int KeySize, int alg, String mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeySpecException, DataLengthException, IllegalStateException, InvalidCipherTextException { String res = ""; byte[] Encrypted = Base64.decodeBase64(CText.getBytes("UTF-8")); Encryptor enc = new Encryptor(); enc.setParameters(KeySize, alg); enc.setDecParameters(Encrypted, alg, pwd, KeySize, mode); byte[] bytesRes = enc.CBCDecrypt(Encrypted, alg); res = new String(bytesRes, Charset.forName("UTF-8")); return res; }
public GenericKey generateUnwrappedKey(AlgorithmIdentifier encryptedKeyAlgorithm, byte[] encryptedKey) throws OperatorException { wrapper.init(false, wrappingKey); try { return new GenericKey(encryptedKeyAlgorithm, wrapper.unwrap(encryptedKey, 0, encryptedKey.length)); } catch (InvalidCipherTextException e) { throw new OperatorException("unable to unwrap key: " + e.getMessage(), e); } }
public static byte[] generateEncryptedPreMasterSecret(TlsContext context, RSAKeyParameters rsaServerPublicKey, OutputStream output) throws IOException { /* * Choose a PremasterSecret and send it encrypted to the server */ byte[] premasterSecret = new byte[48]; context.getSecureRandom().nextBytes(premasterSecret); TlsUtils.writeVersion(context.getClientVersion(), premasterSecret, 0); PKCS1Encoding encoding = new PKCS1Encoding(new RSABlindedEngine()); encoding.init(true, new ParametersWithRandom(rsaServerPublicKey, context.getSecureRandom())); try { byte[] encryptedPreMasterSecret = encoding.processBlock(premasterSecret, 0, premasterSecret.length); if (context.getServerVersion().isSSL()) { // TODO Do any SSLv3 servers actually expect the length? output.write(encryptedPreMasterSecret); } else { TlsUtils.writeOpaque16(encryptedPreMasterSecret, output); } } catch (InvalidCipherTextException e) { /* * This should never happen, only during decryption. */ throw new TlsFatalAlert(AlertDescription.internal_error); } return premasterSecret; }