List of usage examples for javax.crypto.spec IvParameterSpec IvParameterSpec
public IvParameterSpec(byte[] iv)
iv
as the IV. From source file:com.tremolosecurity.scale.totp.TotpController.java
@PostConstruct public void init() { this.error = null; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();//from w w w. j a va 2s.co m this.scaleTotpConfig = (ScaleTOTPConfigType) commonConfig.getScaleConfig(); this.login = request.getRemoteUser(); UnisonUserData userData; try { userData = this.scaleSession.loadUserFromUnison(this.login, new AttributeData(scaleTotpConfig.getServiceConfiguration().getLookupAttributeName(), scaleTotpConfig.getUiConfig().getDisplayNameAttribute(), scaleTotpConfig.getAttributeName())); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return; } this.user = userData.getUserObj(); this.displayName = userData.getUserObj().getDisplayName(); ScaleAttribute scaleAttr = userData.getUserObj().getAttrs().get(scaleTotpConfig.getAttributeName()); if (scaleAttr == null) { if (logger.isDebugEnabled()) logger.debug("no sattribute"); this.error = "Token not found"; return; } this.encryptedToken = scaleAttr.getValue(); try { byte[] decryptionKeyBytes = Base64.decodeBase64(scaleTotpConfig.getDecryptionKey().getBytes("UTF-8")); SecretKey decryptionKey = new SecretKeySpec(decryptionKeyBytes, 0, decryptionKeyBytes.length, "AES"); Gson gson = new Gson(); Token token = gson.fromJson(new String(Base64.decodeBase64(this.encryptedToken.getBytes("UTF-8"))), Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64.decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, decryptionKey, spec); String decryptedJSON = new String( cipher.doFinal(Base64.decodeBase64(token.getEncryptedRequest().getBytes("UTF-8")))); if (logger.isDebugEnabled()) logger.debug(decryptedJSON); TOTPKey totp = gson.fromJson(decryptedJSON, TOTPKey.class); this.otpURL = "otpauth://totp/" + totp.getUserName() + "@" + totp.getHost() + "?secret=" + totp.getSecretKey(); } catch (Exception e) { e.printStackTrace(); this.error = "Could not decrypt token"; } try { int size = 250; Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = qrCodeWriter.encode(this.otpURL, BarcodeFormat.QR_CODE, size, size, hintMap); int CrunchifyWidth = byteMatrix.getWidth(); BufferedImage image = new BufferedImage(CrunchifyWidth, CrunchifyWidth, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, CrunchifyWidth, CrunchifyWidth); graphics.setColor(Color.BLACK); for (int i = 0; i < CrunchifyWidth; i++) { for (int j = 0; j < CrunchifyWidth; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(image, "png", baos); this.encodedQRCode = new String(Base64.encodeBase64(baos.toByteArray())); } catch (Exception e) { e.printStackTrace(); this.error = "Could not encode QR Code"; } }
From source file:com.gfw.press.encrypt.Encrypt.java
/** * //w w w .ja va 2 s . com * * @param key * SecretKey * @param cipher_data * ? * @param IV * IV * * @return ? * */ private byte[] decrypt(SecretKey key, byte[] cipher_data, byte[] IV) { if (key == null || cipher_data == null || cipher_data.length == 0 || IV == null || IV.length == 0) { return null; } IvParameterSpec IVSpec = new IvParameterSpec(IV); try { cipher.init(Cipher.DECRYPT_MODE, key, IVSpec); } catch (InvalidKeyException | InvalidAlgorithmParameterException ex) { log("?Cipher"); ex.printStackTrace(); return null; } try { return cipher.doFinal(cipher_data); } catch (IllegalBlockSizeException | BadPaddingException ex) { log("?"); ex.printStackTrace(); return null; } }
From source file:com.forsrc.utils.AesUtils.java
/** * Encrypt string.//from w w w. j a v a2s . c om * * @param src the src * @return String string * @throws AesException the aes exception * @Title: encrypt * @Description: */ public String encrypt(String src) throws AesException { Cipher cipher = null; try { cipher = Cipher.getInstance(CIPHER_KEY); } catch (NoSuchAlgorithmException e) { throw new AesException(e); } catch (NoSuchPaddingException e) { throw new AesException(e); } byte[] raw = KEY.getBytes(); SecretKeySpec secretKeySpec = new SecretKeySpec(raw, SECRET_KEY); IvParameterSpec ivParameterSpec = new IvParameterSpec(IV_PARAMETER.getBytes()); try { cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec); } catch (InvalidKeyException e) { throw new AesException(e); } catch (InvalidAlgorithmParameterException e) { throw new AesException(e); } byte[] encrypted; try { encrypted = cipher.doFinal(src.getBytes(CHARSET_UTF8)); } catch (IllegalBlockSizeException e) { throw new AesException(e); } catch (BadPaddingException e) { throw new AesException(e); } catch (UnsupportedEncodingException e) { throw new AesException(e); } return new String(new Base64().encode(encrypted)); }
From source file:org.hdiv.cipher.CipherHTTP.java
/** * Generates a Cipher object that implements the specified <code>transformation</code>, initializes cipher vector * and initializes cipher to decryption mode with a key and a set of algorithm parameters. * //from w ww . j a v a 2 s . c o m * @param key * the encryption key * @throws HDIVException * if there is an initialization error. */ public void initDecryptMode(Key key) { try { // vector initialization this.ivSpec = new IvParameterSpec(key.getInitVector()); this.cipher.init(Cipher.DECRYPT_MODE, key.getKey(), this.ivSpec); this.encryptMode = false; } catch (Exception e) { String errorMessage = HDIVUtil.getMessage("cipher.init.decrypt", e.getMessage()); throw new HDIVException(errorMessage, e); } }
From source file:com.frame.Conf.Utilidades.java
public static String encrypt(String key, String iv, String cleartext) throws Exception { Cipher cipher = Cipher.getInstance(cI); SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), alg); IvParameterSpec ivParameterSpec = new IvParameterSpec(iv.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivParameterSpec); byte[] encrypted = cipher.doFinal(cleartext.getBytes()); return new String(encodeBase64(encrypted)); }
From source file:org.apache.camel.converter.crypto.CryptoDataFormat.java
private Cipher initializeCipher(int mode, Key key, byte[] iv) throws Exception { Cipher cipher = cryptoProvider == null ? Cipher.getInstance(algorithm) : Cipher.getInstance(algorithm, cryptoProvider); if (key == null) { throw new IllegalStateException( "A valid encryption key is required. Either configure the CryptoDataFormat " + "with a key or provide one in a header using the header name 'CamelCryptoKey'"); }//from w w w .j ava 2 s. com if (mode == ENCRYPT_MODE || mode == DECRYPT_MODE) { if (iv != null) { cipher.init(mode, key, new IvParameterSpec(iv)); } else if (parameterSpec != null) { cipher.init(mode, key, parameterSpec); } else { cipher.init(mode, key); } } return cipher; }
From source file:org.apache.shindig.common.crypto.Crypto.java
/** * AES-128-CBC encryption with a given IV. * * @param key/*w ww . j a va 2s.c o m*/ * @param iv * @param plain * * @return the cipher text * * @throws GeneralSecurityException */ public static byte[] aes128cbcEncryptWithIV(byte[] key, byte[] iv, byte[] plain) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(CIPHER_TYPE); Key cipherKey = new SecretKeySpec(key, CIPHER_KEY_TYPE); IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, cipherKey, ivSpec); return cipher.doFinal(plain); }
From source file:com.cyberninjas.xerobillableexpenses.util.Settings.java
private String encryptText(String plainText) { try {//from www . jav a 2 s.c o m this.iv = prefs.getByteArray("DRUGS", null); if (this.iv == null) { //If not set, set the IV cipher.init(Cipher.ENCRYPT_MODE, this.secret); AlgorithmParameters params = cipher.getParameters(); this.iv = params.getParameterSpec(IvParameterSpec.class).getIV(); prefs.putByteArray("DRUGS", this.iv); } else { cipher.init(Cipher.ENCRYPT_MODE, this.secret, new IvParameterSpec(this.iv)); } byte[] ciphertext = cipher.doFinal(plainText.getBytes("UTF-8")); String ret = new String(Base64.encodeBase64(ciphertext)); return ret; } catch (InvalidParameterSpecException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidKeyException ex) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex); } catch (InvalidAlgorithmParameterException ex) { Logger.getLogger(Settings.class.getName()).log(Level.SEVERE, null, ex); } return ""; }
From source file:org.eclipse.che.api.crypt.server.JCEEncryptTextService.java
@Override public String decryptText(final EncryptResult toDecrypt) throws EncryptException { if (toDecrypt.getInitVector() == null || toDecrypt.getCipherText() == null) { throw new EncryptException("Incorrect encrypt result for this scheme"); }// w w w . j a va2 s. c om final byte[] ivBlob = Base64.decodeBase64(toDecrypt.getInitVector()); final byte[] cipherBlob = Base64.decodeBase64(toDecrypt.getCipherText()); String plainText; try { final SecretKey secret = generateSecret(); final Cipher cipher = Cipher.getInstance(this.transformation); cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBlob)); plainText = new String(cipher.doFinal(cipherBlob), "UTF-8"); } catch (final NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | InvalidKeySpecException | UnsupportedEncodingException | IllegalBlockSizeException | BadPaddingException e) { throw new EncryptException(e); } return plainText; }
From source file:com.github.aelstad.keccakj.keyak.KeyakTestUtils.java
public void runTests(List<KeyakTest> tests) throws Exception { LakeKeyak wrapper = new LakeKeyak(); LakeKeyak unwrapper = new LakeKeyak(); LakeKeyak unwrapperFailing = new LakeKeyak(); for (KeyakTest dt : tests) { System.out.println("initialize with:"); System.out.println("key: " + toHex(dt.key)); System.out.println("nonce: " + toHex(dt.nonce)); wrapper.init(dt.key, dt.nonce);/* w w w . j av a2 s. co m*/ unwrapper.init(dt.key, dt.nonce); unwrapperFailing.init(dt.key, dt.nonce); LakeKeyakCipher lkEncryptingCipher = new LakeKeyakCipher(); lkEncryptingCipher.init(Cipher.ENCRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce)); LakeKeyakCipher lkDecryptingCipher = new LakeKeyakCipher(); lkDecryptingCipher.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce)); LakeKeyakCipher lkDecryptingFailing = new LakeKeyakCipher(); lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce)); for (TestCommand tc : dt.commands) { if (tc instanceof ForgetCommand) { System.out.println("forget"); lkEncryptingCipher.forget(); lkDecryptingCipher.forget(); } else if (tc instanceof PairCommand) { PairCommand pc = (PairCommand) tc; System.out.println("associated data: " + toHex(pc.ad)); System.out.println("plaintext: " + toHex(pc.plaintext)); System.out.println("ciphertext: " + toHex(pc.ciphertext)); System.out.println("tag: " + toHex(pc.tag)); byte[] wrapOut = new byte[pc.plaintext.length]; byte[] tagOut = new byte[pc.tag.length]; lkEncryptingCipher.updateAAD(pc.ad); byte[] encrypted = lkEncryptingCipher.doFinal(pc.plaintext); Assert.assertTrue(encrypted.length == pc.plaintext.length + 16); System.arraycopy(encrypted, 0, wrapOut, 0, pc.plaintext.length); System.arraycopy(encrypted, encrypted.length - 16, tagOut, 0, 16); System.out.println("got ciphertext: " + toHex(wrapOut)); System.out.println("got tag: " + toHex(tagOut)); Assert.assertArrayEquals(wrapOut, pc.ciphertext); Assert.assertArrayEquals(tagOut, pc.tag); lkDecryptingCipher.updateAAD(pc.ad); byte[] decrypted = lkDecryptingCipher.doFinal(encrypted); Assert.assertArrayEquals(decrypted, pc.plaintext); lkDecryptingFailing.updateAAD(pc.ad); AEADBadTagException expected = null; try { byte[] decryptedFailing = lkDecryptingFailing.doFinal(new byte[16]); } catch (AEADBadTagException ex) { expected = ex; } Assert.assertNotNull(expected); lkDecryptingFailing = new LakeKeyakCipher(); lkDecryptingFailing.init(Cipher.DECRYPT_MODE, new LakeKeyakKey(dt.key), new IvParameterSpec(dt.nonce)); } System.out.println(); } } }