private void sealedObjectTest() throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("ECIES"); kpg.initialize(new ECGenParameterSpec("secp256r1")); KeyPair keyPair = kpg.generateKeyPair(); Cipher cipher = Cipher.getInstance("ECIES"); cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic()); String toEncrypt = "Hello"; // Check that cipher works ok cipher.doFinal(toEncrypt.getBytes()); // Using a SealedObject to encrypt the same string fails with a NullPointerException SealedObject sealedObject = new SealedObject(toEncrypt, cipher); cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate()); String result = (String) sealedObject.getObject(cipher); isTrue("result wrong", result.equals(toEncrypt)); result = (String) sealedObject.getObject(keyPair.getPrivate()); isTrue("result wrong", result.equals(toEncrypt)); }
void run() throws Exception { Cipher cipher = Cipher.getInstance("RC2/ECB/NOPADDING", "SunJCE"); SecretKey keySpec = new SecretKeySpec(key, "RC2"); RC2ParameterSpec rc2Spec = new RC2ParameterSpec(effectiveKeySize); cipher.init(Cipher.ENCRYPT_MODE, keySpec, rc2Spec); byte[] enc = cipher.doFinal(plaintext); if (Arrays.equals(ciphertext, enc) == false) { System.out.println("RC2AlgorithmParameters Cipher test " + "encryption failed:"); System.out.println("plaintext: " + RC2AlgorithmParameters.toString(plaintext)); System.out.println("ciphertext: " + RC2AlgorithmParameters.toString(ciphertext)); System.out.println("encrypted: " + RC2AlgorithmParameters.toString(enc)); System.out.println("key: " + RC2AlgorithmParameters.toString(key)); System.out.println("effective key length: " + effectiveKeySize); throw new Exception("RC2AlgorithmParameters Cipher test " + "encryption failed"); } enc = cipher.doFinal(plaintext); if (Arrays.equals(ciphertext, enc) == false) { throw new Exception("Re-encryption test failed"); } cipher.init(Cipher.DECRYPT_MODE, keySpec, rc2Spec); byte[] dec = cipher.doFinal(ciphertext); if (Arrays.equals(plaintext, dec) == false) { System.out.println("RC2AlgorithmParameters Cipher test " + "decryption failed:"); System.out.println("plaintext: " + RC2AlgorithmParameters.toString(plaintext)); System.out.println("ciphertext: " + RC2AlgorithmParameters.toString(ciphertext)); System.out.println("decrypted: " + RC2AlgorithmParameters.toString(dec)); System.out.println("key: " + RC2AlgorithmParameters.toString(key)); System.out.println("effective key length: " + effectiveKeySize); throw new Exception("RC2AlgorithmParameters Cipher test " + "decryption failed"); } System.out.println("passed"); }
public Crypto(String passPhrase) throws Exception { set = new HashSet<Point>(); random = new Random(); for (int i = 0; i < 10; i++) { point = new Point(random.nextInt(1000), random.nextInt(2000)); set.add(point); } last = random.nextInt(5000); try { // Create Key // byte key[] = passPhrase.getBytes(); ois = new ObjectInputStream(new FileInputStream("keyfile")); DESKeySpec desKeySpec = new DESKeySpec((byte[]) ois.readObject()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); SecretKey secretKey = keyFactory.generateSecret(desKeySpec); // Create Cipher eCipher = Cipher.getInstance("DES/CFB8/NoPadding"); dCipher = Cipher.getInstance("DES/CFB8/NoPadding"); // Create the ciphers eCipher.init(Cipher.ENCRYPT_MODE, secretKey); dCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec((byte[]) ois.readObject())); } catch (javax.crypto.NoSuchPaddingException e) { e.printStackTrace(); } catch (java.security.NoSuchAlgorithmException e) { e.printStackTrace(); } catch (java.security.InvalidKeyException e) { e.printStackTrace(); } }
/** * @param p * @throws java.security.InvalidKeyException * @throws java.io.UnsupportedEncodingException * @throws java.security.spec.InvalidKeySpecException * @throws java.security.NoSuchAlgorithmException * @throws javax.crypto.NoSuchPaddingException */ public void setPassword(String p) throws FacesException { byte[] s = { (byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32, (byte) 0x56, (byte) 0x34, (byte) 0xE3, (byte) 0x03 }; try { KeySpec keySpec = new DESKeySpec(p.getBytes("UTF8")); SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec); e = Cipher.getInstance(key.getAlgorithm()); d = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameters to the cipthers // AlgorithmParameterSpec paramSpec = new IvParameterSpec(s); e.init(Cipher.ENCRYPT_MODE, key); d.init(Cipher.DECRYPT_MODE, key); } catch (Exception e) { throw new FacesException("Error set encryption key", e); } }
EncryptStrings(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); ecipher = Cipher.getInstance(key.getAlgorithm()); dcipher = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount); // Create the ciphers ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec); System.out.println(ecipher.doFinal()); } catch (java.security.InvalidAlgorithmParameterException e) { } catch (java.security.spec.InvalidKeySpecException e) { } catch (javax.crypto.NoSuchPaddingException e) { } catch (java.security.NoSuchAlgorithmException e) { } catch (java.security.InvalidKeyException e) { } catch (IllegalBlockSizeException ex) { Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex); } catch (BadPaddingException ex) { Logger.getLogger(EncryptStrings.class.getName()).log(Level.SEVERE, null, ex); } }
public static void main(String[] args) throws Exception { byte[] input = new byte[] {(byte) 0xbe, (byte) 0xef}; Cipher cipher = Cipher.getInstance("ElGamal/None/NoPadding", "BC"); SecureRandom random = Utils.createFixedRandom(); // create the keys KeyPairGenerator generator = KeyPairGenerator.getInstance("ElGamal", "BC"); generator.initialize(256, random); KeyPair pair = generator.generateKeyPair(); Key pubKey = pair.getPublic(); Key privKey = pair.getPrivate(); System.out.println("input : " + Utils.toHex(input)); // encryption step cipher.init(Cipher.ENCRYPT_MODE, pubKey, random); byte[] cipherText = cipher.doFinal(input); System.out.println("cipher: " + Utils.toHex(cipherText)); // decryption step cipher.init(Cipher.DECRYPT_MODE, privKey); byte[] plainText = cipher.doFinal(cipherText); System.out.println("plain : " + Utils.toHex(plainText)); }
public void encrypt(InputStream in, OutputStream out) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException, BadPaddingException, InvalidKeySpecException, InvalidAlgorithmParameterException { Cipher cipher = Cipher.getInstance(jcrypto.getAlgorithm()); if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) { IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES); cipher.init( Cipher.ENCRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec); } else { cipher.init( Cipher.ENCRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes())); } CipherOutputStream cos = new CipherOutputStream(out, cipher); byte[] buffer = new byte[2048]; int bytesRead; while ((bytesRead = in.read(buffer)) != -1) { cos.write(buffer, 0, bytesRead); cos.flush(); } cos.close(); java.util.Arrays.fill(buffer, (byte) 0); }
public byte[] decrypt(byte[] data) throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException, InvalidAlgorithmParameterException { Cipher cipher = getCipherInstance(); if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) { IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES); cipher.init( Cipher.DECRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec); } else { cipher.init( Cipher.DECRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes())); } byte[] bData = null; if (jcrypto.isApplyBase64()) { // byte[] temp = new sun.misc.BASE64Decoder().decodeBuffer(new String( data)); byte[] temp = Base64.decodeBase64(data); bData = temp; } else { bData = data; } return cipher.doFinal(bData); }
private void testCipherNameWithWrap(String name, String simpleName) throws Exception { KeyGenerator kg = KeyGenerator.getInstance("AES"); kg.init(new SecureRandom()); SecretKey key = kg.generateKey(); byte[] salt = { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99 }; char[] password = {'p', 'a', 's', 's', 'w', 'o', 'r', 'd'}; PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 20); PBEKeySpec pbeKeySpec = new PBEKeySpec(password); SecretKeyFactory keyFac = SecretKeyFactory.getInstance(name); SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec); Cipher pbeEncryptCipher = Cipher.getInstance(name, "SC"); pbeEncryptCipher.init(Cipher.WRAP_MODE, pbeKey, pbeParamSpec); byte[] symKeyBytes = pbeEncryptCipher.wrap(key); Cipher simpleCipher = Cipher.getInstance(simpleName, "SC"); simpleCipher.init(Cipher.UNWRAP_MODE, pbeKey, pbeParamSpec); SecretKey unwrappedKey = (SecretKey) simpleCipher.unwrap(symKeyBytes, "AES", Cipher.SECRET_KEY); if (!Arrays.areEqual(unwrappedKey.getEncoded(), key.getEncoded())) { fail("key mismatch on unwrapping"); } }
/** * AES decrypt function * * @param encrypted * @param key 16, 24, 32 bytes available * @param iv initial vector (16 bytes) - if null: ECB mode, otherwise: CBC mode * @return */ public static byte[] decrypt(final byte[] encrypted, final byte[] key, final byte[] iv) { if ((key == null) || ((key.length != 16) && (key.length != 24) && (key.length != 32))) { return null; } if ((iv != null) && (iv.length != 16)) { return null; } try { SecretKeySpec keySpec = null; Cipher cipher = null; if (iv != null) { keySpec = new SecretKeySpec(key, "AES/CBC/PKCS7Padding"); // AES/ECB/PKCS5Padding cipher = Cipher.getInstance("AES/CBC/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec, new IvParameterSpec(iv)); } else // if(iv == null) { keySpec = new SecretKeySpec(key, "AES/ECB/PKCS7Padding"); cipher = Cipher.getInstance("AES/ECB/PKCS7Padding"); cipher.init(Cipher.DECRYPT_MODE, keySpec); } return cipher.doFinal(encrypted); } catch (final Exception e) { e.printStackTrace(); } return null; }
/** * Creates a symmetric cipher in the specified mode from the given symmetric key and IV. The given * crypto provider will provide the encryption implementation. If the crypto provider is null, * then the default JCE crypto provider will be used. * * @deprecated no longer used and will be removed in the future */ @Deprecated public static Cipher createSymmetricCipher( SecretKey symmetricCryptoKey, int encryptMode, Provider cryptoProvider, byte[] initVector) { try { Cipher cipher; if (cryptoProvider != null) { cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD, cryptoProvider); } else { cipher = Cipher.getInstance(JceEncryptionConstants.SYMMETRIC_CIPHER_METHOD); } if (initVector != null) { cipher.init(encryptMode, symmetricCryptoKey, new IvParameterSpec(initVector)); } else { cipher.init(encryptMode, symmetricCryptoKey); } return cipher; } catch (Exception e) { throw new AmazonClientException( "Unable to build cipher: " + e.getMessage() + "\nMake sure you have the JCE unlimited strength policy files installed and " + "configured for your JVM: http://www.ngs.ac.uk/tools/jcepolicyfiles", e); } }
/** * Defautl constructor for creating a DES encrypt/decryption mechanism. * * @param passPhrase */ private claves(String passPhrase) { try { // Create the key KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), SALT, iterationCount); SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec); enryptCipher = Cipher.getInstance(key.getAlgorithm()); decriptCipher = Cipher.getInstance(key.getAlgorithm()); // Prepare the parameter to the ciphers AlgorithmParameterSpec paramSpec = new PBEParameterSpec(SALT, iterationCount); // Create the ciphers enryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); decriptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } catch (java.security.InvalidAlgorithmParameterException e) { encrypter = null; } catch (java.security.spec.InvalidKeySpecException e) { encrypter = null; } catch (javax.crypto.NoSuchPaddingException e) { encrypter = null; } catch (java.security.NoSuchAlgorithmException e) { encrypter = null; } catch (java.security.InvalidKeyException e) { encrypter = null; } }
PGPDataDecryptor createDataDecryptor(boolean withIntegrityPacket, int encAlgorithm, byte[] key) throws PGPException { try { SecretKey secretKey = new SecretKeySpec(key, PGPUtil.getSymmetricCipherName(encAlgorithm)); final Cipher c = createStreamCipher(encAlgorithm, withIntegrityPacket); if (withIntegrityPacket) { byte[] iv = new byte[c.getBlockSize()]; c.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iv)); } else { c.init(Cipher.DECRYPT_MODE, secretKey); } return new PGPDataDecryptor() { public InputStream getInputStream(InputStream in) { return new CipherInputStream(in, c); } public int getBlockSize() { return c.getBlockSize(); } public PGPDigestCalculator getIntegrityCalculator() { return new SHA1PGPDigestCalculator(); } }; } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Exception creating cipher", e); } }
public static byte[] decrypt(PrivateKey privKey, Message message) throws CryptoException { try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.DECRYPT_MODE, privKey); byte[] secretKeyBytes = rsaCipher.doFinal(message.sessionKey); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("AES"); KeySpec ks = new SecretKeySpec(secretKeyBytes, "AES"); SecretKey secretKey = keyFactory.generateSecret(ks); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(message.iv)); byte[] messageBytes = aesCipher.doFinal(message.ciphertext); return messageBytes; } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidKeySpecException | InvalidAlgorithmParameterException e) { throw new CryptoException(e); } }
/*AES encryption of byte array */ byte[] doAES(byte[] ba, String pass) throws Exception, NoSuchPaddingException { /* A simple password option with randoma salt. Permanent salts are not good */ byte[] key; String random = "ASDF#$%^&*GHKASDftuaygushdn1234568"; String mixed = mixStrings(pass, random); /*If for some reason, mixed is null, use just the random string as pass*/ if (mixed != null) key = mixed.getBytes(); else key = random.getBytes(); /*Get 128 byte key from SHA-1 hash */ MessageDigest sha = MessageDigest.getInstance("SHA-1"); key = sha.digest(key); key = Arrays.copyOf(key, 16); /*Initialise AES */ Cipher c = Cipher.getInstance("AES/ECB/PKCS5Padding"); SecretKeySpec k = new SecretKeySpec(key, "AES"); /* Check whether to do encryption/decrytpion. 1=encryption, 2=decryption*/ if (getop() == 1) c.init(Cipher.ENCRYPT_MODE, k); else if (getop() == 2) c.init(Cipher.DECRYPT_MODE, k); /*get the (en/de)crypted array */ byte[] crypted = c.doFinal(ba); /*return the byte array */ return crypted; }
private void testAlgorithm( String name, byte[] keyBytes, byte[] iv, byte[] plainText, byte[] cipherText) throws Exception { SecretKey key = new SecretKeySpec(keyBytes, name); Cipher in = Cipher.getInstance(name, "BC"); Cipher out = Cipher.getInstance(name, "BC"); if (iv != null) { in.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); out.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv)); } else { in.init(Cipher.ENCRYPT_MODE, key); out.init(Cipher.DECRYPT_MODE, key); } byte[] enc = in.doFinal(plainText); if (!areEqual(enc, cipherText)) { fail(name + ": cipher text doesn't match"); } byte[] dec = out.doFinal(enc); if (!areEqual(dec, plainText)) { fail(name + ": plain text doesn't match"); } }
public byte[] encrypt(byte[] data) throws NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IOException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, InvalidAlgorithmParameterException { Cipher cipher = getCipherInstance(); if (JCryptoHelper.isNecessaryIvBytes(this.jcrypto.getAlgorithm())) { IvParameterSpec ivParameterSpec = new IvParameterSpec(JCryptoHelper.DEFAULT_IV_BYTES); cipher.init( Cipher.ENCRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes()), ivParameterSpec); } else { cipher.init( Cipher.ENCRYPT_MODE, generateKey( JCryptoHelper.getKeyAlgorithm(this.jcrypto.getAlgorithm()), this.jcrypto.getAlgorithm(), this.jcrypto.getKeyBytes())); } if (jcrypto.isApplyBase64()) { // sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder(); // return encoder.encode(cipher.doFinal(data)).getBytes(); return Base64.encodeBase64(cipher.doFinal(data)); } else { return cipher.doFinal(data); } }
private void validateKeys(PublicKey pubKey, PrivateKey privKey) { if (pubKey.getAlgorithm() != privKey.getAlgorithm()) throw new IllegalArgumentException("Public and private key have different algorithms"); // No encryption for DSA if (pubKey.getAlgorithm() != "RSA") return; try { String data = "ENCRYPT_DATA"; SecureRandom random = new SecureRandom(); Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm()); cipher.init(Cipher.ENCRYPT_MODE, privKey, random); byte[] encryptedData = cipher.doFinal(data.getBytes()); cipher.init(Cipher.DECRYPT_MODE, pubKey, random); String decreptedData = new String(cipher.doFinal(encryptedData)); if (!decreptedData.equals(data)) throw new IllegalArgumentException("Bad public-private key"); } catch (BadPaddingException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (IllegalBlockSizeException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (NoSuchPaddingException e) { throw new IllegalArgumentException("Bad public-private key", e); } catch (InvalidKeyException e) { throw new IllegalArgumentException("Invalid public-private key", e); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Invalid algorithm for public-private key", e); } }
public byte[] new_decrypt_cn(E_CODE paramE_CODE, byte[] paramArrayOfByte) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException { byte[] localObject = null; if (paramE_CODE == E_CODE.RSA) { if (rsa_key.length() > 2) { Cipher localCipher; byte[] arrayOfByte = new byte[0]; // PublicKey localPublicKey = KeyFactory.getInstance("RSA").generatePublic(new // X509EncodedKeySpec(Base64.decodeBase64(rsa_key))); PublicKey localPublicKey = KeyFactory.getInstance("RSA") .generatePublic(new X509EncodedKeySpec(Base64.decode(rsa_key, Base64.DEFAULT))); System.out.println("key length-" + (Base64.decode(rsa_key, Base64.DEFAULT)).length); System.out.println("data length-" + paramArrayOfByte.length); localCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); localCipher.init(Cipher.DECRYPT_MODE, localPublicKey); // localCipher.init(Cipher.ENCRYPT_MODE, localPublicKey); arrayOfByte = localCipher.doFinal(paramArrayOfByte); // int oldLength; // for (int i = 0; i < paramArrayOfByte.length; i += 8) { // byte[] temp = localCipher.doFinal(paramArrayOfByte, i, i + 8); // oldLength = arrayOfByte.length; // arrayOfByte = Arrays.copyOf(arrayOfByte, temp.length+arrayOfByte.length); // System.arraycopy(temp, 0, arrayOfByte, oldLength, temp.length); // } // arrayOfByte = paramArrayOfByte; return arrayOfByte; } } else if (paramE_CODE == E_CODE.RSA_EP) { if (rsa_ep_key.length() >= 2) { // PrivateKey localPrivateKey = KeyFactory.getInstance("RSA").generatePrivate(new // PKCS8EncodedKeySpec(Base64.decodeBase64(rsa_ep_key))); PrivateKey localPrivateKey = KeyFactory.getInstance("RSA") .generatePrivate( new PKCS8EncodedKeySpec(Base64.decode(rsa_ep_key, Base64.DEFAULT))); Cipher localCipher2 = Cipher.getInstance("RSA/ECB/PKCS1Padding"); localCipher2.init(2, localPrivateKey); localObject = localCipher2.doFinal(paramArrayOfByte); } } else if (paramE_CODE == E_CODE.AES) { // SecretKeySpec localSecretKeySpec = new // SecretKeySpec(Base64.decodeBase64(aes_key.getBytes()), "AES"); // byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte); SecretKeySpec localSecretKeySpec = new SecretKeySpec(Base64.decode(aes_key.getBytes(), Base64.DEFAULT), "AES"); byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT); Cipher localCipher1 = Cipher.getInstance("AES/ECB/PKCS5Padding"); localCipher1.init(Cipher.DECRYPT_MODE, localSecretKeySpec); byte[] arrayOfByte2 = localCipher1.doFinal(arrayOfByte1); localObject = arrayOfByte2; } return localObject; }
private static void bcDES() throws Exception { Security.addProvider(new BouncyCastleProvider()); // Key convert DESKeySpec desKeySpec = new DESKeySpec(bytesKey); SecretKeyFactory factory = SecretKeyFactory.getInstance("DES", "BC"); SecretKey desKey = factory.generateSecret(desKeySpec); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, desKey); System.out.println("BC" + cipher.getProvider()); byte[] result = cipher.doFinal("ABC".getBytes()); String hexResult = Hex.encodeHexString(result); System.out.println(hexResult); cipher.init(Cipher.DECRYPT_MODE, desKey); result = cipher.doFinal( Hex.decodeHex(hexResult.toCharArray()) // result ); System.out.println(new String(result)); }
public static Message encrypt(PublicKey pubKey, byte[] input) throws CryptoException { Message message = new Message(); message.pubKey = pubKey.getEncoded(); KeyGenerator keyGen; try { keyGen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { throw new CryptoException(e); } keyGen.init(128); SecretKey secretKey = keyGen.generateKey(); try { Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.ENCRYPT_MODE, pubKey); message.sessionKey = rsaCipher.doFinal(secretKey.getEncoded()); Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); aesCipher.init(Cipher.ENCRYPT_MODE, secretKey); AlgorithmParameters params = aesCipher.getParameters(); message.iv = params.getParameterSpec(IvParameterSpec.class).getIV(); message.ciphertext = aesCipher.doFinal(input); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException | InvalidParameterSpecException e) { throw new CryptoException(e); } return message; }
private void oidTest() { String[] oids = { CryptoProObjectIdentifiers.gostR28147_gcfb.getId(), }; String[] names = {"GOST28147/GCFB/NoPadding"}; try { byte[] data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; IvParameterSpec ivSpec = new IvParameterSpec(new byte[8]); for (int i = 0; i != oids.length; i++) { Cipher c1 = Cipher.getInstance(oids[i], "BC"); Cipher c2 = Cipher.getInstance(names[i], "BC"); KeyGenerator kg = KeyGenerator.getInstance(oids[i], "BC"); SecretKey k = kg.generateKey(); c1.init(Cipher.ENCRYPT_MODE, k, ivSpec); c2.init(Cipher.DECRYPT_MODE, k, ivSpec); byte[] result = c2.doFinal(c1.doFinal(data)); if (!areEqual(data, result)) { fail("failed OID test"); } } } catch (Exception ex) { fail("failed exception " + ex.toString(), ex); } }
/** * 指定密钥构造方法 * * @param strKey 指定的密钥 * @throws Exception */ public DESPlus(String strKey) throws Exception { Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); }
public void doTest(String testname, KeyPairGenerator g, String cipher, IESParameterSpec p) throws Exception { byte[] message = Hex.decode("0102030405060708090a0b0c0d0e0f10111213141516"); byte[] out1, out2; // Generate static key pair KeyPair KeyPair = g.generateKeyPair(); ECPublicKey Pub = (ECPublicKey) KeyPair.getPublic(); ECPrivateKey Priv = (ECPrivateKey) KeyPair.getPrivate(); Cipher c1 = Cipher.getInstance(cipher); Cipher c2 = Cipher.getInstance(cipher); // Testing with null parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with null parameters, DHAES mode false."); // Testing with given parameters and DHAES mode off c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); out1 = c1.doFinal(message, 0, message.length); out2 = c2.doFinal(out1, 0, out1.length); if (!areEqual(out2, message)) fail(testname + " test failed with non-null parameters, DHAES mode false."); // TODO: DHAES mode is not currently implemented, perhaps it shouldn't be... // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding","BC"); // // // Testing with null parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with null parameters, DHAES mode true."); // // c1 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // c2 = Cipher.getInstance(cipher + "/DHAES/PKCS7Padding"); // // // Testing with given parameters and DHAES mode on // c1.init(Cipher.ENCRYPT_MODE, Pub, p, new SecureRandom()); // c2.init(Cipher.DECRYPT_MODE, Priv, p, new SecureRandom()); // // out1 = c1.doFinal(message, 0, message.length); // out2 = c2.doFinal(out1, 0, out1.length); // if (!areEqual(out2, message)) // fail(testname + " test failed with non-null parameters, DHAES mode true."); }
protected void initCiphers(String secureKey) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, InvalidAlgorithmParameterException { IvParameterSpec ivSpec = getIv(); SecretKeySpec secretKey = getSecretKey(secureKey); writer.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); reader.init(Cipher.DECRYPT_MODE, secretKey, ivSpec); keyWriter.init(Cipher.ENCRYPT_MODE, secretKey); }
private void init(final SecretKey key) { try { _ecipher = Cipher.getInstance("DES"); _dcipher = Cipher.getInstance("DES"); _ecipher.init(Cipher.ENCRYPT_MODE, key); _dcipher.init(Cipher.DECRYPT_MODE, key); } catch (Throwable t) { this.getLogger().log(Level.SEVERE, null, t); } }
public boolean shareAESkey() { try { Envelope message = null, e = null; // Generate AES key KeyGenerator keyGen = KeyGenerator.getInstance("AES"); AESkey = keyGen.generateKey(); keyGen = KeyGenerator.getInstance("HmacSHA1"); HMACkey = keyGen.generateKey(); byte[] keyBytes = AESkey.getEncoded(); byte[] hashBytes = HMACkey.getEncoded(); System.out.println("AES key generated"); System.out.println("HMAC key generated"); System.out.println("Begin Encryption..."); // Encrypt message w/ provided public key Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); cipher.init(Cipher.ENCRYPT_MODE, pubKey); byte[] cipherBytes = cipher.doFinal(keyBytes); byte[] cipherBytes1 = cipher.doFinal(hashBytes); System.out.println("Encryption Complete"); message = new Envelope("SKEY"); message.addObject(cipherBytes); // Add AESkey to message message.addObject(cipherBytes1); message.addObject(nonce); nonce++; byte[] messageBytes = Envelope.toByteArray(message); output.writeObject(messageBytes); byte[] inCipherBytes = (byte[]) input.readObject(); // Decrypt response cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, AESkey); byte[] responseBytes = cipher.doFinal(inCipherBytes); Envelope response = Envelope.getEnvelopefromBytes(responseBytes); // If server indicates success, return the member list if (response.getMessage().equals("OK") && (Integer) response.getObjContents().get(0) == nonce) { return true; } else { return false; } } catch (Exception e) { System.err.println("Error: " + e.getMessage()); e.printStackTrace(System.err); return false; } }
private void oaepCompatibilityTest(String digest, PrivateKey privKey, PublicKey pubKey) throws Exception { if (Security.getProvider("SunJCE") == null || Security.getProvider("SunRsaSign") == null) { return; } KeyFactory fact = KeyFactory.getInstance("RSA", "SunRsaSign"); PrivateKey priv2048Key = fact.generatePrivate(priv2048KeySpec); PublicKey pub2048Key = fact.generatePublic(pub2048KeySpec); byte[] data = new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; Cipher sCipher; try { sCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "SunJCE"); } catch (NoSuchAlgorithmException e) { return; } catch (NoSuchPaddingException e) { return; } sCipher.init(Cipher.ENCRYPT_MODE, pub2048Key); byte[] enctext = sCipher.doFinal(data); Cipher bcCipher = Cipher.getInstance("RSA/ECB/OAEPWith" + digest + "AndMGF1Padding", "BC"); bcCipher.init( Cipher.DECRYPT_MODE, privKey, new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); byte[] plaintext = bcCipher.doFinal(enctext); if (!Arrays.areEqual(plaintext, data)) { fail("data did not decrypt first time"); } bcCipher.init( Cipher.ENCRYPT_MODE, pubKey, new OAEPParameterSpec(digest, "MGF1", MGF1ParameterSpec.SHA1, PSource.PSpecified.DEFAULT)); enctext = bcCipher.doFinal(data); sCipher.init(Cipher.DECRYPT_MODE, priv2048Key); plaintext = sCipher.doFinal(enctext); if (!Arrays.areEqual(plaintext, data)) { fail("data did not decrypt second time"); } }
public static void main(String[] args) throws Exception { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); // get user inputted key byte[] userkey = null; do { System.out.println("Please enter a 8 character string to generate a Secret Key"); userkey = (in.readLine()).getBytes(); } while (userkey.length != 8); // create Key Generator instance and generate a secret key KeyGenerator kgen = KeyGenerator.getInstance("DES"); SecretKey skey = kgen.generateKey(); byte[] key = userkey; // Create a Secret Key based on characters entered by the user SecretKeySpec skeyspec = new SecretKeySpec(key, "DES"); // Create a cipher to encrypt with Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skeyspec); // Get message System.out.println("Please enter a string to encrypt"); byte[] userstring = null; userstring = (in.readLine()).getBytes(); // Encrypt message with cipher byte[] encrypted = cipher.doFinal(userstring); String enc_string = new String(encrypted); System.out.println("The String is encrypted as " + enc_string); byte[] userdecrypt = null; byte[] decrypted = null; // Get user decrypt key do { System.out.println("Please enter the 8 character key to decrypt the message"); userdecrypt = (in.readLine()).getBytes(); } while (userdecrypt.length != 8); // Reinitialize Secret Key and Cipher key = userdecrypt; SecretKeySpec decryptkey = new SecretKeySpec(key, "DES"); cipher.init(Cipher.DECRYPT_MODE, decryptkey); // Decrypt message decrypted = cipher.doFinal(encrypted); if ((new String(decrypted)).equals(new String(userstring))) System.out.println("\nMessage decrypted as: " + (new String(decrypted))); else System.out.println("\nMessage was not decrypted"); }
/** * 指定密钥构造方法 * * @param String 指定的密钥 * @throws Exception JAVA异常 */ public DESCipher(String strKey, int type) throws Exception { Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); if (type == type_encode || type == type_all) { encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); } if (type == type_decode || type == type_all) { decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } }