List of usage examples for javax.crypto Cipher DECRYPT_MODE
int DECRYPT_MODE
To view the source code for javax.crypto Cipher DECRYPT_MODE.
Click Source Link
From source file:com.tremolosecurity.unison.u2f.util.U2fUtil.java
public static List<SecurityKeyData> loadUserKeys(AuthInfo userData, String challengeStoreAttribute, String encyrptionKeyName) throws Exception, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { Attribute challengeAttr = userData.getAttribs().get(challengeStoreAttribute); Type t = new TypeToken<List<KeyHolder>>() { }.getType();//from ww w . j av a 2 s. co m ArrayList<SecurityKeyData> devices = new ArrayList<SecurityKeyData>(); if (challengeAttr != null) { SecretKey key = GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(encyrptionKeyName); if (key == null) { throw new Exception("Queue message encryption key not found"); } EncryptedMessage msg = gson.fromJson(inflate(challengeAttr.getValues().get(0)), EncryptedMessage.class); IvParameterSpec spec = new IvParameterSpec(msg.getIv()); Cipher cipher; cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, key, spec); byte[] bytes = cipher.doFinal(msg.getMsg()); String json = new String(bytes); java.util.List<KeyHolder> fromJSON = gson.fromJson(json, t); for (KeyHolder kh : fromJSON) { devices.add(new SecurityKeyData(kh.getEnrollmentTime(), kh.getKeyHandle(), kh.getPublicKey(), null, kh.getCounter())); } } return devices; }
From source file:net.sourceforge.jaulp.crypto.aes.HexDecryptor.java
/** * Initializes the {@link SimpleDecryptor} object. * * @throws UnsupportedEncodingException//from www . ja va 2 s . c o m * is thrown by get the byte array of the private key String object fails. * @throws NoSuchAlgorithmException * is thrown if instantiation of the cypher object fails. * @throws NoSuchPaddingException * is thrown if instantiation of the cypher object fails. * @throws InvalidKeyException * the invalid key exception is thrown if initialization of the cypher object fails. */ private void initialize() throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { if (!isInitialized()) { byte[] key; if (this.getPrivateKey() != null) { key = this.getPrivateKey().getBytes("UTF-8"); } else { key = CryptConst.PRIVATE_KEY.getBytes("UTF-8"); } SecretKeySpec skeySpec = new SecretKeySpec(key, Algorithm.AES.getAlgorithm()); this.cipher = Cipher.getInstance(Algorithm.AES.getAlgorithm()); cipher.init(Cipher.DECRYPT_MODE, skeySpec); } }
From source file:com.gfw.press.encrypt.Encrypt.java
/** * /*from ww w.ja va2 s .c om*/ * * @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.tremolosecurity.scale.totp.TotpController.java
@PostConstruct public void init() { this.error = null; HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext() .getRequest();// ww w . ja va 2 s . c o 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.haulmont.cuba.core.sys.SecurityTokenManager.java
/** * Decrypt security token and read filtered data *///from ww w.jav a 2 s .c o m public void readSecurityToken(Entity entity) { SecurityState securityState = getSecurityState(entity); if (getSecurityToken(entity) == null) { return; } Multimap<String, Object> filteredData = ArrayListMultimap.create(); BaseEntityInternalAccess.setFilteredData(securityState, filteredData); Cipher cipher = getCipher(Cipher.DECRYPT_MODE); try { byte[] decrypted = cipher.doFinal(getSecurityToken(securityState)); String json = new String(decrypted, StandardCharsets.UTF_8); JSONObject jsonObject = new JSONObject(json); for (Object key : jsonObject.keySet()) { if (!SYSTEM_ATTRIBUTE_KEYS.contains(key)) { String elementName = String.valueOf(key); JSONArray jsonArray = jsonObject.getJSONArray(elementName); MetaProperty metaProperty = entity.getMetaClass().getPropertyNN(elementName); for (int i = 0; i < jsonArray.length(); i++) { Object id = jsonArray.get(i); filteredData.put(elementName, convertId(id, metaProperty)); } } } if (jsonObject.has(READ_ONLY_ATTRIBUTES_KEY)) { BaseEntityInternalAccess.setReadonlyAttributes(securityState, parseJsonArrayAsStrings(jsonObject.getJSONArray(READ_ONLY_ATTRIBUTES_KEY))); } if (jsonObject.has(HIDDEN_ATTRIBUTES_KEY)) { BaseEntityInternalAccess.setHiddenAttributes(securityState, parseJsonArrayAsStrings(jsonObject.getJSONArray(HIDDEN_ATTRIBUTES_KEY))); } if (jsonObject.has(REQUIRED_ATTRIBUTES_KEY)) { BaseEntityInternalAccess.setRequiredAttributes(securityState, parseJsonArrayAsStrings(jsonObject.getJSONArray(REQUIRED_ATTRIBUTES_KEY))); } } catch (Exception e) { throw new RuntimeException("An error occurred while reading security token", e); } }
From source file:com.cherong.mock.common.base.util.EncryptionUtil.java
/** * des//from w w w. j a va 2s .c o m * * @param content * @param key * @return * @throws Exception */ public static String decryptByDES(byte[] content, String key) { try { DESKeySpec desKS = new DESKeySpec(key.getBytes()); SecretKeyFactory skf = SecretKeyFactory.getInstance("DES"); SecretKey sk = skf.generateSecret(desKS); Cipher cip = Cipher.getInstance(DES_CIPHER_ALGORITHM); cip.init(Cipher.DECRYPT_MODE, sk); byte[] result = cip.doFinal(content); return new String(result); } catch (Exception e) { LOGGER.error("{}", e); return null; } }
From source file:cloudeventbus.pki.CertificateUtils.java
public static void validateSignature(PublicKey key, byte[] challenge, byte[] salt, byte[] signature) { try {/* w w w . j a va 2s.c om*/ Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, key); final byte[] decryptedSignature = cipher.doFinal(signature); if (decryptedSignature.length != challenge.length + salt.length) { throw new InvalidSignatureException("Signature doesn't match challenge"); } for (int i = 0; i < challenge.length; i++) { if (decryptedSignature[i] != challenge[i]) { throw new InvalidSignatureException("Signature doesn't match challenge"); } } for (int i = 0; i < salt.length; i++) { if (decryptedSignature[challenge.length + i] != salt[i]) { throw new InvalidSignatureException("Signature doesn't match challenge"); } } } catch (GeneralSecurityException e) { throw new CertificateSecurityException(e); } }
From source file:com.ephesoft.dcma.encryption.core.EncryptorDecryptor.java
/** * This method is used to start the encryption process. * // www . ja v a2s . com * @param data byte[] * @param salt byte[] * @param isEncryption boolean * @return byte[] * @throws CryptographyException {@link CryptographyException} */ public byte[] startCrypting(byte[] data, byte[] salt, boolean isEncryption) throws CryptographyException { KeySpec keySpec = new PBEKeySpec(EncryptionConstants.KEY.toCharArray(), salt, EncryptionConstants.ITERATION_COUNT); SecretKey key; byte[] finalBytes = null; try { key = SecretKeyFactory.getInstance(EncryptionConstants.ALGORITHM).generateSecret(keySpec); Cipher ecipher = Cipher.getInstance(key.getAlgorithm()); AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, EncryptionConstants.ITERATION_COUNT); if (isEncryption) { ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); } else { ecipher.init(Cipher.DECRYPT_MODE, key, paramSpec); } finalBytes = ecipher.doFinal(data); } catch (InvalidKeySpecException e) { if (isEncryption) { LOGGER.error("Encryption : Key used is invalid", e); throw new CryptographyException("Key used is invalid", e); } else { LOGGER.error("Decryption : Key used is invalid", e); throw new CryptographyException("Key used is invalid", e); } } catch (NoSuchAlgorithmException e) { if (isEncryption) { LOGGER.error("Encryption : Algorithm used does not exist", e); throw new CryptographyException("Algorithm used does not exist", e); } else { LOGGER.error("Decryption : Algorithm used does not exist", e); throw new CryptographyException("Algorithm used does not exist", e); } } catch (NoSuchPaddingException e) { if (isEncryption) { LOGGER.error("Encryption : Padding used does not exist", e); throw new CryptographyException("Padding used does not exist", e); } else { LOGGER.error("Decryption : Padding used does not exist", e); throw new CryptographyException("Padding used does not exist", e); } } catch (InvalidKeyException e) { if (isEncryption) { LOGGER.error("Encryption : Key generated is invalid", e); throw new CryptographyException("Key generated is invalid", e); } else { LOGGER.error("Decryption : Key generated is invalid", e); throw new CryptographyException("Key generated is invalid", e); } } catch (InvalidAlgorithmParameterException e) { if (isEncryption) { LOGGER.error("Encryption : Algorithm parameter is invalid", e); throw new CryptographyException("Algorithm parameter is invalid", e); } else { LOGGER.error("Decryption : Algorithm parameter is invalid", e); throw new CryptographyException("Algorithm parameter is invalid", e); } } catch (IllegalBlockSizeException e) { if (isEncryption) { LOGGER.error("Encryption : Block size is illegal", e); throw new CryptographyException("Block size is illegal", e); } else { LOGGER.error("Decryption : Block size is illegal", e); throw new CryptographyException("Block size is illegal", e); } } catch (BadPaddingException e) { if (isEncryption) { LOGGER.error("Encryption : Padding done is invalid", e); throw new CryptographyException("Padding done is invalid", e); } else { LOGGER.error("Decryption : Padding done is invalid", e); throw new CryptographyException("Padding done is invalid", e); } } return finalBytes; }
From source file:com.aqnote.shared.encrypt.symmetric.Blowfish.java
/** * ?CipherdoFinal?reset ???/*from w ww . jav a2s .c o m*/ * * @param b * ? * @return ? * @throws IllegalBlockSizeException * @throws BadPaddingException */ public synchronized static byte[] decrypt(byte[] b) throws IllegalBlockSizeException, BadPaddingException { byte[] buffer = null; initCipher(decryptCipher, Cipher.DECRYPT_MODE, key, iv); buffer = decryptCipher.doFinal(b); return buffer; }
From source file:at.tfr.securefs.xnio.MessageHandlerImpl.java
@Override public void handleMessage(String json, MessageSender messageSender) throws IOException { log.debug("handleMessage: " + json); final Message message = objectMapper.readValue(json, Message.class); Path path = configuration.getBasePath().resolve(message.getPath()); if (!path.relativize(configuration.getBasePath()).toString().equals("..")) { throw new SecurityException("invalid path spec: " + message.getPath()); }/*from w w w .j a v a 2s.c o m*/ try { final String uniqueKey = message.getUniqueKey(); // find the Channel for this data stream: StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>> info = activeStreams.getStreams() .get(uniqueKey); if (message.getType() == MessageType.OPEN && info != null) { log.warn("illegal state on Open stream: " + message); IoUtils.safeClose(info.getStream().getRightSide()); messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey)); } switch (message.getType()) { case ERROR: log.info("error from Client: " + json); case CLOSE: { if (info != null) { IoUtils.safeClose(info.getStream().getRightSide()); } } break; case OPEN: { switch (message.getSubType()) { case READ: { final InputStream is = Files.newInputStream(path, StandardOpenOption.READ); final InputStream cis = new CipherInputStream(is, getCipher(message, Cipher.DECRYPT_MODE)); final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker .createHalfDuplexPipe(); pipe.getLeftSide().getReadSetter().set(new SecureChannelWriterBase(message) { @Override protected void write(Message message) { try { messageSender.send(message); } catch (Exception e) { log.warn("cannot write message=" + message + " : " + e, e); } } }); pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() { @Override public void handleEvent(StreamSourceChannel channel) { activeStreams.getStreams().remove(uniqueKey); messageSender.send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey)); } }); pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() { private byte[] bytes = new byte[Constants.BUFFER_SIZE]; @Override public void handleEvent(StreamSinkChannel channel) { try { int count = 0; while ((count = cis.read(bytes, 0, bytes.length)) > 0) { if (count > 0) { Channels.writeBlocking(pipe.getRightSide(), ByteBuffer.wrap(bytes, 0, count)); } if (count < 0) { pipe.getRightSide().close(); } else { channel.resumeWrites(); } } } catch (Exception e) { log.warn("cannot read from cypher: " + e, e); IoUtils.safeClose(channel); } } }); activeStreams.getStreams().put(uniqueKey, new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe, message.getPath())); // start sending data: pipe.getLeftSide().resumeReads(); pipe.getRightSide().resumeWrites(); } break; case WRITE: { Files.createDirectories(path.getParent()); OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE); OutputStream cos = new CipherOutputStream(os, getCipher(message, Cipher.ENCRYPT_MODE)); ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe(); pipe.getLeftSide().getReadSetter().set(new SecureChannelReaderBase() { @Override public void handleEvent(StreamSourceChannel channel) { readChannel(message, cos, pipe, channel); } }); pipe.getLeftSide().getCloseSetter().set(new SecureChannelReaderBase() { @Override public void handleEvent(StreamSourceChannel channel) { try { cos.close(); activeStreams.getStreams().remove(pipe.toString()); messageSender .send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey)); log.info("closed channel: " + pipe.toString()); } catch (IOException e) { log.warn("cannot close stream: message=" + message + " : " + e, e); } } }); activeStreams.getStreams().put(uniqueKey, new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe, message.getPath())); // start receiving data: pipe.getLeftSide().resumeReads(); } break; default: messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey)); break; } } break; case DATA: { if (info != null) { Channels.writeBlocking(info.getStream().getRightSide(), ByteBuffer.wrap(message.getBytes())); } else { messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey)); } } break; } } catch (IOException e) { log.warn("cannot handle message: " + message + " : " + e, e); throw e; } catch (Exception e) { log.warn("cannot handle message: " + message + " : " + e, e); throw new IOException("cannot handle message: " + message + " : " + e, e); } }