Java Code Examples for javax.crypto.Cipher

The following are top voted examples for showing how to use javax.crypto.Cipher. 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: GOF   File: AesEncryptionStrategy.java   View source code 7 votes vote down vote up
@Override
public void encryptData(String plaintext) {
   System.out.println("-------Encrypting data using AES algorithm-------");
   try {
       KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
       keyGenerator.init(128);
       SecretKey secretKey = keyGenerator.generateKey();
       byte[] plaintTextByteArray = plaintext.getBytes("UTF8");

       Cipher cipher = Cipher.getInstance("AES");
       cipher.init(Cipher.ENCRYPT_MODE, secretKey);
       byte[] cipherText = cipher.doFinal(plaintTextByteArray);

       System.out.println("Original data: " + plaintext);
       System.out.println("Encrypted data:");
       for (int i = 0; i < cipherText.length; i++) {
           System.out.print(cipherText[i] + " ");

       }
   }
       catch(Exception ex){
           ex.printStackTrace();
       }
   }
 
Example 2
Project: cas4.0.x-server-wechat   File: EncryptedMapDecorator.java   View source code 6 votes vote down vote up
protected String decrypt(final String value, final String hashedKey) {
    if (value == null) {
        return null;
    }

    try {
        final Cipher cipher = getCipherObject();
        final byte[] ivCiphertext = decode(value.getBytes());
        final int ivSize = byte2int(Arrays.copyOfRange(ivCiphertext, 0, INTEGER_LEN));
        final byte[] ivValue = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN, (INTEGER_LEN + ivSize));
        final byte[] ciphertext = Arrays.copyOfRange(ivCiphertext, INTEGER_LEN + ivSize, ivCiphertext.length);
        final IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
        
        cipher.init(Cipher.DECRYPT_MODE, this.key, ivSpec);

        final byte[] plaintext = cipher.doFinal(ciphertext);

        return new String(plaintext);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Project: Android_Code_Arbiter   File: SafeApacheCamelCipherPair.java   View source code 6 votes vote down vote up
public SafeApacheCamelCipherPair(String transformation)
        throws GeneralSecurityException {
    this.transformation = transformation;

    int d = transformation.indexOf('/');
    String cipherName;
    if (d > 0) {
        cipherName = transformation.substring(0, d);
    } else {
        cipherName = transformation;
    }
    KeyGenerator keygen = KeyGenerator.getInstance(cipherName);
    keygen.init(new SecureRandom());
    Key key = keygen.generateKey();
    this.enccipher = Cipher.getInstance(transformation);
    this.deccipher = Cipher.getInstance(transformation);
    this.enccipher.init(1, key);
    byte[] ivp = this.enccipher.getIV();
    this.deccipher.init(2, key, ivp == null ? null : new IvParameterSpec(ivp));
}
 
Example 4
Project: jdk8u-jdk   File: ConstructKeys.java   View source code 6 votes vote down vote up
static final Key constructKey(byte[] encoding, String keyAlgorithm,
                              int keyType)
    throws InvalidKeyException, NoSuchAlgorithmException {
    Key result = null;
    switch (keyType) {
    case Cipher.SECRET_KEY:
        result = ConstructKeys.constructSecretKey(encoding,
                                                  keyAlgorithm);
        break;
    case Cipher.PRIVATE_KEY:
        result = ConstructKeys.constructPrivateKey(encoding,
                                                   keyAlgorithm);
        break;
    case Cipher.PUBLIC_KEY:
        result = ConstructKeys.constructPublicKey(encoding,
                                                  keyAlgorithm);
        break;
    }
    return result;
}
 
Example 5
Project: Android_Code_Arbiter   File: SafeIvGeneration.java   View source code 6 votes vote down vote up
public static void encrypt(String message) throws Exception {

        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);

        //IV
        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        //Key
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        SecretKey secretKey = generator.generateKey();

        //Encrypt
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding", "BC");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        cipher.update(message.getBytes());

        byte[] data = cipher.doFinal();
        System.out.println(HexUtil.toString(data));
    }
 
Example 6
Project: paillier   File: PaillierCipher.java   View source code 6 votes vote down vote up
/**
 * Initialises this cipher with key and a source of randomness
 */
protected void engineInit(int mode, Key key, SecureRandom random)
		throws InvalidKeyException {
	if (mode == Cipher.ENCRYPT_MODE)
		if (!(key instanceof PaillierPublicKey))
			throw new InvalidKeyException(
					"I didn't get a PaillierPublicKey. ");
		else if (mode == Cipher.DECRYPT_MODE)
			if (!(key instanceof PaillierPrivateKey))
				throw new InvalidKeyException(
						"I didn't get a PaillierPrivateKey. ");
			else
				throw new IllegalArgumentException("Bad mode: " + mode);

	stateMode = mode;
	keyPaillier = key;
	SECURE_RANDOM = random;
	int modulusLength = ((PaillierKey) key).getN().bitLength();
	calculateBlockSizes(modulusLength);
}
 
Example 7
Project: aaden-pay   File: BaofooSecurityUtil.java   View source code 6 votes vote down vote up
/**
 * aes解密-128位
 */
public static String AesDecrypt(String encryptContent, String password) {
	try {
		KeyGenerator keyGen = KeyGenerator.getInstance("AES");
		SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
		secureRandom.setSeed(password.getBytes());
		keyGen.init(128, secureRandom);
		SecretKey secretKey = keyGen.generateKey();
		byte[] enCodeFormat = secretKey.getEncoded();
		SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, key);
		return new String(cipher.doFinal(hex2Bytes(encryptContent)));
	} catch (Exception e) {
		logger.error("AesDecrypt exception", e);
		return null;
	}
}
 
Example 8
Project: openjdk-jdk10   File: ApiTest.java   View source code 6 votes vote down vote up
/**
 * Returns the algorithm supported for input mechanism.
 * @param mech Mechanism name
 * @param alg Algorithm name
 * @return Algorithm name
 */
private static String getDefaultAlg(String mech, String alg)
        throws NoSuchAlgorithmException {
    if (alg == null) {
        switch (mech) {
            case "Hash_DRBG":
            case "HMAC_DRBG":
                return "SHA-256";
            case "CTR_DRBG":
                return (Cipher.getMaxAllowedKeyLength("AES") < 256)
                        ? "AES-128" : "AES-256";
            default:
                throw new RuntimeException("Mechanism not supported");
        }
    }
    return alg;
}
 
Example 9
Project: Encryption   File: DES.java   View source code 6 votes vote down vote up
/**
     * Implementation of DES encryption
     */
    public static String encrypt(String method, byte[] key, byte[] vector, byte[] message) throws Exception {

//        generate Key
        byte[] keyBytes = generateKey(key, KEY_LEGHT);
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes, method);

//        generate Initialization Vector
        byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);

        Cipher cipher = Cipher.getInstance(method);

        if(hasInitVector(method)){
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        }

        byte[] cipherText = cipher.doFinal(message);

        return Base64.encodeToString(cipherText, Base64.DEFAULT);
    }
 
Example 10
Project: openjdk-jdk10   File: Empty.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    try {
        byte master[] = {
                0, 1, 2, 3, 4
        };
        SecretKey key = new SecretKeySpec(master, "DES");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        throw new RuntimeException("InvalidKeyException not thrown");
    } catch (java.security.InvalidKeyException ike) {
        ike.printStackTrace();
        if (ike.getMessage() != null) {
            out.println("Status -- Passed");
        } else {
            throw new RuntimeException("Error message is not expected when"
                    + " InvalidKeyException is thrown");
        }

    }
}
 
Example 11
Project: drift   File: PemReader.java   View source code 6 votes vote down vote up
private static PKCS8EncodedKeySpec readPrivateKey(File keyFile, Optional<String> keyPassword)
        throws IOException, GeneralSecurityException
{
    String content = Files.toString(keyFile, US_ASCII);

    Matcher matcher = KEY_PATTERN.matcher(content);
    if (!matcher.find()) {
        throw new KeyStoreException("found no private key: " + keyFile);
    }
    byte[] encodedKey = base64Decode(matcher.group(1));

    if (!keyPassword.isPresent()) {
        return new PKCS8EncodedKeySpec(encodedKey);
    }

    EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(encodedKey);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(encryptedPrivateKeyInfo.getAlgName());
    SecretKey secretKey = keyFactory.generateSecret(new PBEKeySpec(keyPassword.get().toCharArray()));

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

    return encryptedPrivateKeyInfo.getKeySpec(cipher);
}
 
Example 12
Project: ipack   File: JceAsymmetricValueDecryptorGenerator.java   View source code 6 votes vote down vote up
public InputDecryptor getValueDecryptor(AlgorithmIdentifier keyEncryptionAlgorithm, final AlgorithmIdentifier contentEncryptionAlgorithm, byte[] encryptedContentEncryptionKey)
    throws CRMFException
{
    Key secretKey = extractSecretKey(keyEncryptionAlgorithm, contentEncryptionAlgorithm, encryptedContentEncryptionKey);

    final Cipher dataCipher = helper.createContentCipher(secretKey, contentEncryptionAlgorithm);

    return new InputDecryptor()
    {
        public AlgorithmIdentifier getAlgorithmIdentifier()
        {
            return contentEncryptionAlgorithm;
        }

        public InputStream getInputStream(InputStream dataIn)
        {
            return new CipherInputStream(dataIn, dataCipher);
        }
    };
}
 
Example 13
Project: GitHub   File: DESUtil.java   View source code 6 votes vote down vote up
/**
 * DES算法,加密
 *
 * @param data
 *         待加密字符串
 * @param key
 *            加密私钥,长度不能够小于8位
 * @return 加密后的字节数组,一般结合Base64编码使用

 * @throws Exception
 */
public static String encode(String key, String data) {
    if (data == null)
        return null;
    try {
        DESKeySpec dks = new DESKeySpec(key.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // key的长度不能够小于8位字节
        Key secretKey = keyFactory.generateSecret(dks);
        Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
        IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
        AlgorithmParameterSpec paramSpec = iv;
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);
        byte[] bytes = cipher.doFinal(data.getBytes());
        return byte2String(bytes);
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example 14
Project: BaseClient   File: CryptManager.java   View source code 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 15
Project: Encryption   File: PBE.java   View source code 6 votes vote down vote up
/**
     * Implementation of PBE encryption
     */
    public static String encrypt(Method method, byte[] key, KeySize keySize, byte[] vector, byte[] message) throws Exception{

//        generate Key
        byte[] keyBytes = generateKey(key, keySize.getSize());
        SecretKeySpec keySpec = new SecretKeySpec(keyBytes , method.getMethod());

//        generate Initialization Vector
        byte[] keyBytesIv = generateVector(vector, VECTOR_LEGHT);
        IvParameterSpec ivSpec = new IvParameterSpec(keyBytesIv);

        Cipher cipher = Cipher.getInstance(method.getMethod());

        if(hasInitVector(method.getMethod())){
            cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        }

        byte[] cipherText = cipher.doFinal(message);

        return Base64.encodeToString(cipherText, Base64.DEFAULT);
    }
 
Example 16
Project: JAddOn   File: RSA.java   View source code 6 votes vote down vote up
/**
 * Decrypts a message with a private key
 * @param chiffrat byte Array encrypted text to decrypt
 * @param pk PrivateKey Key for the decryption
 * @return String Decrypted message
 */
public String decrypt(byte[] chiffrat, PrivateKey pk) {
    if(!isMessageLengthValid(chiffrat)) {
        StaticStandard.logErr("Chiffrat must not be longer than " + maximum_message_length + " bytes");
        return null;
    }
    try {
        final Cipher cipher = Cipher.getInstance(RSA);
        cipher.init(Cipher.DECRYPT_MODE, pk);
        String message = new String(cipher.doFinal(chiffrat));
        return message;
    } catch (Exception ex) {
        StaticStandard.logErr("Error while decrypting message: " + ex);
        return null;
    }
}
 
Example 17
Project: jdk8u-jdk   File: Signature.java   View source code 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 18
Project: TIIEHenry-Android-SDK   File: DESUtils.java   View source code 6 votes vote down vote up
/**
 * DES
 * @param src
 * @param password
 * @return
 */
public static byte[] decrypt(byte []src, String password) {
    try {
        // DES算法要求有一个可信任的随机数源
        SecureRandom random = new SecureRandom();
        // 创建一个DESKeySpec对象
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        // 创建一个密匙工厂
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        // 将DESKeySpec对象转换成SecretKey对象
        SecretKey securekey = keyFactory.generateSecret(desKey);
        // Cipher对象实际完成解密操作
        Cipher cipher = Cipher.getInstance("DES");
        // 用密匙初始化Cipher对象
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        // 真正开始解密操作
        return cipher.doFinal(src);
    } catch (Throwable e) {
        e.printStackTrace();
    }

    return null;
}
 
Example 19
Project: alfresco-core   File: AbstractEncryptor.java   View source code 6 votes vote down vote up
@Override
public Serializable sealObject(String keyAlias, AlgorithmParameters params, Serializable input)
{
    if (input == null)
    {
        return null;
    }
    Cipher cipher = getCipher(keyAlias, params, Cipher.ENCRYPT_MODE);
    if (cipher == null)
    {
        return input;
    }
    try
    {
        return new SealedObject(input, cipher);
    }
    catch (Exception e)
    {
        throw new AlfrescoRuntimeException("Failed to seal object", e);
    }
}
 
Example 20
Project: openjdk-jdk10   File: Turkish.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    Locale reservedLocale = Locale.getDefault();
    try {
        Locale.setDefault(new Locale("tr", "TR"));

        System.out.println(Cipher.getInstance("RSA/ECB/PKCS1Padding"));
        System.out.println(Cipher.getInstance("RSA/ECB/PKCS1PADDING"));
        System.out.println(Cipher.getInstance("rsa/ecb/pkcs1padding"));
        System.out.println(Cipher.getInstance("Blowfish"));
        System.out.println(Cipher.getInstance("blowfish"));
        System.out.println(Cipher.getInstance("BLOWFISH"));

        System.out.println("OK");
    } finally {
        // restore the default locale
        Locale.setDefault(reservedLocale);
    }
}
 
Example 21
Project: OpenJSharp   File: KeyProtector.java   View source code 6 votes vote down vote up
/**
 * Seals the given cleartext key, using the password provided at
 * construction time
 */
SealedObject seal(Key key)
    throws Exception
{
    // create a random salt (8 bytes)
    byte[] salt = new byte[8];
    SunJCE.getRandom().nextBytes(salt);

    // create PBE parameters from salt and iteration count
    PBEParameterSpec pbeSpec = new PBEParameterSpec(salt, 20);

    // create PBE key from password
    PBEKeySpec pbeKeySpec = new PBEKeySpec(this.password);
    SecretKey sKey = new PBEKey(pbeKeySpec, "PBEWithMD5AndTripleDES");
    pbeKeySpec.clearPassword();

    // seal key
    Cipher cipher;

    PBEWithMD5AndTripleDESCipher cipherSpi;
    cipherSpi = new PBEWithMD5AndTripleDESCipher();
    cipher = new CipherForKeyProtector(cipherSpi, SunJCE.getInstance(),
                                       "PBEWithMD5AndTripleDES");
    cipher.init(Cipher.ENCRYPT_MODE, sKey, pbeSpec);
    return new SealedObjectForKeyProtector(key, cipher);
}
 
Example 22
Project: springboot-shiro-cas-mybatis   File: Cas30ResponseViewTests.java   View source code 6 votes vote down vote up
private String decryptCredential(final String cred) {
    try {
        final PrivateKeyFactoryBean factory = new PrivateKeyFactoryBean();
        factory.setAlgorithm("RSA");
        factory.setLocation(new ClassPathResource("RSA1024Private.p8"));
        factory.setSingleton(false);
        final PrivateKey privateKey = factory.getObject();

        logger.debug("Initializing cipher based on [{}]", privateKey.getAlgorithm());
        final Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());

        logger.debug("Decoding value [{}]", cred);
        final byte[] cred64 = CompressionUtils.decodeBase64ToByteArray(cred);

        logger.debug("Initializing decrypt-mode via private key [{}]", privateKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        final byte[] cipherData = cipher.doFinal(cred64);
        return new String(cipherData);
    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 23
Project: pivaa   File: Encryption.java   View source code 6 votes vote down vote up
/**
 * Decrypt DATA
 * @param encryptedBase64
 * @return
 */
public static String decryptAES_ECB_PKCS5Padding(String encryptedBase64) {
    try {
        byte[] IV = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
        IvParameterSpec iv = new IvParameterSpec(IV);

        byte[] key = {
                1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1
        };
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);

        Base64 b64 = new Base64();
        byte[] encryptedBase64Bytes = encryptedBase64.getBytes();
        byte[] original = cipher.doFinal(b64.decodeBase64(encryptedBase64Bytes));

        return new String(original);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return null;
}
 
Example 24
Project: openjdk-jdk10   File: PBECipherWrapper.java   View source code 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 25
Project: nifi-registry   File: NiFiRegistryPropertiesLoader.java   View source code 5 votes vote down vote up
private static String getDefaultProviderKey() {
    try {
        return "aes/gcm/" + (Cipher.getMaxAllowedKeyLength("AES") > 128 ? "256" : "128");
    } catch (NoSuchAlgorithmException e) {
        return "aes/gcm/128";
    }
}
 
Example 26
Project: RISE-V2G   File: SecurityUtils.java   View source code 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 27
Project: Progetto-A   File: Criptazione.java   View source code 5 votes vote down vote up
/**
* decripta il messaggio
* 
* @param message messaggio per la decritptazione
* @return stringa decriptata
* @throws Exception 
*/
 private String decrypt(String message) throws Exception {
   byte[] bytesrc = convertHexString(message);
   Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
   DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
   SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
   SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
   IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));

   cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
   byte[] retByte = cipher.doFinal(bytesrc);
   return new String(retByte);
 }
 
Example 28
Project: iBase4J-Common   File: RSACoder.java   View source code 5 votes vote down vote up
/**
 * 公钥加密
 * 
 * @param data 待加密数据
 * @param key 公钥
 * @return byte[] 加密数据
 * @throws Exception
 */
public static byte[] encryptByPublicKey(byte[] data, byte[] key) throws Exception {
	// 取得公钥
	X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
	// 对数据加密
	Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
	cipher.init(Cipher.ENCRYPT_MODE, publicKey);
	return cipher.doFinal(data);
}
 
Example 29
Project: boohee_v5.6   File: e.java   View source code 5 votes vote down vote up
public static byte[] a(String str, byte[] bArr) {
    byte[] bArr2 = null;
    try {
        Key secretKeySpec = new SecretKeySpec(str.getBytes(), "DESede");
        AlgorithmParameterSpec ivParameterSpec = new IvParameterSpec(new byte[8]);
        Cipher instance = Cipher.getInstance(a);
        instance.init(1, secretKeySpec, ivParameterSpec);
        bArr2 = instance.doFinal(bArr);
    } catch (Exception e) {
    }
    return bArr2;
}
 
Example 30
Project: dracoon-dropzone   File: CryptoUtil.java   View source code 5 votes vote down vote up
private byte[] encrypt(byte[] plainText, byte[] key, byte[] initialVector)
		throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
		InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
	Cipher cipher = Cipher.getInstance(cipherTransformation);
	SecretKeySpec secretKeySpec = new SecretKeySpec(key, aesEncryptionAlgorithm);
	IvParameterSpec ivParameterSpec = new IvParameterSpec(initialVector);
	cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
	plainText = cipher.doFinal(plainText);
	return plainText;
}
 
Example 31
Project: ModuleFrame   File: EncryptUtil.java   View source code 5 votes vote down vote up
/**
 * DES加密模板
 *
 * @param data           数据
 * @param key            秘钥
 * @param algorithm      加密算法
 * @param transformation 转变
 * @param isEncrypt      {@code true}: 加密 {@code false}: 解密
 * @return 密文或者明文,适用于DES,3DES,AES
 */
public static byte[] desTemplate(byte[] data, byte[] key, String algorithm, String transformation, boolean isEncrypt) {
    if (data == null || data.length == 0 || key == null || key.length == 0) return null;
    try {
        SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
        Cipher cipher = Cipher.getInstance(transformation);
        SecureRandom random = new SecureRandom();
        cipher.init(isEncrypt ? Cipher.ENCRYPT_MODE : Cipher.DECRYPT_MODE, keySpec, random);
        return cipher.doFinal(data);
    } catch (Throwable e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 32
Project: openjdk-jdk10   File: Encrypt.java   View source code 5 votes vote down vote up
private void combination_16(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocateDirect(0);
    emptyBuf.put(new byte[0]);
    c.updateAAD(emptyBuf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text with an empty buffer
    c.update(in, output);
    ByteBuffer emptyBuf2 = ByteBuffer.allocate(0);
    emptyBuf2.put(new byte[0]);
    c.doFinal(emptyBuf2, output);
    int resultSize = output.position();
    byte[] result16 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result16, 0, resultSize);
    results.add(result16);
}
 
Example 33
Project: openjdk-jdk10   File: CICOSkipTest.java   View source code 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 34
Project: jdk8u-jdk   File: TestOAEPPadding.java   View source code 5 votes vote down vote up
private static void testEncryptDecrypt(OAEPParameterSpec spec,
        int dataLength) throws Exception {

    System.out.print("Testing OAEP with hash ");
    if (spec != null) {
        System.out.print(spec.getDigestAlgorithm() + " and MGF " +
            ((MGF1ParameterSpec)spec.getMGFParameters()).
                getDigestAlgorithm());
    } else {
        System.out.print("Default");
    }
    System.out.println(", " + dataLength + " bytes");

    Cipher c = Cipher.getInstance("RSA/ECB/OAEPPadding", cp);
    if (spec != null) {
        c.init(Cipher.ENCRYPT_MODE, publicKey, spec);
    } else {
        c.init(Cipher.ENCRYPT_MODE, publicKey);
    }

    byte[] data = new byte[dataLength];
    byte[] enc = c.doFinal(data);
    if (spec != null) {
        c.init(Cipher.DECRYPT_MODE, privateKey, spec);
    } else {
        c.init(Cipher.DECRYPT_MODE, privateKey);
    }
    byte[] dec = c.doFinal(enc);
    if (Arrays.equals(data, dec) == false) {
        throw new Exception("Data does not match");
    }
}
 
Example 35
Project: fussroll   File: AESEncryption.java   View source code 5 votes vote down vote up
static String encrypt(String data) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    Key key = generateKey();
    Cipher cipher = Cipher.getInstance(algorithm);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    byte[] encryptedData = cipher.doFinal(data.getBytes());
    return (encodeToString(encryptedData, 16));
}
 
Example 36
Project: InstantAppStarter   File: ObscuredSharedPreferences.java   View source code 5 votes vote down vote up
protected String encrypt(String value ) {

        try {
            final byte[] bytes = value!=null ? value.getBytes(UTF8) : new byte[0];
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
            SecretKey key = keyFactory.generateSecret(new PBEKeySpec(SEKRIT));
            Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
            pbeCipher.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(Secure.getString(context.getContentResolver(), Secure.ANDROID_ID).getBytes(UTF8), 20));
            return new String(Base64.encode(pbeCipher.doFinal(bytes), Base64.NO_WRAP),UTF8);
        } catch( Exception e ) {
            throw new RuntimeException(e);
        }

    }
 
Example 37
Project: jdk8u-jdk   File: Encrypt.java   View source code 5 votes vote down vote up
private void combination_16(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer to test
    ByteBuffer buf = ByteBuffer.allocateDirect(AAD.length);
    buf.put(AAD);
    buf.position(0);
    buf.limit(AAD.length);
    c.updateAAD(buf);

    // prepare empty ByteBuffer
    ByteBuffer emptyBuf = ByteBuffer.allocateDirect(0);
    emptyBuf.put(new byte[0]);
    c.updateAAD(emptyBuf);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text with an empty buffer
    c.update(in, output);
    ByteBuffer emptyBuf2 = ByteBuffer.allocate(0);
    emptyBuf2.put(new byte[0]);
    c.doFinal(emptyBuf2, output);
    int resultSize = output.position();
    byte[] result16 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result16, 0, resultSize);
    results.add(result16);
}
 
Example 38
Project: WiFiSDCryptoLocker   File: CryptoUtils.java   View source code 5 votes vote down vote up
/**
 * Decrypts the cryptoKey of the user with the given derived key
 *
 * @param derivedKey derived key of the user
 * @param user       the user for which the cryptoKey should be decrypted
 * @return the decrypted cryptoKey
 * @throws GeneralSecurityException in case of an error
 */
private static SecretKey decryptCryptoKey(byte[] derivedKey, User user) throws GeneralSecurityException {

    Cipher cipher = Cipher.getInstance(AES_CTR_NO_PADDING, BOUNCY_CASTLE);
    SecretKey derivedKeySecretKey = new SecretKeySpec(derivedKey, 0, derivedKey.length, AES);
    cipher.init(Cipher.DECRYPT_MODE, derivedKeySecretKey, new IvParameterSpec(user.getCryptoKeyIV()));
    byte[] encryptionKeyDecrypted = cipher.doFinal(user.getCryptoKey());

    return new SecretKeySpec(encryptionKeyDecrypted, 0, encryptionKeyDecrypted.length, AES);
}
 
Example 39
Project: Leanplum-Android-SDK   File: AESCrypt.java   View source code 5 votes vote down vote up
/**
 * Encrypts the plaintext using password. In case of exception, returns null.
 */
// VisibleForTesting
public static String encryptInternal(String password, String plaintext) {
  try {
    return Arrays.toString(performCryptOperation(Cipher.ENCRYPT_MODE, password,
        plaintext.getBytes("UTF-8")));
  } catch (UnsupportedEncodingException e) {
    Log.w("Unable to encrypt " + plaintext, e);
    return null;
  }
}
 
Example 40
Project: ibm-cos-sdk-java   File: CryptoRuntime.java   View source code 5 votes vote down vote up
private static boolean check() {
    try {
        Cipher.getInstance(
                ContentCryptoScheme.AES_GCM.getCipherAlgorithm(),
                BOUNCY_CASTLE_PROVIDER);
        return true;
    } catch (Exception e) {
        return false;
    }
}