javax.crypto.NoSuchPaddingException Java Examples

The following examples show how to use javax.crypto.NoSuchPaddingException. 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: SslContext.java    From netty4.0.27Learn with Apache License 2.0 6 votes vote down vote up
/**
 * Generates a key specification for an (encrypted) private key.
 *
 * @param password characters, if {@code null} or empty an unencrypted key is assumed
 * @param key bytes of the DER encoded private key
 *
 * @return a key specification
 *
 * @throws IOException if parsing {@code key} fails
 * @throws NoSuchAlgorithmException if the algorithm used to encrypt {@code key} is unkown
 * @throws NoSuchPaddingException if the padding scheme specified in the decryption algorithm is unkown
 * @throws InvalidKeySpecException if the decryption key based on {@code password} cannot be generated
 * @throws InvalidKeyException if the decryption key based on {@code password} cannot be used to decrypt
 *                             {@code key}
 * @throws InvalidAlgorithmParameterException if decryption algorithm parameters are somehow faulty
 */
protected static PKCS8EncodedKeySpec generateKeySpec(char[] password, byte[] key)
        throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException,
        InvalidKeyException, InvalidAlgorithmParameterException {

    if (password == null || password.length == 0) {
        return new PKCS8EncodedKeySpec(key);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

    Cipher cipher = Cipher.getInstance(encryptedPrivateKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, pbeKey, encryptedPrivateKeyInfo.getAlgParameters());

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example #2
Source File: DownloadData.java    From dummydroid with Apache License 2.0 6 votes vote down vote up
/**
 * Access the APK file
 * 
 * @return an inputstream from which the app can be read (already processed
 *         through crypto).
 * @throws NoSuchPaddingException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 */
public InputStream openApp() throws IOException, NoSuchAlgorithmException,
		NoSuchProviderException, NoSuchPaddingException, InvalidKeyException,
		InvalidAlgorithmParameterException {
	InputStream ret = api.executeDownload(downloadUrl, downloadAuthCookie.getName() + "="
			+ downloadAuthCookie.getValue());
	if (appDeliveryData.hasEncryptionParams()) {
		int version = ret.read();
		if (version != 0) {
			throw new IOException("Unknown crypto container!");
		}
		ret.skip(4); // Meta data
		byte[] iv = new byte[16];
		ret.read(iv);
		byte[] encoded = appDeliveryData.getEncryptionParams().getEncryptionKey().getBytes("UTF-8");
		byte[] decoded = Base64.decode(encoded, Base64.DEFAULT);
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE");
		SecretKeySpec key = new SecretKeySpec(decoded, "AES");
		cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
		return new CipherInputStream(ret, cipher);
	}
	else {
		return ret;
	}
}
 
Example #3
Source File: TestCipherKeyWrapperTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException,
        InvalidKeyException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException {
    for (String alg : PBE_ALGORITHM_AR) {
        String baseAlgo = alg.split("/")[0].toUpperCase();
        // only run the tests on longer key lengths if unlimited version
        // of JCE jurisdiction policy files are installed

        if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE
                && (baseAlgo.endsWith("TRIPLEDES") || alg
                        .endsWith("AES_256"))) {
            out.println("keyStrength > 128 within " + alg
                    + " will not run under global policy");
            continue;
        }
        SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p);
        SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover"
                .toCharArray()));
        wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true);
    }
}
 
Example #4
Source File: Signature.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static SignatureSpi newInstance(Service s)
        throws NoSuchAlgorithmException {
    if (s.getType().equals("Cipher")) {
        // must be NONEwithRSA
        try {
            Cipher c = Cipher.getInstance(RSA_CIPHER, s.getProvider());
            return new CipherAdapter(c);
        } catch (NoSuchPaddingException e) {
            throw new NoSuchAlgorithmException(e);
        }
    } else {
        Object o = s.newInstance(null);
        if (o instanceof SignatureSpi == false) {
            throw new NoSuchAlgorithmException
                ("Not a SignatureSpi: " + o.getClass().getName());
        }
        return (SignatureSpi)o;
    }
}
 
Example #5
Source File: AesFlushingCipher.java    From TelePlus-Android with GNU General Public License v2.0 6 votes vote down vote up
public AesFlushingCipher(int mode, byte[] secretKey, long nonce, long offset) {
  try {
    cipher = Cipher.getInstance("AES/CTR/NoPadding");
    blockSize = cipher.getBlockSize();
    zerosBlock = new byte[blockSize];
    flushedBlock = new byte[blockSize];
    long counter = offset / blockSize;
    int startPadding = (int) (offset % blockSize);
    cipher.init(
        mode,
        new SecretKeySpec(secretKey, Util.splitAtFirst(cipher.getAlgorithm(), "/")[0]),
        new IvParameterSpec(getInitializationVector(nonce, counter)));
    if (startPadding != 0) {
      updateInPlace(new byte[startPadding], 0, startPadding);
    }
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
      | InvalidAlgorithmParameterException e) {
    // Should never happen.
    throw new RuntimeException(e);
  }
}
 
Example #6
Source File: OS.java    From Flashtool with GNU General Public License v3.0 6 votes vote down vote up
public static void encrypt(File infile) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
 byte[] buf = new byte[1024];
    try {
  	  String outname = infile.getAbsolutePath()+".enc";
  	  FileInputStream in = new FileInputStream(infile);
  	  RC4OutputStream out = new RC4OutputStream(new FileOutputStream(outname));
  	  int len;
  	  while((len = in.read(buf)) >= 0) {
  		  if (len > 0)
  			  out.write(buf, 0, len);
  	  }
  	  out.flush();
  	  out.close();
  	  in.close();
    } catch(IOException e) {
      e.printStackTrace();
    }
}
 
Example #7
Source File: Wallet.java    From etherscan-explorer with GNU General Public License v3.0 6 votes vote down vote up
private static byte[] performCipherOperation(
        int mode, byte[] iv, byte[] encryptKey, byte[] text) throws CipherException {

    try {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        SecretKeySpec secretKeySpec = new SecretKeySpec(encryptKey, "AES");
        cipher.init(mode, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(text);
    } catch (NoSuchPaddingException | NoSuchAlgorithmException
            | InvalidAlgorithmParameterException | InvalidKeyException
            | BadPaddingException | IllegalBlockSizeException e) {
        throw new CipherException("Error performing cipher operation", e);
    }
}
 
Example #8
Source File: CipherFileChannelTest.java    From encfs4j with Apache License 2.0 6 votes vote down vote up
@Test
public void test2DefaultRead() throws IOException,
		NoSuchAlgorithmException, NoSuchPaddingException {

	CipherFileChannel fc = new CipherFileChannel(Paths.get(persistentFile
			.getAbsolutePath()), cipherTransformation, secretKeySpec,
			Paths.get(persistentFile.getParent()), false);

	ByteBuffer buf = ByteBuffer.allocate(testStringLength);
	fc.read(buf);
	fc.close();

	buf.flip();

	byte[] dst = new byte[testStringLength];

	buf.get(dst);

	assertEquals(testString, new String(dst));
}
 
Example #9
Source File: XMLCipher.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Construct a Cipher object
 */
private Cipher constructCipher(String algorithm, String digestAlgorithm) throws XMLEncryptionException {
    String jceAlgorithm = JCEMapper.translateURItoJCEID(algorithm);
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "JCE Algorithm = " + jceAlgorithm);
    }

    Cipher c;
    try {
        if (requestedJCEProvider == null) {
            c = Cipher.getInstance(jceAlgorithm);
        } else {
            c = Cipher.getInstance(jceAlgorithm, requestedJCEProvider);
        }
    } catch (NoSuchAlgorithmException nsae) {
        // Check to see if an RSA OAEP MGF-1 with SHA-1 algorithm was requested
        // Some JDKs don't support RSA/ECB/OAEPPadding
        if (XMLCipher.RSA_OAEP.equals(algorithm)
            && (digestAlgorithm == null
                || MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1.equals(digestAlgorithm))) {
            try {
                if (requestedJCEProvider == null) {
                    c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding");
                } else {
                    c = Cipher.getInstance("RSA/ECB/OAEPWithSHA1AndMGF1Padding", requestedJCEProvider);
                }
            } catch (Exception ex) {
                throw new XMLEncryptionException("empty", ex);
            }
        } else {
            throw new XMLEncryptionException("empty", nsae);
        }
    } catch (NoSuchProviderException nspre) {
        throw new XMLEncryptionException("empty", nspre);
    } catch (NoSuchPaddingException nspae) {
        throw new XMLEncryptionException("empty", nspae);
    }

    return c;
}
 
Example #10
Source File: CryptoClass.java    From Android-InsecureBankv2 with MIT License 6 votes vote down vote up
public static byte[] aes256decrypt(byte[] ivBytes, byte[] keyBytes, byte[] textBytes)
throws UnsupportedEncodingException,
NoSuchAlgorithmException,
NoSuchPaddingException,
InvalidKeyException,
InvalidAlgorithmParameterException,
IllegalBlockSizeException,
BadPaddingException {

	AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivBytes);
	SecretKeySpec newKey = new SecretKeySpec(keyBytes, "AES");
	Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
	cipher.init(Cipher.DECRYPT_MODE, newKey, ivSpec);
	return cipher.doFinal(textBytes);
	
}
 
Example #11
Source File: AttachmentCipherInputStream.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
private AttachmentCipherInputStream(InputStream inputStream, byte[] cipherKey, long totalDataSize)
    throws IOException
{
  super(inputStream);

  try {
    byte[] iv = new byte[BLOCK_SIZE];
    readFully(iv);

    this.cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    this.cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(cipherKey, "AES"), new IvParameterSpec(iv));

    this.done          = false;
    this.totalRead     = 0;
    this.totalDataSize = totalDataSize;
  } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example #12
Source File: TestCipher.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public void runAll() throws InvalidKeyException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        ShortBufferException, IllegalBlockSizeException,
        BadPaddingException, NoSuchAlgorithmException,
        NoSuchProviderException {

    for (String mode : MODES) {
        for (String padding : PADDINGS) {
            if (!isMultipleKeyLengthSupported()) {
                runTest(mode, padding, minKeySize);
            } else {
                int keySize = maxKeySize;
                while (keySize >= minKeySize) {
                    out.println("With Key Strength: " + keySize);
                    runTest(mode, padding, keySize);
                    keySize -= KEYCUTTER;
                }
            }
        }
    }
}
 
Example #13
Source File: SymmetricCryptograph.java    From cassandra-reaper with Apache License 2.0 6 votes vote down vote up
private String decryptText(String key, String encryptedText) throws InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
  byte[] encryptedData = decode(encryptedText);
  if (encryptedData.length <= 16) {
    throw new IllegalArgumentException("Invalid format for supplied encrypted value");
  }

  byte[] initVector = subArray(encryptedData, 0, 16);
  byte[] encryptedBytes = subArray(encryptedData, initVector.length, encryptedData.length);

  IvParameterSpec ivspec = new IvParameterSpec(initVector);
  SecretKey secretKey = createSecretKey(key);

  Cipher decipher = Cipher.getInstance(cipher);
  decipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
  byte[] decryptedBytes = decipher.doFinal(encryptedBytes);

  return new String(decryptedBytes, StandardCharsets.UTF_8);
}
 
Example #14
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
public static SealedData seal(@NonNull byte[] input) {
  SecretKey secretKey = getOrCreateKeyStoreEntry();

  try {
    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    byte[] iv   = cipher.getIV();
    byte[] data = cipher.doFinal(input);

    return new SealedData(iv, data);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example #15
Source File: EncryptedCoder.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
OutputStream createEncryptedOutputStream(@NonNull byte[] masterKey, @NonNull File file)
    throws IOException
{
  try {
    byte[] random = Util.getSecretBytes(32);
    Mac    mac    = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(masterKey, "HmacSHA256"));

    FileOutputStream fileOutputStream = new FileOutputStream(file);
    byte[]           iv               = new byte[16];
    byte[]           key              = mac.doFinal(random);

    Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));

    fileOutputStream.write(MAGIC_BYTES);
    fileOutputStream.write(random);

    CipherOutputStream outputStream = new CipherOutputStream(fileOutputStream, cipher);
    outputStream.write(MAGIC_BYTES);

    return outputStream;
  } catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {
    throw new AssertionError(e);
  }
}
 
Example #16
Source File: AttachmentCipherOutputStream.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private Cipher initializeCipher() {
  try {
    return Cipher.getInstance("AES/CBC/PKCS5Padding");
  } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
    throw new AssertionError(e);
  }
}
 
Example #17
Source File: EncryptDES.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
public EncryptDES() throws NoSuchAlgorithmException, NoSuchPaddingException{
	//ʵ����֧��DES�㷨����Կ������(�㷨���������谴�涨�������׳��쳣)
	keygen = KeyGenerator.getInstance("DES", new org.bouncycastle.jce.provider.BouncyCastleProvider());
	//������Կ
	deskey = keygen.generateKey();
	//����Cipher����,ָ����֧�ֵ�DES�㷨
	c = Cipher.getInstance("DES");
}
 
Example #18
Source File: TelemetryService.java    From AirMapSDK-Android with Apache License 2.0 5 votes vote down vote up
private byte[] encrypt(byte[] key, IvParameterSpec iv, byte[] payload) throws InvalidAlgorithmParameterException, InvalidKeyException,
        IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException {

    SecretKey secretKey = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
    return cipher.doFinal(payload);
}
 
Example #19
Source File: DESCoder.java    From wecube-platform with Apache License 2.0 5 votes vote down vote up
public byte[] doDecrypt(byte[] data, byte[] key) throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException {
    SecureRandom random = new SecureRandom();
    DESKeySpec desKey = new DESKeySpec(key);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(CIPHER_ALGORITHM);
    SecretKey securekey = keyFactory.generateSecret(desKey);
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
    cipher.init(Cipher.DECRYPT_MODE, securekey, random);
    return cipher.doFinal(data);

}
 
Example #20
Source File: GXDLMSClock.java    From gurux.dlms.java with GNU General Public License v2.0 5 votes vote down vote up
public final byte[][] shiftTime(final GXDLMSClient client,
        final int forTime)
        throws InvalidKeyException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    if (forTime < -900 || forTime > 900) {
        throw new IllegalArgumentException("Invalid shift time.");
    }
    return client.method(this, 6, forTime, DataType.INT16);
}
 
Example #21
Source File: SM4Util.java    From chain33-sdk-java with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private static Cipher generateCBCCipher(String algorithmName, int mode, byte[] key, byte[] iv)
        throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        NoSuchProviderException, NoSuchPaddingException {
    Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
    Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
    IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
    cipher.init(mode, sm4Key, ivParameterSpec);
    return cipher;
}
 
Example #22
Source File: LockSettingsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public VerifyCredentialResponse verifyTiedProfileChallenge(String credential, int type,
        long challenge, int userId) throws RemoteException {
    checkPasswordReadPermission(userId);
    if (!isManagedProfileWithUnifiedLock(userId)) {
        throw new RemoteException("User id must be managed profile with unified lock");
    }
    final int parentProfileId = mUserManager.getProfileParent(userId).id;
    // Unlock parent by using parent's challenge
    final VerifyCredentialResponse parentResponse = doVerifyCredential(
            credential,
            type,
            true /* hasChallenge */,
            challenge,
            parentProfileId,
            null /* progressCallback */);
    if (parentResponse.getResponseCode() != VerifyCredentialResponse.RESPONSE_OK) {
        // Failed, just return parent's response
        return parentResponse;
    }

    try {
        // Unlock work profile, and work profile with unified lock must use password only
        return doVerifyCredential(getDecryptedPasswordForTiedProfile(userId),
                LockPatternUtils.CREDENTIAL_TYPE_PASSWORD,
                true,
                challenge,
                userId, null /* progressCallback */);
    } catch (UnrecoverableKeyException | InvalidKeyException | KeyStoreException
            | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidAlgorithmParameterException | IllegalBlockSizeException
            | BadPaddingException | CertificateException | IOException e) {
        Slog.e(TAG, "Failed to decrypt child profile key", e);
        throw new RemoteException("Unable to get tied profile token");
    }
}
 
Example #23
Source File: Crypto.java    From PowerFileExplorer with GNU General Public License v3.0 5 votes vote down vote up
public byte[] cipher(byte[] data, int mode)
		throws NoSuchAlgorithmException, NoSuchPaddingException,
		InvalidKeyException, IllegalBlockSizeException,
		BadPaddingException, InvalidAlgorithmParameterException {
	KeyManager km = new KeyManager(ctx);
	SecretKeySpec sks = new SecretKeySpec(km.getId(), engine);
	IvParameterSpec iv = new IvParameterSpec(km.getIv());
	Cipher c = Cipher.getInstance(crypto);
	c.init(mode, sks, iv);
	return c.doFinal(data);
}
 
Example #24
Source File: CICOSkipTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void initCiphers(String algo, SecretKey key,
        AlgorithmParameterSpec aps) throws NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException,
        InvalidAlgorithmParameterException {
    Provider provider = Security.getProvider("SunJCE");
    if (provider == null) {
        throw new RuntimeException("SunJCE provider does not exist.");
    }
    Cipher ci1 = Cipher.getInstance(algo, provider);
    ci1.init(Cipher.ENCRYPT_MODE, key, aps);
    pair[0] = ci1;
    Cipher ci2 = Cipher.getInstance(algo, provider);
    ci2.init(Cipher.DECRYPT_MODE, key, aps);
    pair[1] = ci2;
}
 
Example #25
Source File: ToolDES.java    From protools with Apache License 2.0 5 votes vote down vote up
/**
 * 加密
 *
 * @param data
 *         待加密数据
 * @param key
 *         密钥
 *
 * @return byte[] 加密数据
 *
 * @throws Exception
 */
public static byte[] encrypt(byte[] data, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException {

    // 还原密钥
    Key k = toKey(key);

    // 实例化
    Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

    // 初始化,设置为加密模式
    cipher.init(Cipher.ENCRYPT_MODE, k);

    // 执行操作
    return cipher.doFinal(data);
}
 
Example #26
Source File: KeyStoreHelper.java    From xmrwallet with Apache License 2.0 5 votes vote down vote up
private static byte[] encrypt(String alias, byte[] data) {
    try {
        PublicKey publicKey = getPublicKey(alias);
        Cipher cipher = Cipher.getInstance(SecurityConstants.CIPHER_RSA_ECB_PKCS1);

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    } catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException
            | NoSuchAlgorithmException | NoSuchPaddingException ex) {
        Timber.e(ex);
        return null;
    }
}
 
Example #27
Source File: ExportControlled.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
public static byte[] encryptWithRSAPublicKey(byte[] source, RSAPublicKey key, String transformation) throws RSAException {
    try {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(source);
    } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
        throw ExceptionFactory.createException(RSAException.class, e.getMessage(), e);
    }
}
 
Example #28
Source File: DynRH.java    From Clusion with GNU General Public License v3.0 5 votes vote down vote up
public static List<String> resolve(byte[] key, List<byte[]> list)
		throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
		NoSuchProviderException, NoSuchPaddingException, IOException {

	byte[] key2 = CryptoPrimitives.generateCmac(key, 1 + new String());
	List<String> result = new ArrayList<String>();

	for (byte[] ct : list) {
		String decr = new String(CryptoPrimitives.decryptAES_CTR_String(ct, key2)).split("\t\t\t")[0];
		result.add(decr);
	}

	return result;
}
 
Example #29
Source File: RC4OutputStream.java    From Flashtool with GNU General Public License v3.0 5 votes vote down vote up
public RC4OutputStream(OutputStream out) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException {
       if (Security.getProvider("BC") == null) {
           Security.addProvider(new BouncyCastleProvider());
       }
       SecretKeySpec secretKeySpec = new SecretKeySpec(BaseEncoding.base64().decode(OS.RC4Key), "RC4");
       Cipher cipher = Cipher.getInstance("RC4");
       cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
       localCipherOutputStream = new CipherOutputStream(out, cipher);
}
 
Example #30
Source File: SecKFTranslateTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(Algorithm algo) throws NoSuchAlgorithmException,
        NoSuchProviderException, InvalidKeyException,
        InvalidKeySpecException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, ShortBufferException,
        IllegalBlockSizeException, BadPaddingException {
    AlgorithmParameterSpec[] aps = new AlgorithmParameterSpec[1];
    byte[] plainText = new byte[800];

    SecretKey key1 = algo.intSecurityKey(aps);
    Random random = new Random();
    // Initialization
    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.toString(),
            SUN_JCE);

    random.nextBytes(plainText);
    Cipher ci = Cipher.getInstance(algo.toString(), SUN_JCE);
    // Encryption
    ci.init(Cipher.ENCRYPT_MODE, key1, aps[0]);
    byte[] cipherText = new byte[ci.getOutputSize(plainText.length)];
    int offset = ci.update(plainText, 0, plainText.length, cipherText, 0);
    ci.doFinal(cipherText, offset);
    // translate key
    SecretKey key2 = skf.translateKey(key1);

    // Decryption
    ci.init(Cipher.DECRYPT_MODE, key2, aps[0]);
    byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)];
    ci.doFinal(cipherText, 0, cipherText.length, recoveredText);

    // Comparison
    if (!Arrays.equals(plainText, recoveredText)) {
        System.out.println("Key1:" + new String(key1.getEncoded())
                + " Key2:" + new String(key2.getEncoded()));
        throw new RuntimeException("Testing translate key failed with "
                + algo);
    }

}