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 | 10 votes |
@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: aaden-pay File: BaofooSecurityUtil.java View source code | 7 votes |
/**
* 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 3
| Project: cas4.0.x-server-wechat File: EncryptedMapDecorator.java View source code | 6 votes |
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 4
| Project: Android_Code_Arbiter File: SafeApacheCamelCipherPair.java View source code | 6 votes |
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 5
| Project: jdk8u-jdk File: ConstructKeys.java View source code | 6 votes |
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 6
| Project: Android_Code_Arbiter File: SafeIvGeneration.java View source code | 6 votes |
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 7
| Project: openjdk-jdk10 File: ApiTest.java View source code | 6 votes |
/**
* 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 8
| Project: Encryption File: DES.java View source code | 6 votes |
/**
* 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 9
| Project: openjdk-jdk10 File: Empty.java View source code | 6 votes |
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 10
| Project: drift File: PemReader.java View source code | 6 votes |
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 11
| Project: ipack File: JceAsymmetricValueDecryptorGenerator.java View source code | 6 votes |
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 12
| Project: GitHub File: DESUtil.java View source code | 6 votes |
/**
* 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 13
| Project: BaseClient File: CryptManager.java View source code | 6 votes |
/**
* 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 14
| Project: Encryption File: PBE.java View source code | 6 votes |
/**
* 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 15
| Project: JAddOn File: RSA.java View source code | 6 votes |
/**
* 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 16
| Project: jdk8u-jdk File: Signature.java View source code | 6 votes |
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 17
| Project: TIIEHenry-Android-SDK File: DESUtils.java View source code | 6 votes |
/**
* 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 18
| Project: alfresco-core File: AbstractEncryptor.java View source code | 6 votes |
@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 19
| Project: openjdk-jdk10 File: Turkish.java View source code | 6 votes |
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 20
| Project: OpenJSharp File: KeyProtector.java View source code | 6 votes |
/**
* 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 21
| Project: springboot-shiro-cas-mybatis File: Cas30ResponseViewTests.java View source code | 6 votes |
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 22
| Project: pivaa File: Encryption.java View source code | 6 votes |
/**
* 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 23
| Project: openjdk-jdk10 File: PBECipherWrapper.java View source code | 5 votes |
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 24
| Project: nifi-registry File: NiFiRegistryPropertiesLoader.java View source code | 5 votes |
private static String getDefaultProviderKey() {
try {
return "aes/gcm/" + (Cipher.getMaxAllowedKeyLength("AES") > 128 ? "256" : "128");
} catch (NoSuchAlgorithmException e) {
return "aes/gcm/128";
}
}
Example 25
| Project: RISE-V2G File: SecurityUtils.java View source code | 5 votes |
/**
* 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()) 