List of usage examples for javax.crypto SecretKey getEncoded
public byte[] getEncoded();
From source file:piecework.security.concrete.ExampleBouncyCastleEncryptionService.java
@Override public String decrypt(Secret secret) throws InvalidCipherTextException, GeneralSecurityException, UnsupportedEncodingException { SecretKey secretKey = keyProvider.getDecryptionKey(secret.getName()); BufferedBlockCipher cipher = cipher(); byte[] key = secretKey.getEncoded(); byte[] iv = Base64.decode(secret.getIv()); cipher.init(false, new ParametersWithIV(new KeyParameter(key), iv)); byte[] hidden = Base64.decode(secret.getCiphertext()); byte[] temporary; int outputLength = cipher.getOutputSize(hidden.length); temporary = new byte[outputLength]; int bytesProcessed = cipher.processBytes(hidden, 0, hidden.length, temporary, 0); bytesProcessed += cipher.doFinal(temporary, bytesProcessed); byte[] clear = new byte[bytesProcessed]; System.arraycopy(temporary, 0, clear, 0, bytesProcessed); return new String(clear, "UTF-8"); }
From source file:edu.hku.sdb.crypto.SearchEncryptTest.java
@Test public void testSearch() throws UnsupportedEncodingException { String testStr1 = "briton"; String testStr2 = "Briton"; try {// ww w . ja v a 2 s .c om SEKey key = testObj.keyGen(); String passage = "The 2015 Tour de France was the 102nd edition of the Tour " + "de France, one of cycling's three Grand Tours. The 3,360.3 km (2," + "088 mi)-long race started in Utrecht, the Netherlands, on 4 July " + "2015, and concluded with the Champs-[lysmes stage in Paris, on 26" + " July. A total of 198 riders from 22 teams entered the 21-stage " + "race, which was won by Chris Froome of Team Sky. The second and " + "third places were taken by the Movistar Team riders Nairo Quintana " + "and Alejandro Valverde, respectively." + "BMC Racing Team's Rohan Dennis won the first stage to take the race" + " leader's yellow jersey. Trek Factory Racing rider Fabian " + "Cancellara claimed it the following stage, only to lose it to " + "crashing out on stage three. Froome held it for the fourth, until a" + " three day stint by Etixx-Quick Step's Tony Martin, which came to " + "end with his abandonment on the seventh stage. Froome then took " + "over the position again. He successfully defended the overall lead " + "from attacks by Quintana and other general classification " + "contenders until the event's finish in Paris. After the penultimate" + " stage that ended on Alpe d'Huez, in which Froome was distanced by " + "Quintana, he cemented his final margin of seventy-two seconds." + "Froome became the first Briton to win the Tour de France twice, " + "after his 2013 victory. He also won the mountains classification. " + "Peter Sagan of Tinkoff-Saxo won the points classification. The " + "young rider classification was won by Quintana. Movistar Team " + "finished as the winners of the team classification, which ranks " + "each of the twenty-two teams contesting the race by lowest " + "cumulative time."; String[] parts = passage.split("[^a-zA-Z0-9]+"); byte[][] encrypts = new byte[parts.length][]; int count = 0; for (int i = 0; i < parts.length; i++) { if (parts[i].length() > 2) { // keyword with at least 3 chars encrypts[count] = testObj.encrypt(key, count, parts[i]); count++; } } SecretKey pubKey = testObj.prkey; String encoded = Base64.encodeBase64String(pubKey.getEncoded()); byte[] decoded = Base64.decodeBase64(encoded); SecretKey prkey = new SecretKeySpec(decoded, "AES"); testObj.prkey = prkey; boolean found = false; for (int i = 0; i < count && !found; i++) { if (testObj.search(encrypts[i], testStr1)) { found = true; } } assertTrue(!found); found = false; for (int i = 0; i < count && !found; i++) { if (testObj.search(encrypts[i], testStr2)) { found = true; } } assertTrue(found); } catch (SEException e) { e.printStackTrace(); } }
From source file:components.security.Password.java
/** * Hashes the password using pbkdf2 and the given salt. * * @param password the plain text password to hash. * @param salt the salt for the password * @return the hashed password/*w ww . j a v a2s . com*/ */ public char[] hash(char[] password, byte[] salt) { checkNotNull(password); checkArgument(password.length != 0); checkNotNull(salt); checkArgument(salt.length != 0); try { SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKey key = f.generateSecret(new PBEKeySpec(password, salt, iterations, desiredKeyLenght)); return Base64.encodeBase64String(key.getEncoded()).toCharArray(); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { Logger.error("Problem during password hashing", e); throw new IllegalStateException("Could not hash the password of the user.", e); } }
From source file:org.openmrs.module.clinicalsummary.io.UploadSummariesTask.java
/** * Method to initialize the cipher object with the correct encryption algorithm. * * @throws Exception/*from w w w. j a va2 s . c om*/ */ protected void initializeCipher() throws Exception { SecretKeyFactory factory = SecretKeyFactory.getInstance(TaskConstants.SECRET_KEY_FACTORY); KeySpec spec = new PBEKeySpec(password.toCharArray(), password.getBytes(), 1024, 128); SecretKey tmp = factory.generateSecret(spec); if (log.isDebugEnabled()) log.debug("Secret Key Length: " + tmp.getEncoded().length); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), TaskConstants.KEY_SPEC); cipher = Cipher.getInstance(TaskConstants.CIPHER_CONFIGURATION); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(initVector)); }
From source file:com.cfs.util.AESCriptografia.java
public String gerarChaveRandomica() { String chave = null;/*ww w .j av a 2 s. c om*/ try { /* Cria o gerador de chaves */ KeyGenerator keygen = KeyGenerator.getInstance("AES"); /* Inicializa o gerador de chaves */ SecureRandom random = new SecureRandom(); keygen.init(random); /* Cria uma chave */ SecretKey key = keygen.generateKey(); /* Captura a chave na forma de bytes */ byte[] buffer = key.getEncoded(); /* Codifica a chave gerada */ byte[] chaveGerada = Base64.encodeBase64(buffer); /* Converte a chave para texto */ chave = new String(chaveGerada, "UTF-8"); } catch (Exception e) { e.printStackTrace(); } /* Retorna a chave */ return chave; }
From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java
private void generateKeyWithWrongAlgorithm(Path keyPath) throws NoSuchAlgorithmException, IOException { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); SecretKey secretKey = keyGenerator.generateKey(); char[] hexKey = encodeHex(secretKey.getEncoded()); writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8); }
From source file:ie.peternagy.jcrypto.algo.AesWrapper.java
/** * Generate secret key from iv, salt, baseKey * *//*from w w w. j a va 2 s. com*/ protected final void generateSecretKey() { try { SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM); KeySpec keySpec = new PBEKeySpec(new String(baseKey).toCharArray(), salt, 4096, 256); SecretKey generalSecret = factory.generateSecret(keySpec); secretKey = new SecretKeySpec(generalSecret.getEncoded(), ALGORITHM_NAME); } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { Logger.getLogger(AesWrapper.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Invalid environment, check max key size", ex); } }
From source file:org.codice.ddf.configuration.migration.MigrationZipFileTest.java
private SecretKey createSecretKey(Path keyPath) throws Exception { KeyGenerator keyGenerator = null; keyGenerator = KeyGenerator.getInstance(MigrationZipConstants.KEY_ALGORITHM); SecretKey secretKey = keyGenerator.generateKey(); char[] hexKey = encodeHex(secretKey.getEncoded()); writeStringToFile(keyPath.toFile(), String.valueOf(hexKey), Charsets.UTF_8); return secretKey; }
From source file:org.apache.ws.security.message.SymmetricSignatureTest.java
/** * Setup method// www.ja v a 2s . c o m * <p/> * * @throws Exception Thrown when there is a problem in setup */ @org.junit.Before public void setUp() throws Exception { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); SecretKey key = keyGen.generateKey(); keyData = key.getEncoded(); }
From source file:tds.itemrenderer.security.Encryption.java
/** * initializes ciphers and adds jce provider if provided * * @throws TDS.Shared.Security.TDSEncryptionException *//*www. j av a 2s .c om*/ @PostConstruct protected void init() { if (encryptionKey == null || StringUtils.isBlank(encryptionKey) || encryptionKey.length() < MINIMUM_KEY_LENGTH) { throw new TDSEncryptionException( String.format("Number of characters for key must be greater than %s", MINIMUM_KEY_LENGTH)); } try { SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(PBE_KEY_ALGORITHM); KeySpec keySpec = new PBEKeySpec(encryptionKey.toCharArray(), PBE_SALT, PBE_NUM_ITERATIONS, PBE_KEY_LENGTH); SecretKey secretKeyTemp; secretKeyTemp = secretKeyFactory.generateSecret(keySpec); secretKey = new SecretKeySpec(secretKeyTemp.getEncoded(), CIPHER_ALGORITHM); encryptCipher = Cipher.getInstance(TRANSFORMATION); decryptCipher = Cipher.getInstance(TRANSFORMATION); encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey); } catch (NoSuchAlgorithmException e) { log.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Algorithm is not available"); } catch (InvalidKeySpecException e) { log.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Key specification is not valid"); } catch (NoSuchPaddingException e) { log.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Padding is not valid"); } catch (InvalidKeyException e) { log.error("Encyption.initCipher: " + e.getMessage(), e); throw new TDSEncryptionException("Key is not valid"); } }