Java Code Examples for javax.crypto.NoSuchPaddingException

The following are top voted examples for showing how to use javax.crypto.NoSuchPaddingException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: BaseClient   File: CryptManager.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the Cipher Instance.
 */
private static Cipher createTheCipherInstance(int opMode, String transformation, Key key)
{
    try
    {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opMode, key);
        return cipher;
    }
    catch (InvalidKeyException invalidkeyexception)
    {
        invalidkeyexception.printStackTrace();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
    }
    catch (NoSuchPaddingException nosuchpaddingexception)
    {
        nosuchpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher creation failed!");
    return null;
}
 
Example 2
Project: DMS   File: AES256.java   Source Code and License 6 votes vote down vote up
public String decrypt(String str) {
    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());
        String Str = new String(cipher.doFinal(byteStr), "UTF-8");

        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
    }
    return null;
}
 
Example 3
Project: openjdk-jdk10   File: TestCipher.java   Source Code and License 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 4
Project: DMS   File: AES256.java   Source Code and License 6 votes vote down vote up
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());
        String Str = new String(cipher.doFinal(byteStr), "UTF-8");

        return Str;
    } catch (NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeyException | InvalidAlgorithmParameterException
            | IllegalBlockSizeException | BadPaddingException
            | UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 5
Project: wolfcrypt-jni   File: WolfCryptCipherTest.java   Source Code and License 6 votes vote down vote up
@BeforeClass
public static void testProviderInstallationAtRuntime()
    throws NoSuchProviderException, NoSuchPaddingException {

    /* install wolfJCE provider at runtime */
    Security.addProvider(new WolfCryptProvider());

    Provider p = Security.getProvider("wolfJCE");
    assertNotNull(p);

    /* populate enabledJCEAlgos to test */
    for (int i = 0; i < supportedJCEAlgos.length; i++) {
        try {
            Cipher c = Cipher.getInstance(supportedJCEAlgos[i], "wolfJCE");
            enabledJCEAlgos.add(supportedJCEAlgos[i]);

        } catch (NoSuchAlgorithmException e) {
            /* algorithm not enabled */
        }
    }

    /* fill expected block size HashMap */
    expectedBlockSizes.put("AES/CBC/NoPadding", 16);
    expectedBlockSizes.put("DESede/CBC/NoPadding", 8);
    expectedBlockSizes.put("RSA/ECB/PKCS1Padding", 0);
}
 
Example 6
Project: iot-plat   File: EncryptDecryptData.java   Source Code and License 6 votes vote down vote up
/**
 * 加密方法
 * 
 * @param rawKeyData
 * @param str
 * @return
 * @throws InvalidKeyException
 * @throws NoSuchAlgorithmException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws NoSuchPaddingException
 * @throws InvalidKeySpecException
 */
public static byte[] encrypt(byte rawKeyData[], String str) throws InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException,
		BadPaddingException, NoSuchPaddingException, InvalidKeySpecException {
	// DES算法要求有一个可信任的随机数源
	SecureRandom sr = new SecureRandom();
	// 从原始密匙数据创建一个DESKeySpec对象
	DESKeySpec dks = new DESKeySpec(rawKeyData);
	// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
	SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
	SecretKey key = keyFactory.generateSecret(dks);
	// Cipher对象实际完成加密操作
	Cipher cipher = Cipher.getInstance("DES");
	// 用密匙初始化Cipher对象
	cipher.init(Cipher.ENCRYPT_MODE, key, sr);
	// 现在,获取数据并加密
	byte data[] = str.getBytes();
	// 正式执行加密操作
	byte[] encryptedData = cipher.doFinal(data);

	System.out.println("加密后===>" + encryptedData);
	return encryptedData;
}
 
Example 7
Project: Mevius-IO   File: MeviusTransferPacket.java   Source Code and License 6 votes vote down vote up
public static MeviusTransferPacket getInstance(PublicKey publickey, MeviusPacket packet)
		throws MeviusCipherException {
	try {
		DESedeKeySpec desKeySpec = new DESedeKeySpec(((String) MeviusCipherKey.randomDESKey().getKey()).getBytes());
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
		Key key = keyFactory.generateSecret(desKeySpec);
		Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE");
		c.init(Cipher.ENCRYPT_MODE, publickey);
		byte[] bkey = convertObj(key, c);
		c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
		c.init(Cipher.ENCRYPT_MODE, key);
		byte[] bobj = convertObj(packet, c);
		return new MeviusTransferPacket(bkey, bobj);
	} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
			| IOException | InvalidKeySpecException | IllegalBlockSizeException | BadPaddingException e) {
		e.printStackTrace();
		throw new MeviusCipherException(e.getLocalizedMessage());
	}
}
 
Example 8
Project: openjdk-jdk10   File: TestCipherKeyWrapperTest.java   Source Code and License 6 votes vote down vote up
private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms)
        throws NoSuchAlgorithmException, InvalidKeyException,
        NoSuchPaddingException, IllegalBlockSizeException,
        InvalidAlgorithmParameterException {
    for (String algo : algorithms) {
        // Key pair generated
        System.out.println("Generate key pair (algorithm: " + algo
                + ", provider: " + p.getName() + ")");
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo);
        kpg.initialize(512);
        KeyPair kp = kpg.genKeyPair();
        // key generated
        String algoWrap = "DES";
        KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p);
        Key key = kg.generateKey();
        wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY,
                false);
        wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY,
                false);
    }
}
 
Example 9
Project: keepass2android   File: NativeAESCipherSpi.java   Source Code and License 6 votes vote down vote up
@Override
protected void engineSetPadding(String padding)
		throws NoSuchPaddingException {
	
	if ( ! mIsInited ) {
		NativeLib.init();
	}
	
	if ( padding.length() == 0 ) {
		return;
	}

	if ( ! padding.equals("PKCS5Padding") ) {
		throw new NoSuchPaddingException("Only supports PKCS5Padding.");
	}
	
	mPadding = true;
		
}
 
Example 10
Project: CustomWorldGen   File: CryptManager.java   Source Code and License 6 votes vote down vote up
/**
 * Creates the Cipher Instance.
 */
private static Cipher createTheCipherInstance(int opMode, String transformation, Key key)
{
    try
    {
        Cipher cipher = Cipher.getInstance(transformation);
        cipher.init(opMode, key);
        return cipher;
    }
    catch (InvalidKeyException invalidkeyexception)
    {
        invalidkeyexception.printStackTrace();
    }
    catch (NoSuchAlgorithmException nosuchalgorithmexception)
    {
        nosuchalgorithmexception.printStackTrace();
    }
    catch (NoSuchPaddingException nosuchpaddingexception)
    {
        nosuchpaddingexception.printStackTrace();
    }

    LOGGER.error("Cipher creation failed!");
    return null;
}
 
Example 11
Project: Mevius-IO   File: MeviusTransferPacket.java   Source Code and License 6 votes vote down vote up
public Key getKey(PrivateKey privatekey) throws MeviusCipherException {
	try {
		Cipher c = Cipher.getInstance("RSA/ECB/PKCS1PADDING", "SunJCE");
		c.init(Cipher.DECRYPT_MODE, privatekey);
		/*
		 * DESedeKeySpec desKeySpec = new DESedeKeySpec((byte[]) (convertByte(key, c)));
		 * SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede"); return
		 * keyFactory.generateSecret(desKeySpec);
		 */
		return (Key) convertByte(key, c);
	} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException
			| ClassNotFoundException | IOException | IllegalBlockSizeException | BadPaddingException e) {
		e.printStackTrace();
		throw new MeviusCipherException(e.getMessage());
	}
}
 
Example 12
Project: sunbird-utils   File: DefaultEncryptionServivceImpl.java   Source Code and License 6 votes vote down vote up
/**
 * this method is used to encrypt the password.
 * 
 * @param value String password
 * @param encryption_key
 * @return encrypted password.
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws BadPaddingException
 * @throws IllegalBlockSizeException
 */
@SuppressWarnings("restriction")
public static String encrypt(String value) throws NoSuchAlgorithmException,
    NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
  encryption_key = getSalt();
  Key key = generateKey();
  Cipher c = Cipher.getInstance(ALGORITHM);
  c.init(Cipher.ENCRYPT_MODE, key);

  String valueToEnc = null;
  String eValue = value;
  for (int i = 0; i < ITERATIONS; i++) {
    valueToEnc = encryption_key + eValue;
    byte[] encValue = c.doFinal(valueToEnc.getBytes());
    eValue = new sun.misc.BASE64Encoder().encode(encValue);
  }
  return eValue;
}
 
Example 13
Project: nifi-registry   File: AESSensitivePropertyProvider.java   Source Code and License 6 votes vote down vote up
public AESSensitivePropertyProvider(String keyHex) throws NoSuchPaddingException, NoSuchAlgorithmException, NoSuchProviderException {
    byte[] key = validateKey(keyHex);

    try {
        Security.addProvider(new BouncyCastleProvider());
        cipher = Cipher.getInstance(ALGORITHM, PROVIDER);
        // Only store the key if the cipher was initialized successfully
        this.key = new SecretKeySpec(key, "AES");
    } catch (NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException e) {
        logger.error("Encountered an error initializing the {}: {}", IMPLEMENTATION_NAME, e.getMessage());
        throw new SensitivePropertyProtectionException("Error initializing the protection cipher", e);
    }
}
 
Example 14
Project: dracoon-dropzone   File: CryptoUtil.java   Source Code and License 6 votes vote down vote up
private byte[] decrypt(byte[] cipherText, byte[] key, byte[] initialVector)
		throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
		InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
	Cipher cipher = Cipher.getInstance(cipherTransformation);
	SecretKeySpec secretKeySpecy = new SecretKeySpec(key, aesEncryptionAlgorithm);
	IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
	cipher.init(Cipher.DECRYPT_MODE, secretKeySpecy, ivParameterSpec);
	cipherText = cipher.doFinal(cipherText);
	return cipherText;
}
 
Example 15
Project: dracoon-dropzone   File: CryptoUtil.java   Source Code and License 6 votes vote down vote up
public String encrypt(String plainText, String key) {
	String encodedString = "";

	try {
		byte[] plainTextbytes = plainText.getBytes(characterEncoding);
		byte[] keyBytes = getKeyBytes(KEY_PREFIX + "" + key);
		encodedString = Base64.getEncoder().encodeToString(encrypt(plainTextbytes, keyBytes, keyBytes));
	} catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
			| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

	return encodedString;

}
 
Example 16
Project: alfresco-core   File: DefaultEncryptor.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 17
Project: oscm-app   File: PasswordSetup.java   Source Code and License 6 votes vote down vote up
private String decrypt(String text) throws GeneralSecurityException {
    SecretKeySpec skeySpec = new SecretKeySpec(
            Base64.decodeBase64(ENCRYPTION_KEY), "AES");

    byte[] result;
    try {
        byte[] decoded = Base64.decodeBase64(text.getBytes());
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        result = cipher.doFinal(decoded);
    } catch (InvalidKeyException | NoSuchAlgorithmException
            | NoSuchPaddingException | IllegalBlockSizeException
            | BadPaddingException e) {
        throw new GeneralSecurityException(
                "unable to decrypt old encryption");
    }

    return new String(result);
}
 
Example 18
Project: timesheet-upload   File: EncryptDecryptUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns an encrypted value from a given String value, encrypt/encode it
 * into an URL safe String. This method uses AES algorithm for encryption
 * and Apache Base64 class to encode it into URL safe String from byte
 * array.
 *
 * @param key        --- This key is a 16byte String parameter. In ECAS it is
 *                   created using Apache RandomUtils method and is stored in the session. So
 *                   the key will be different for each session.
 * @param initVector --- This initVector is a 16byte String parameter. In
 *                   ECAS it is a constant that is maintained in each controller.
 * @param value      --- This is the input value that will be encrypted.
 * @return
 * @throws Exception
 */
public String encrypt(String key, String initVector, String value) throws Exception {
    log.debug("Inside the encrypt method of EncryptDecryptService");
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(ENCODING));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM_AES);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

        byte[] encrypted = cipher.doFinal(value.getBytes());
        log.info("Encrypted string: " + Base64.encodeBase64URLSafeString(encrypted));

        return Base64.encodeBase64URLSafeString(encrypted);
    } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException ex) {
        log.error("Error while encryption: " + ex);
        throw ex;
    }

}
 
Example 19
Project: timesheet-upload   File: EncryptDecryptUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a decrypted String value for a given encrypted value. This method
 * uses AES algorithm for encryption/decryption and Apache Commons Codec
 * Base64 class to decode it into a byte array.
 *
 * @param key---     This key is a 16byte String parameter. In ECAS it is
 *                   created using Apache RandomUtils method and is stored in the session. So
 *                   the key will be different for each session.
 * @param initVector --- This initVector is a 16byte String parameter. In
 *                   ECAS it is a constant that is maintained in each controller.
 * @param encrypted  --- This is the encrypted value that will be decrypted.
 * @return
 * @throws Exception
 */
public String decrypt(String key, String initVector, String encrypted) throws Exception {
    try {
        IvParameterSpec iv = new IvParameterSpec(initVector.getBytes(ENCODING));
        SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM_AES);

        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

        byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));
        log.info("Decrypted string: " + original);

        return new String(original);
    } catch (UnsupportedEncodingException | InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException ex) {
        log.error("Error while decryption: " + ex);
        throw ex;
    }

}
 
Example 20
Project: Parallator   File: Security.java   Source Code and License 5 votes vote down vote up
public static String decrypt(String encrypted) throws IllegalArgumentException, UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    IvParameterSpec iv = new IvParameterSpec(getInitVector());
    SecretKeySpec skeySpec = new SecretKeySpec(getKey(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

    byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted.trim()));

    return new String(original);
}
 
Example 21
Project: iroha-demo-android   File: AssetReceivePresenter.java   Source Code and License 5 votes vote down vote up
@NotNull
private String getPublicKey() {
    if (publicKey == null || publicKey.isEmpty()) {
        final Context context = assetReceiveView.getContext();
        try {
            publicKey = KeyPair.getKeyPair(context).publicKey;
        } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException
                | KeyStoreException | InvalidKeyException | IOException e) {
            Log.e(TAG, "getKeyPair: ", e);
            assetReceiveView.showError(ErrorMessageFactory.create(context, e), e);
            return "";
        }
    }
    return publicKey;
}
 
Example 22
Project: phoenix.webui.framework   File: Encryptor.java   Source Code and License 5 votes vote down vote up
private Encryptor(String algorithm) throws NoSuchAlgorithmException, NoSuchPaddingException
{
    keyGen = KeyGenerator.getInstance(algorithm);
    key = keyGen.generateKey();
    
    cipher = Cipher.getInstance(algorithm);
}
 
Example 23
Project: jdk8u-jdk   File: CICOSkipTest.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 24
Project: phoenix.webui.framework   File: EncryptorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test() throws NoSuchAlgorithmException, NoSuchPaddingException, 
	InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
	Encryptor encryptor = Encryptor.getInstance(Encryptor.ALG_DES);
	
	String plainText = "123456";
	
	String encryptText = encryptor.encryptStr(plainText);
	System.out.println("plainText : " + plainText);
	System.out.println("encryptText : " + encryptText);
	
	String decryptText = encryptor.decryptStr(encryptText);
	System.out.println("decryptText : " + decryptText);
}
 
Example 25
Project: PearPlanner   File: StudyPlanner.java   Source Code and License 5 votes vote down vote up
public StudyPlanner(Account newAccount) throws NoSuchPaddingException, NoSuchAlgorithmException
{
    this.account = newAccount;
    // Add Default Quantity types:
    Collections.addAll(this.quantityTypes, QuantityType.listOfQuantityTypes());
    // Add Default Task types:
    Collections.addAll(this.taskTypes, TaskType.listOfTaskTypes());
}
 
Example 26
Project: trust-wallet-android   File: PasswordManagerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void setGetPasswordLegacy() throws NoSuchPaddingException, InvalidKeyException, NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException, UnsupportedEncodingException, InvalidKeySpecException {
    Context context = InstrumentationRegistry.getTargetContext();

    PasswordManager.setPasswordLegacy("myaddress", "mypassword", context);
    assertThat(PasswordManager.getPassword("myaddress", context), is("mypassword"));
}
 
Example 27
Project: SecureUtils   File: AES256PKCS5Padding.java   Source Code and License 5 votes vote down vote up
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()));
}
 
Example 28
Project: SecureUtils   File: AES256PKCS5Padding.java   Source Code and License 5 votes vote down vote up
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)));
}
 
Example 29
Project: SecureUtils   File: AES128PKCS7Padding.java   Source Code and License 5 votes vote down vote up
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()));
}
 
Example 30
Project: mfva   File: ExportedActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_exported);

    Log.d("redis", "Initialising jedis...");
    Jedis jedis = new Jedis("localhost");

    try {
        Cipher.getInstance("DES/ECB/ZeroBytePadding", "BC");
    } catch (NoSuchAlgorithmException|NoSuchProviderException|NoSuchPaddingException e) {
        // pass
    }
}
 
Example 31
Project: SecureUtils   File: SecureStringTest.java   Source Code and License 5 votes vote down vote up
@Test
public void isEmptyIsCorrect()
        throws NoSuchPaddingException, IOException, InvalidAlgorithmParameterException,
        NoSuchAlgorithmException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException {
    SecureString secureString1 = new SecureString(KEY, "");
    assertTrue(secureString1.isEmpty());
}
 
Example 32
Project: jdk8u-jdk   File: TestCipherKeyWrapperTest.java   Source Code and License 5 votes vote down vote up
private void wrapperBlowfishKeyTest() throws InvalidKeyException,
        NoSuchAlgorithmException, NoSuchPaddingException,
        IllegalBlockSizeException, InvalidAlgorithmParameterException {
    // how many kinds of padding mode
    int padKinds;
    // Keysize should be multiple of 8 bytes.
    int KeyCutter = 8;
    int kSize = BLOWFISH_MIN_KEYSIZE;
    String algorithm = "Blowfish";
    int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm);
    boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE;
    SecretKey key = null;
    while (kSize <= BLOWFISH_MAX_KEYSIZE) {
        for (String mode : MODEL_AR) {
            // PKCS5padding is meaningful only for ECB, CBC, PCBC
            if (mode.equalsIgnoreCase(MODEL_AR[0])
                    || mode.equalsIgnoreCase(MODEL_AR[1])
                    || mode.equalsIgnoreCase(MODEL_AR[2])) {
                padKinds = PADDING_AR.length;
            } else {
                padKinds = 1;
            }
            // Initialization
            KeyGenerator kg = KeyGenerator.getInstance(algorithm);
            for (int k = 0; k < padKinds; k++) {
                String transformation = algorithm + "/" + mode + "/"
                        + PADDING_AR[k];
                if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) {
                    out.println(transformation
                            + " will not run if input length not multiple"
                            + " of 8 bytes when padding is " + NOPADDING);
                    continue;
                }
                kg.init(kSize);
                key = kg.generateKey();
                // only run the tests on longer key lengths if unlimited
                // version of JCE jurisdiction policy files are installed
                if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) {
                    out.println("keyStrength > 128 within " + algorithm
                            + " will not run under global policy");
                } else {
                    wrapTest(transformation, transformation, key, key,
                            Cipher.SECRET_KEY, false);
                }
            }
        }
        if (kSize <= LINIMITED_KEYSIZE) {
            KeyCutter = 8;
        } else {
            KeyCutter = 48;
        }
        kSize += KeyCutter;
    }
}
 
Example 33
Project: keepass2android   File: JCEStreamCipher.java   Source Code and License 5 votes vote down vote up
/**
 * should never be called.
 */
protected void engineSetPadding(
    String  padding) 
throws NoSuchPaddingException
{
    if (!padding.equalsIgnoreCase("NoPadding"))
    {
        throw new NoSuchPaddingException("Padding " + padding + " unknown.");
    }
}
 
Example 34
Project: jdk8u-jdk   File: XMLCipher.java   Source Code and License 5 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 35
Project: openjdk-jdk10   File: PBECipherWrapper.java   Source Code and License 5 votes vote down vote up
public PBKDF2(String algo, String passwd)
        throws InvalidKeySpecException, NoSuchAlgorithmException,
        NoSuchPaddingException {
    super(algo, PBKDF2_SALT_SIZE);

    ci = Cipher.getInstance(CIPHER_TRANSFORMATION);

    PBEKeySpec pbeKeySpec = new PBEKeySpec(passwd.toCharArray(), getSalt(),
            ITERATION_COUNT, CIPHER_KEY_SIZE);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo);
    key = keyFactory.generateSecret(pbeKeySpec);
}
 
Example 36
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 5 votes vote down vote up
/**
 * The private key corresponding to the contract certificate is to be decrypted by 
 * the receiver (EVCC) using the session key derived in the ECDH protocol.
 * Applies the algorithm AES-CBC-128 according to NIST Special Publication 800-38A.
 * The initialization vector IV shall be read from the 16 most significant bytes of the 
 * ContractSignatureEncryptedPrivateKey field.
 * 
 * @param sessionKey The symmetric session key with which the encrypted private key is to be decrypted
 * @param encryptedKeyWithIV The encrypted private key of the contract certificate given as a byte array
 * 							 whose first 16 byte hold the initialization vector
 * @return The decrypted private key of the contract certificate
 */
private static ECPrivateKey decryptPrivateKey(SecretKey sessionKey, byte[] encryptedKeyWithIV) {
	byte[] initVector = new byte[16];
	byte[] encryptedKey = null;
	
	try {
		// Get the first 16 bytes of the encrypted private key which hold the IV
		
		encryptedKey = new byte[encryptedKeyWithIV.length - 16];
		System.arraycopy(encryptedKeyWithIV, 0, initVector, 0, 16);
		System.arraycopy(encryptedKeyWithIV, 16, encryptedKey, 0, encryptedKeyWithIV.length - 16);
		
		IvParameterSpec ivParamSpec = new IvParameterSpec(initVector);
		Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
		
		/*
		 * You must have the Java Cryptography Extension (JCE) Unlimited Strength 
		 * Jurisdiction Policy Files 8 installed, otherwise this cipher.init call will yield a
		 * "java.security.InvalidKeyException: Illegal key size"
		 */
		cipher.init(Cipher.DECRYPT_MODE, sessionKey, ivParamSpec);
		byte[] decrypted = cipher.doFinal(encryptedKey);

		return getPrivateKey(decrypted);
	} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
			InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException |
			NegativeArraySizeException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to decrypt private key" +
				  "\nSession key (" + (sessionKey != null ? sessionKey.getEncoded().length : 0) + " bytes): " +
				  ByteUtils.toHexString(sessionKey.getEncoded()) +
				  "\nEncrypted key (" + (encryptedKey != null ? encryptedKey.length : 0) + " bytes): " +
				  ByteUtils.toHexString(encryptedKey) +
				  "\nEncrypted key with IV (" + (encryptedKeyWithIV != null ? encryptedKeyWithIV.length : 0) + " bytes): " +
				  ByteUtils.toHexString(encryptedKey), e);
	} 
	
	return null;
}
 
Example 37
Project: RollenspielAlexaSkill   File: SimpleCrypto.java   Source Code and License 5 votes vote down vote up
private static byte[] encrypt(byte[] raw, byte[] clear) {
try {
          SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
              Cipher cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
          byte[] encrypted = cipher.doFinal(clear);
              return encrypted;
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
	throw new RuntimeException(e.toString(), e);
}
     }
 
Example 38
Project: RollenspielAlexaSkill   File: SimpleCrypto.java   Source Code and License 5 votes vote down vote up
private static byte[] decrypt(byte[] raw, byte[] encrypted) {
try {
          SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
              Cipher cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.DECRYPT_MODE, skeySpec);
          byte[] decrypted = cipher.doFinal(encrypted);
              return decrypted;
} catch (NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException e) {
	throw new RuntimeException(e.toString(), e);
}
     }
 
Example 39
Project: Mevius-IO   File: MeviusTransferPacket.java   Source Code and License 5 votes vote down vote up
public MeviusPacket getPacket(Key key) throws MeviusCipherException {
	try {
		Cipher c = Cipher.getInstance("DESede/ECB/PKCS5Padding");
		c.init(Cipher.DECRYPT_MODE, key);
		return (MeviusPacket) convertByte(obj, c);
	} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | ClassNotFoundException
			| IOException | IllegalBlockSizeException | BadPaddingException e) {
		throw new MeviusCipherException(e.getMessage());

	}
}
 
Example 40
Project: EasyAppleSyncAdapter   File: Crypto.java   Source Code and License 5 votes vote down vote up
private static byte[] cipher(byte[] data, int mode, Context ctx)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
        IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException {
    KeyManager km = new KeyManager();
    SecretKeySpec sks = new SecretKeySpec(km.getId(ctx), engine);
    IvParameterSpec iv = new IvParameterSpec(km.getIv(ctx));
    Cipher c = Cipher.getInstance(crypto);
    c.init(mode, sks, iv);
    return c.doFinal(data);
}
 
Example 41
Project: EasyAppleSyncAdapter   File: SyncServerHandlerImpl.java   Source Code and License 5 votes vote down vote up
private CalendarData getCalendarFromServer(Context context, Account account)
        throws InvalidAccountException, DavException, IOException, HttpException, NoSuchPaddingException,
        InvalidAlgorithmParameterException, NoSuchAlgorithmException, IllegalBlockSizeException,
        BadPaddingException, InvalidKeyException {

    OkHttpClient httpClient = HttpClient.create(context, account, getHttpLogger());

    return DavResourceFinder.getCalendarsData(context, account, httpClient);
}
 
Example 42
Project: Cable-Android   File: EncryptingPartOutputStream.java   Source Code and License 5 votes vote down vote up
private Cipher initializeCipher(Mac mac, SecretKeySpec key) throws IOException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException {
  Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  cipher.init(Cipher.ENCRYPT_MODE, key);

  byte[] ivBytes = cipher.getIV();
  mac.update(ivBytes);
  super.write(ivBytes, 0, ivBytes.length);

  return cipher;
}
 
Example 43
Project: xlight_android_native   File: Crypto.java   Source Code and License 5 votes vote down vote up
@SuppressLint("TrulyRandom")
static byte[] encryptWithKey(byte[] inputData, PublicKey publicKey) throws CryptoException {
    try {
        @SuppressLint("GetInstance")  // the warning doesn't apply to how we're using this
                Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(inputData);

    } catch (NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
            | InvalidKeyException | BadPaddingException e) {
        log.e("Error while encrypting bytes: ", e);
        throw new CryptoException(e);
    }
}
 
Example 44
Project: ipack   File: CipherSpi.java   Source Code and License 5 votes vote down vote up
private void initFromSpec(
    OAEPParameterSpec pSpec)
    throws NoSuchPaddingException
{
    MGF1ParameterSpec mgfParams = (MGF1ParameterSpec)pSpec.getMGFParameters();
    Digest digest = DigestFactory.getDigest(mgfParams.getDigestAlgorithm());
    
    if (digest == null)
    {
        throw new NoSuchPaddingException("no match on OAEP constructor for digest algorithm: "+ mgfParams.getDigestAlgorithm());
    }

    cipher = new OAEPEncoding(new RSABlindedEngine(), digest, ((PSource.PSpecified)pSpec.getPSource()).getValue());
    paramSpec = pSpec;
}
 
Example 45
Project: jdk8u-jdk   File: PBECipherWrapper.java   Source Code and License 5 votes vote down vote up
public Legacy(String algo, String passwd)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeySpecException {
    super(algo, PBE_SALT_SIZE);

    SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.split("/")[0]);
    key = skf.generateSecret(new PBEKeySpec(passwd.toCharArray()));

    aps = new PBEParameterSpec(getSalt(), ITERATION_COUNT);

    ci = Cipher.getInstance(algo);
}
 
Example 46
Project: jdk8u-jdk   File: SecKFTranslateTest.java   Source Code and License 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);
    }

}
 
Example 47
Project: openjdk-jdk10   File: PreferredProviderNegativeTest.java   Source Code and License 5 votes vote down vote up
public static void afterJCESet(String value, String expected)
        throws NoSuchAlgorithmException, NoSuchPaddingException {
    String[] arrays = value.split(":");
    Cipher cipher = Cipher.getInstance(arrays[0]);

    Security.setProperty(SEC_PREF_PROP, value);
    if (!cipher.getProvider().getName().equals(expected)) {
        throw new RuntimeException("Test Failed:The security property can't"
                + " be updated after JCE load.");
    }
    System.out.println("Test Pass");
}
 
Example 48
Project: Phoenix-for-VK   File: CryptHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Decrypt text using private key.
 *
 * @param text :encrypted text
 * @param key  :The private key
 * @return plain text
 * @throws java.lang.Exception
 */
public static String decryptRsa(byte[] text, PrivateKey key) throws InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException {
    byte[] dectyptedText;

    // get an RSA cipher object and print the provider
    final Cipher cipher = Cipher.getInstance("RSA");

    // decrypt the text using the private key
    cipher.init(Cipher.DECRYPT_MODE, key);
    dectyptedText = cipher.doFinal(text);
    return new String(dectyptedText);
}
 
Example 49
Project: privacyidea-authenticator   File: EncryptionHelper.java   Source Code and License 5 votes vote down vote up
static byte[] encrypt(SecretKey secretKey, byte[] plaintext)
        throws NoSuchPaddingException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException,
        IllegalBlockSizeException, UnsupportedEncodingException, InvalidAlgorithmParameterException {
    final byte[] iv = new byte[AppConstants.IV_LENGTH];
    new SecureRandom().nextBytes(iv);
    byte[] cipherText = encrypt(secretKey, new IvParameterSpec(iv), plaintext);
    byte[] combined = new byte[iv.length + cipherText.length];
    System.arraycopy(iv, 0, combined, 0, iv.length);
    System.arraycopy(cipherText, 0, combined, iv.length, cipherText.length);
    return combined;
}
 
Example 50
Project: Cable-Android   File: MasterCipher.java   Source Code and License 5 votes vote down vote up
private Cipher getDecryptingCipher(SecretKeySpec key, byte[] encryptedBody) throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException {
  //		Cipher cipher      = Cipher.getInstance("AES/CBC/PKCS5Padding");
  IvParameterSpec iv = new IvParameterSpec(encryptedBody, 0, decryptingCipher.getBlockSize());
  decryptingCipher.init(Cipher.DECRYPT_MODE, key, iv);

  return decryptingCipher;
}
 
Example 51
Project: PeSanKita-android   File: DecryptingPartInputStream.java   Source Code and License 5 votes vote down vote up
private Cipher initializeCipher(SecretKeySpec key) 
  throws InvalidKeyException, InvalidAlgorithmParameterException, 
         NoSuchAlgorithmException, NoSuchPaddingException, IOException 
{
  Cipher cipher      = Cipher.getInstance("AES/CBC/PKCS5Padding");
  IvParameterSpec iv = readIv(cipher.getBlockSize());
  cipher.init(Cipher.DECRYPT_MODE, key, iv);

  return cipher;
}
 
Example 52
Project: iroha-demo-android   File: AccountRegisterPresenter.java   Source Code and License 5 votes vote down vote up
public View.OnClickListener onRegisterClicked() {
    return new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final Context context = accountRegisterView.getContext();
            final String alias = accountRegisterView.getAlias();

            if (alias.isEmpty()) {
                accountRegisterView.showError(
                        ErrorMessageFactory.create(context, new RequiredArgumentException(), context.getString(R.string.name))
                );
                return;
            }

            accountRegisterView.showProgress();

            KeyPair keyPair = KeyGenerator.createKeyPair();
            try {
                keyPair.save(context);
            } catch (InvalidKeyException | NoSuchAlgorithmException | KeyStoreException
                    | NoSuchPaddingException | IOException e) {
                Log.e(TAG, "onClick: ", e);
                Crashlytics.log(Log.ERROR, AccountRegisterPresenter.TAG, e.getMessage());
            }
            register(keyPair, alias);
        }
    };
}
 
Example 53
Project: Limitart   File: SymmetricEncryptionUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 加密端构造函数
 * 
 * @param password
 * @param ivStr
 * @throws NoSuchPaddingException
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 * @throws InvalidKeyException
 */
private SymmetricEncryptionUtil(String password, String ivStr) throws NoSuchAlgorithmException,
		NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException {
	byte[] bytes = password.getBytes(CharsetUtil.UTF_8);
	byte[] resultKey = new byte[0X10];
	System.arraycopy(bytes, 0, resultKey, 0, Math.min(resultKey.length, bytes.length));
	generateKey = new SecretKeySpec(resultKey, ALGORITHM);
	if (ivStr != null) {
		// 初始化16位向量
		this.iv = new byte[0X10];
		byte[] ivRaw = ivStr.getBytes(CharsetUtil.UTF_8);
		System.arraycopy(ivRaw, 0, this.iv, 0, Math.min(this.iv.length, ivRaw.length));
	}
}
 
Example 54
Project: openjdk-jdk10   File: XMLCipher.java   Source Code and License 5 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 55
Project: quilt   File: Aes256BitKeysizeTest.java   Source Code and License 5 votes vote down vote up
@Test
public final void test256bitKey()
    throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {

  SecureRandom sr = SecureRandom.getInstanceStrong();
  byte[] nonce = new byte[16];
  sr.nextBytes(nonce);

  KeyGenerator keygen = KeyGenerator.getInstance("AES");
  keygen.init(256);
  byte[] key = keygen.generateKey().getEncoded();

  byte[] data = new byte[256];
  sr.nextBytes(data);

  Cipher cipher = Cipher.getInstance("AES/GCM/PKCS5Padding");
  GCMParameterSpec paramSpec = new GCMParameterSpec(128, nonce);

  try {
    cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), paramSpec);
    cipher.doFinal(data);
  } catch (InvalidKeyException e) {
    throw new InterledgerRuntimeException("Error loading 256bit key. "
        + "Likley cause is missing Unlimited Strength Jurisdiction Policy Files.", e);
  }

}
 
Example 56
Project: iroha-demo-android   File: WalletPresenter.java   Source Code and License 5 votes vote down vote up
private String getUuid() {
    final Context context = walletView.getContext();
    final String uuid;
    try {
        uuid = Account.getUuid(context);
    } catch (NoSuchPaddingException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException | InvalidKeyException | IOException e) {
        Crashlytics.log(Log.ERROR, AssetSenderPresenter.TAG, e.getMessage());
        walletView.showError(ErrorMessageFactory.create(context, e), e);
        return null;
    }
    return uuid;
}
 
Example 57
Project: xrd4j   File: AbstractEncrypter.java   Source Code and License 5 votes vote down vote up
/**
 * Encrypts the given string and returns it as a base 64 encoded string.
 *
 * @param plainText string to be encrypted
 * @return encrypted plainText as base 64 encoded string
 */
public String encrypt(String plainText) {
    try {
        byte[] decrypted = plainText.getBytes(StandardCharsets.UTF_8);
        byte[] encrypted = encrypt(decrypted);
        return CryptoHelper.encodeBase64(encrypted);
    } catch (NoSuchAlgorithmException | InvalidKeyException | InvalidAlgorithmParameterException
        | NoSuchPaddingException | IllegalBlockSizeException | BadPaddingException ex) {
        LOGGER.error(ex.getMessage(), ex);
        return null;
    }
}
 
Example 58
Project: openjdk-jdk10   File: NativeRSACipher.java   Source Code and License 5 votes vote down vote up
@Override
protected void engineSetPadding(String padding)
        throws NoSuchPaddingException {
    // Disallow change of padding for now since currently it's explicitly
    // defined in transformation strings
    throw new NoSuchPaddingException("Unsupported padding " + padding);
}
 
Example 59
Project: GitHub   File: PubkeyUtils.java   Source Code and License 4 votes vote down vote up
public static String exportPEM(PrivateKey key, String secret) throws NoSuchAlgorithmException, InvalidParameterSpecException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, InvalidKeySpecException, IllegalBlockSizeException, IOException {
	StringBuilder sb = new StringBuilder();

	byte[] data = key.getEncoded();

	sb.append(PKCS8_START);
	sb.append('\n');

	if (secret != null) {
		byte[] salt = new byte[8];
		SecureRandom random = new SecureRandom();
		random.nextBytes(salt);

		PBEParameterSpec defParams = new PBEParameterSpec(salt, 1);
		AlgorithmParameters params = AlgorithmParameters.getInstance(key.getAlgorithm());

		params.init(defParams);

		PBEKeySpec pbeSpec = new PBEKeySpec(secret.toCharArray());

		SecretKeyFactory keyFact = SecretKeyFactory.getInstance(key.getAlgorithm());
		Cipher cipher = Cipher.getInstance(key.getAlgorithm());
		cipher.init(Cipher.WRAP_MODE, keyFact.generateSecret(pbeSpec), params);

		byte[] wrappedKey = cipher.wrap(key);

		EncryptedPrivateKeyInfo pinfo = new EncryptedPrivateKeyInfo(params, wrappedKey);

		data = pinfo.getEncoded();

		sb.append("Proc-Type: 4,ENCRYPTED\n");
		sb.append("DEK-Info: DES-EDE3-CBC,");
		sb.append(encodeHex(salt));
		sb.append("\n\n");
	}

	int i = sb.length();
	sb.append(Base64.encode(data));
	for (i += 63; i < sb.length(); i += 64) {
		sb.insert(i, "\n");
	}

	sb.append('\n');
	sb.append(PKCS8_END);
	sb.append('\n');

	return sb.toString();
}
 
Example 60
Project: wolfcrypt-jni   File: WolfCryptCipherTest.java   Source Code and License 4 votes vote down vote up
@Test
public void testAesCbcNoPaddingWithOddUpdateFail()
    throws NoSuchProviderException, NoSuchAlgorithmException,
           NoSuchPaddingException, InvalidKeyException,
           IllegalBlockSizeException, InvalidAlgorithmParameterException,
           BadPaddingException {

    byte key[] = new byte[] {
        (byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33,
        (byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37,
        (byte)0x38, (byte)0x39, (byte)0x61, (byte)0x62,
        (byte)0x63, (byte)0x64, (byte)0x65, (byte)0x66
    };

    byte iv[] = new byte[] {
        (byte)0x31, (byte)0x32, (byte)0x33, (byte)0x34,
        (byte)0x35, (byte)0x36, (byte)0x37, (byte)0x38,
        (byte)0x39, (byte)0x30, (byte)0x61, (byte)0x62,
        (byte)0x63, (byte)0x64, (byte)0x65, (byte)0x66
    };

    byte input[] = new byte[] {
        (byte)0x01, (byte)0x02, (byte)0x03, (byte)0x04,
        (byte)0x05, (byte)0x06, (byte)0x07, (byte)0x08,
        (byte)0x09, (byte)0x10, (byte)0x11, (byte)0x12,
        (byte)0x13, (byte)0x14, (byte)0x15, (byte)0x16,
        (byte)0x17, (byte)0x18, (byte)0x19, (byte)0x20,
    };

    byte tmp[];

    if (!enabledJCEAlgos.contains("AES/CBC/NoPadding")) {
        /* bail out if AES is not enabled */
        return;
    }

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

    /* test that doFinal on non-block size input fails */
    tmp = cipher.update(Arrays.copyOfRange(input, 0, 8));        /* 8 */
    assertArrayEquals(tmp, null);
    tmp = cipher.update(Arrays.copyOfRange(input, 8, 12));       /* 4 */
    assertArrayEquals(tmp, null);
    tmp = cipher.update(Arrays.copyOfRange(input, 12, 16));      /* 4 */
    assertEquals(tmp.length, 16);

    try {
        tmp = cipher.doFinal(Arrays.copyOfRange(input, 16, 20)); /* 4 */
        fail("cipher.doFinal on odd size block cipher input should " +
             "throw exception");
    } catch (IllegalBlockSizeException e) {
        assertEquals(e.getMessage(),
                     "Input length not multiple of 16 bytes");
    }
}