Java Code Examples for javax.crypto.Cipher#getInstance()

The following examples show how to use javax.crypto.Cipher#getInstance() . 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: DES.java    From AndroidStudyDemo with GNU General Public License v2.0 6 votes vote down vote up
/**
 * DES算法,解密
 * @param data 待解密字符串
 * @param key 解密私钥,长度不能够小于8位
 * @return 解密后的字节数组
 * @throws Exception 异常
 */
public static String decode(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.DECRYPT_MODE, secretKey, paramSpec);
        return new String(cipher.doFinal(byte2hex(data.getBytes())));
    } catch (Exception e) {
        e.printStackTrace();
        return data;
    }
}
 
Example 2
Source File: CipherTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Several exceptions can be thrown by init. Check that in this case we throw the right one,
 * as the error could fall under the umbrella of other exceptions.
 * http://b/18987633
 */
public void testCipher_init_DoesNotSupportKeyClass_throwsInvalidKeyException()
        throws Exception {
    Provider mockProvider = new MockProvider("MockProvider") {
        public void setup() {
            put("Cipher.FOO", MockCipherSpi.AllKeyTypes.class.getName());
            put("Cipher.FOO SupportedKeyClasses", "none");
        }
    };

    Security.addProvider(mockProvider);
    try {
        Cipher c = Cipher.getInstance("FOO");
        c.init(Cipher.DECRYPT_MODE, new MockKey());
        fail("Expected InvalidKeyException");
    } catch (InvalidKeyException expected) {
    } finally {
        Security.removeProvider(mockProvider.getName());
    }
}
 
Example 3
Source File: EbicsUserService.java    From axelor-open-suite with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * EBICS IG CFONB VF 2.1.4 2012 02 24 - 2.1.3.2 Calcul de la signature:
 *
 * <p>Il convient d’utiliser PKCS1 V1.5 pour chiffrer la clé de chiffrement.
 *
 * <p>EBICS Specification 2.4.2 - 15.2 Workflows at the recipient’s end:
 *
 * <p><b>Decryption of the DES key</b>
 *
 * <p>The leading 256 null bits of the EDEK are removed and the remaining 768 bits are decrypted
 * with the recipient’s secret key of the RSA key system. PDEK is then present. The secret DES key
 * DEK is obtained from the lowest-value 128 bits of PDEK, this is split into the individual keys
 * DEK<SUB>left</SUB> and DEK<SUB>right</SUB>.
 */
public byte[] decrypt(EbicsUser user, byte[] encryptedData, byte[] transactionKey)
    throws AxelorException, GeneralSecurityException, IOException {
  Cipher cipher;
  int blockSize;
  ByteArrayOutputStream outputStream;

  cipher = Cipher.getInstance("RSA/NONE/PKCS1Padding", BouncyCastleProvider.PROVIDER_NAME);
  cipher.init(
      Cipher.DECRYPT_MODE, ebicsService.getPrivateKey(user.getE002Certificate().getPrivateKey()));
  blockSize = cipher.getBlockSize();
  outputStream = new ByteArrayOutputStream();
  for (int j = 0; j * blockSize < transactionKey.length; j++) {
    outputStream.write(cipher.doFinal(transactionKey, j * blockSize, blockSize));
  }

  return decryptData(encryptedData, outputStream.toByteArray());
}
 
Example 4
Source File: CipherStorageAndroidKeystore.java    From keystore-ultimate with Apache License 2.0 6 votes vote down vote up
private static byte[] encryptString(Key key, String value) throws CryptoFailedException {
    try {
        Cipher cipher = Cipher.getInstance(ENCRYPTION_TRANSFORMATION);
        cipher.init(Cipher.ENCRYPT_MODE, key);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        // write initialization vector to the beginning of the stream
        byte[] iv = cipher.getIV();
        outputStream.write(iv, 0, iv.length);
        // encrypt the value using a CipherOutputStream
        CipherOutputStream cipherOutputStream = new CipherOutputStream(outputStream, cipher);
        cipherOutputStream.write(value.getBytes(DEFAULT_CHARSET));
        cipherOutputStream.close();
        return outputStream.toByteArray();
    } catch (IOException | NoSuchAlgorithmException | InvalidKeyException | NoSuchPaddingException e) {
        throw new CryptoFailedException("Could not encrypt value", e);
    }
}
 
Example 5
Source File: StringCrypter.java    From mzmine2 with GNU General Public License v2.0 6 votes vote down vote up
public String decrypt(String encrypted) throws DecryptionException {
    if (encrypted == null || encrypted.isEmpty()) {
        LOGGER.warning("Skipped empty decryption try.");
        return encrypted;
    }

    try {
        byte[] crypted2 = base64Decode(encrypted);

        Cipher cipher = Cipher.getInstance(CRYPT_METHOD);
        cipher.init(Cipher.DECRYPT_MODE, PRIVATE_KEY);
        byte[] cipherData2 = cipher.doFinal(crypted2);
        return new String(cipherData2);
    } catch (IOException | NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
        throw new DecryptionException(e);
    }
}
 
Example 6
Source File: GXDLMSSecureClient.java    From gurux.dlms.java with GNU General Public License v2.0 6 votes vote down vote up
public static Cipher getCipher(final boolean encrypt, final byte[] kek)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, InvalidAlgorithmParameterException {
    GXByteBuffer iv = new GXByteBuffer();
    // iv.set(IV);

    // iv.set(p.getSystemTitle());
    // iv.setUInt32(p.getInvocationCounter());
    SecretKeySpec eks = new SecretKeySpec(kek, "AES");
    Cipher c = Cipher.getInstance("AES/GCM/NoPadding");
    int mode;
    if (encrypt) {
        mode = Cipher.ENCRYPT_MODE;
    } else {
        mode = Cipher.DECRYPT_MODE;
    }
    c.init(mode, eks, new GCMParameterSpec(12 * 8, iv.array()));
    return c;
}
 
Example 7
Source File: AESUtils.java    From common-mvc with MIT License 5 votes vote down vote up
public static String encrypt(String content, String keyWord) throws Exception {
    if(null == content || null == keyWord) throw new RuntimeException("参数错误");
    if(16 != keyWord.length()) throw new RuntimeException("keyWord必须为16位字符");

    try {
        SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(IV.getBytes()));
        byte[] encryptedData = cipher.doFinal(content.getBytes("UTF-8"));
        return parseByte2HexStr(encryptedData);
    } catch (Exception e) {
        throw new Exception("加密失败");
    }
}
 
Example 8
Source File: XMLCipher.java    From jdk1.8-source-analysis with Apache License 2.0 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 9
Source File: AesDkCrypto.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
protected Cipher getCipher(byte[] key, byte[] ivec, int mode)
    throws GeneralSecurityException {

    // IV
    if (ivec == null) {
       ivec = ZERO_IV;
    }
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
    IvParameterSpec encIv = new IvParameterSpec(ivec, 0, ivec.length);
    cipher.init(mode, secretKey, encIv);
    return cipher;
}
 
Example 10
Source File: Tool.java    From eLong-OpenAPI-JAVA-demo with Apache License 2.0 5 votes vote down vote up
public static String encryptDES(String message, String key) throws Exception {
	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.ENCRYPT_MODE, secretKey, iv);

	return toHexString(cipher.doFinal(message.getBytes("UTF-8")));
}
 
Example 11
Source File: Encrypter.java    From stash-token-auth with GNU General Public License v3.0 5 votes vote down vote up
public Encrypter(byte[] key) throws EncryptionException {
  try {
    secretKey = new SecretKeySpec(key, "AES");
    ecipher = Cipher.getInstance("AES");
    dcipher = Cipher.getInstance("AES");
    ecipher.init(Cipher.ENCRYPT_MODE, secretKey);
    dcipher.init(Cipher.DECRYPT_MODE, secretKey);
  } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException e) {
    throw new EncryptionException("Could not initialize secret key", e);
  }
}
 
Example 12
Source File: CryptoUtils.java    From high-performance-java-persistence with Apache License 2.0 5 votes vote down vote up
private static Cipher getCipher() {
    try {
        return Cipher.getInstance("AES/ECB/PKCS5PADDING");
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}
 
Example 13
Source File: CryptoRuntime.java    From ibm-cos-sdk-java with Apache License 2.0 5 votes vote down vote up
private static boolean check() {
    try {
        Cipher.getInstance(RSA_ECB_OAEPWithSHA256AndMGF1Padding,
                BOUNCY_CASTLE_PROVIDER);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 14
Source File: DynamoDbEncryptor.java    From aws-dynamodb-encryption-java with Apache License 2.0 5 votes vote down vote up
private void actualDecryption(Map<String, AttributeValue> itemAttributes,
        Map<String, Set<EncryptionFlags>> attributeFlags, SecretKey encryptionKey,
        Map<String, String> materialDescription) throws GeneralSecurityException {
    final String encryptionMode = encryptionKey != null ?  encryptionKey.getAlgorithm() +
                materialDescription.get(symmetricEncryptionModeHeader) : null;
    Cipher cipher = null;
    int blockSize = -1;

    for (Map.Entry<String, AttributeValue> entry: itemAttributes.entrySet()) {
        Set<EncryptionFlags> flags = attributeFlags.get(entry.getKey());
        if (flags != null && flags.contains(EncryptionFlags.ENCRYPT)) {
            if (!flags.contains(EncryptionFlags.SIGN)) {
                throw new IllegalArgumentException("All encrypted fields must be signed. Bad field: " + entry.getKey());
            }
            ByteBuffer plainText;
            ByteBuffer cipherText = entry.getValue().b().asByteBuffer();
            cipherText.rewind();
            if (encryptionKey instanceof DelegatedKey) {
                plainText = ByteBuffer.wrap(((DelegatedKey)encryptionKey).decrypt(toByteArray(cipherText), null, encryptionMode));
            } else {
                if (cipher == null) {
                    blockSize = getBlockSize(encryptionMode);
                    cipher = Cipher.getInstance(encryptionMode);
                }
                byte[] iv = new byte[blockSize];
                cipherText.get(iv);
                cipher.init(Cipher.DECRYPT_MODE, encryptionKey, new IvParameterSpec(iv), Utils.getRng());
                plainText = ByteBuffer.allocate(cipher.getOutputSize(cipherText.remaining()));
                cipher.doFinal(cipherText, plainText);
                plainText.rewind();
            }
            entry.setValue(AttributeValueMarshaller.unmarshall(plainText));
        }
    }
}
 
Example 15
Source File: CipherHelper.java    From flow-platform-x with Apache License 2.0 5 votes vote down vote up
public static String decrypt(String encrypted, String secret) {
    try {
        SecretKeySpec key = new SecretKeySpec(toBytes(secret), "AES");

        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
        cipher.init(Cipher.DECRYPT_MODE, key);

        byte[] source = cipher.doFinal(Base64.getDecoder().decode(encrypted));
        return new String(source);
    } catch (Throwable e) {
        return StringHelper.EMPTY;
    }
}
 
Example 16
Source File: RSAEncryptedAlphabeticalSerializer.java    From VSerializer with GNU General Public License v2.0 5 votes vote down vote up
@Override
protected byte[] encrypt(byte[] data) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, remotePublicKey);
    byte[] cipherData = cipher.doFinal(data);
    return cipherData;
}
 
Example 17
Source File: Crypto.java    From BambooPlayer with Apache License 2.0 5 votes vote down vote up
public String rsaEncrypt(InputStream keyStream, byte[] data) {
	try {
		PublicKey pubKey = readKeyFromStream(keyStream);
		Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
		cipher.init(Cipher.ENCRYPT_MODE, pubKey);
		byte[] cipherData = cipher.doFinal(data);
		return Base64.encodeToString(cipherData, Base64.NO_WRAP);
	} catch (Exception e) {
		Log.e("rsaEncrypt", e);
		return "";
	}
}
 
Example 18
Source File: AES256.java    From NHentai-android with GNU General Public License v3.0 5 votes vote down vote up
public static String encode(String ePasK, String eConT){
	if (ePasK.length() == 0 || ePasK == null) {
		return "";
	}

	if (eConT.length() == 0 || eConT == null) {
		return "";
	}

	try {
		SecretKeySpec skeySpec = getKey(ePasK);
		byte[] clearText = eConT.getBytes("UTF8");
		
		final byte[] iv = new byte[16];
		Arrays.fill(iv, (byte) 0x00);
		IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec);

		String encrypedValue = Base64.encodeToString(cipher.doFinal(clearText), Base64.DEFAULT);
		return encrypedValue;

	} catch (Exception e) {
		if (QKVConfig.DEBUG){
			e.printStackTrace();
		}
	}
	return "";
}
 
Example 19
Source File: RSAUtils.java    From mpush-client-java with Apache License 2.0 3 votes vote down vote up
/**
 * 公钥加密
 *
 * @param data data      源数据
 * @param publicKey publicKey 公钥(BASE64编码)
 * @return xxx
 * @throws Exception Exception
 */
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
    PublicKey key = decodePublicKey(publicKey);
    // 对数据加密
    Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_PADDING);
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return doFinal(cipher, data, MAX_ENCRYPT_BLOCK);
}
 
Example 20
Source File: Crypter.java    From SimpleServerClient with GNU General Public License v3.0 3 votes vote down vote up
/**
 * Encrypts an array of bytes using the AES algorithm
 * 
 * @param data The array of bytes to encrypt
 * @param rawKey The password to use for encryption. Warning: This password will be extended or
 *        shortened to match a length of 16 bytes (128 bit). Therefore be careful! Different
 *        passwords, starting with the same sixteen characters, result in the same AES key.
 * @return An array of bytes containing the encrypted data
 * @throws Exception If something went wrong with the AES algorithm.
 */
public static byte[] encrypt(byte[] data, String rawKey) throws Exception {
  Key key = generateKey(rawKey);
  Cipher c = Cipher.getInstance(ALGO);
  c.init(Cipher.ENCRYPT_MODE, key);
  byte[] encVal = c.doFinal(data);
  return encVal;
}