List of usage examples for javax.crypto Cipher getOutputSize
public final int getOutputSize(int inputLen)
From source file:net.networksaremadeofstring.cyllell.Authentication.java
private String SignHeaders(String dataToSign) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException { PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decode(this.PrivateKey.getBytes(), 0)); KeyFactory kf = KeyFactory.getInstance("RSA"); PrivateKey pk = kf.generatePrivate(spec); Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING"); cipher.init(Cipher.ENCRYPT_MODE, pk); byte[] EncryptedStream = new byte[cipher.getOutputSize(dataToSign.length())]; try {/* w w w. jav a 2s . co m*/ cipher.doFinal(dataToSign.getBytes(), 0, dataToSign.length(), EncryptedStream, 0); } catch (ShortBufferException e) { // TODO Auto-generated catch block e.printStackTrace(); } return Base64.encodeToString(EncryptedStream, Base64.NO_WRAP); }
From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) throw new NullPointerException("ExternalContext ctx"); testConfiguration(ctx);//from w w w .j a v a 2 s . c o m SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:org.apache.myfaces.shared.util.StateUtils.java
public static byte[] encrypt(byte[] insecure, ExternalContext ctx) { if (ctx == null) { throw new NullPointerException("ExternalContext ctx"); }/*from w ww . j a va 2 s. c o m*/ testConfiguration(ctx); SecretKey secretKey = (SecretKey) getSecret(ctx); String algorithm = findAlgorithm(ctx); String algorithmParams = findAlgorithmParams(ctx); byte[] iv = findInitializationVector(ctx); SecretKey macSecretKey = (SecretKey) getMacSecret(ctx); String macAlgorithm = findMacAlgorithm(ctx); try { // keep local to avoid threading issue Mac mac = Mac.getInstance(macAlgorithm); mac.init(macSecretKey); Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams); if (iv != null) { IvParameterSpec ivSpec = new IvParameterSpec(iv); cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec); } else { cipher.init(Cipher.ENCRYPT_MODE, secretKey); } if (log.isLoggable(Level.FINE)) { log.fine("encrypting w/ " + algorithm + "/" + algorithmParams); } //EtM Composition Approach int macLenght = mac.getMacLength(); byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght]; int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure); mac.update(secure, 0, secureCount); mac.doFinal(secure, secureCount); return secure; } catch (Exception e) { throw new FacesException(e); } }
From source file:Networking.Server.java
public byte[] encryptMessage() { byte[] cipherText = null; byte[] text = null; try {/* w w w .j a v a 2s . c o m*/ byte[] plainText = message.getBytes(); SecretKeySpec myKey; myKey = new SecretKeySpec(this.d.getSessionKey(), "AES"); SecureRandom random = new SecureRandom(); byte randombytes[] = new byte[16]; random.nextBytes(randombytes); this.d.setIv(randombytes); IvParameterSpec iv = new IvParameterSpec(this.d.getIv()); Cipher c = Cipher.getInstance("AES/CTR/NoPadding"); c.init(Cipher.ENCRYPT_MODE, myKey, iv); cipherText = new byte[c.getOutputSize(plainText.length)]; c.doFinal(plainText, 0, plainText.length, cipherText); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); outputStream.write(iv.getIV()); outputStream.write((cipherText)); text = outputStream.toByteArray(); File ivMsgFile = new File("./write_iv.txt"); if (ivMsgFile.createNewFile()) { System.out.println("File is created!"); } FileOutputStream sigfos = new FileOutputStream(ivMsgFile); sigfos.write(text); sigfos.flush(); sigfos.close(); byte[] sig_bytes = new byte[(int) ivMsgFile.length()]; BufferedInputStream bis1 = new BufferedInputStream(new FileInputStream(ivMsgFile)); bis1.read(sig_bytes, 0, sig_bytes.length); sendMesLen((int) ivMsgFile.length()); Timestamp timestamp = new Timestamp(System.currentTimeMillis()); System.out.println("sent time: " + timestamp); Socket writeSocket = new Socket(Ip, port); writeSocket.getOutputStream().write(sig_bytes, 0, sig_bytes.length); writeSocket.getOutputStream().flush(); writeSocket.close(); } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException | IOException ex) { Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex); } return Base64.encodeBase64(text); }
From source file:Networking.Client.java
public void PRF() { try {/* w w w . j a v a 2 s . c om*/ SecretKeySpec myKey = new SecretKeySpec(this.node.getHashed_key_128(), "AES"); byte[] plainText = new byte[128]; byte[] ones = new byte[16]; Arrays.fill(ones, (byte) 1); SecureRandom random = new SecureRandom(); byte IV[] = new byte[16]; random.nextBytes(IV); IvParameterSpec iv = new IvParameterSpec(IV); Cipher c = Cipher.getInstance("AES/CTR/NoPadding"); c.init(Cipher.ENCRYPT_MODE, myKey, iv); byte[] macKey = new byte[c.getOutputSize(plainText.length)]; c.doFinal(plainText, 0, plainText.length, macKey); this.node.setMacKey(macKey); Cipher c1 = Cipher.getInstance("AES/CTR/NoPadding"); c1.init(Cipher.ENCRYPT_MODE, myKey, iv); byte[] sessionKey = new byte[c1.getOutputSize(ones.length)]; c1.doFinal(ones, 0, ones.length, sessionKey); this.node.setSessionKey(sessionKey); } catch (IllegalBlockSizeException | BadPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | NoSuchAlgorithmException | NoSuchPaddingException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } catch (ShortBufferException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:umu.eadmin.servicios.umu2stork.UtilesRsa.java
public String encode(String data) throws javax.servlet.ServletException { String output = ""; if (pk == null) throw new ServletException("Private ciphering key does not exist!"); try {//from ww w .j a v a2 s. c o m logger.info("RSA encoder load"); Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); logger.info("RSA encoder init"); rsaCipher.init(Cipher.ENCRYPT_MODE, pk); int inputSize = data.length(); int inputBlockSize = rsaCipher.getOutputSize(1); int numBlocks = inputSize / inputBlockSize; logger.info("#Blocks: " + numBlocks); int resto = inputSize % inputBlockSize; byte[][] rawOutput = null; if (resto != 0) rawOutput = new byte[numBlocks + 1][]; else rawOutput = new byte[numBlocks][]; int blockCount = 0; while (blockCount < numBlocks) { int index = blockCount * inputBlockSize; rawOutput[blockCount] = rsaCipher.doFinal(data.getBytes(), index, inputBlockSize); logger.info("Block encoded: " + new String(rawOutput[blockCount])); blockCount++; } if (resto != 0) { numBlocks++; int index = blockCount * inputBlockSize; rawOutput[blockCount] = rsaCipher.doFinal(data.getBytes(), index, resto); } int totalSize = 0; for (int i = 0; i < numBlocks; i++) totalSize += rawOutput[i].length; byte[] fullOutput = new byte[totalSize]; int count = 0; for (int i = 0; i < numBlocks; i++) { int blockSize = rawOutput[i].length; for (int j = 0; j < blockSize; j++) { fullOutput[count] = rawOutput[i][j]; count++; } } byte[] encoded64Data = Base64.encode(fullOutput); output = new String(encoded64Data); logger.info("RSA Encoding ends"); } catch (Exception e) { logger.warning("Encoding aborted due Exception: " + e); output = ""; } return output; }
From source file:org.auscope.portal.server.web.controllers.GridLoginController.java
/** * Uses a cipher to decrypt data from an input stream. *///from www . j a va 2 s. c o m private String decryptString(InputStream in, Cipher cipher) throws GeneralSecurityException, IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); int blockSize = cipher.getBlockSize(); int outputSize = cipher.getOutputSize(blockSize); byte[] inBlock = new byte[blockSize]; byte[] outBlock = new byte[outputSize]; int bytesRead; do { bytesRead = in.read(inBlock); if (bytesRead == blockSize) { int len = cipher.update(inBlock, 0, blockSize, outBlock); output.write(outBlock, 0, len); } } while (bytesRead == blockSize); if (bytesRead > 0) { outBlock = cipher.doFinal(inBlock, 0, bytesRead); } else { outBlock = cipher.doFinal(); } output.write(outBlock); return output.toString(); }
From source file:umu.eadmin.servicios.umu2stork.UtilesRsa.java
public String decode(String data) throws ServletException { logger.info("Decoding started : " + data); if (pk == null) throw new ServletException("No ciphering key found"); String output = ""; try {/*from www .j a v a2 s .c om*/ logger.info("RSA decoder load"); Cipher rsaCipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); rsaCipher.init(Cipher.DECRYPT_MODE, pk); byte[] decodedData = new org.apache.commons.codec.binary.Base64().decode(data); int inputSize = decodedData.length; int inputBlockSize = rsaCipher.getOutputSize(1); int numBlocks = inputSize / inputBlockSize; logger.info("#Blocks: " + numBlocks); int resto = inputSize % inputBlockSize; byte[][] rawOutput = null; if (resto != 0) rawOutput = new byte[numBlocks + 1][]; else rawOutput = new byte[numBlocks][]; int blockCount = 0; while (blockCount < numBlocks) { int index = blockCount * inputBlockSize; rawOutput[blockCount] = rsaCipher.doFinal(decodedData, index, inputBlockSize); logger.info("Decoded block: " + new String(rawOutput[blockCount])); blockCount++; } if (resto != 0) { numBlocks++; int index = blockCount * inputBlockSize; rawOutput[blockCount] = rsaCipher.doFinal(decodedData, index, resto); } int totalSize = 0; for (int i = 0; i < numBlocks; i++) totalSize += rawOutput[i].length; byte[] fullOutput = new byte[totalSize]; int count = 0; for (int i = 0; i < numBlocks; i++) { int blockSize = rawOutput[i].length; for (int j = 0; j < blockSize; j++) { fullOutput[count] = rawOutput[i][j]; count++; } } output = new String(fullOutput); logger.info("RSA Decoding ends"); } catch (Exception e) { logger.warning("RSA Decoding aborted due Exception : " + e); output = ""; } return output; }
From source file:org.apache.usergrid.persistence.Schema.java
public static ByteBuffer encrypt(ByteBuffer clear) { if (clear == null || !clear.hasRemaining()) { return clear; }/*from w w w.jav a 2 s . c om*/ try { SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sKeySpec); ByteBuffer encrypted = ByteBuffer.allocate(cipher.getOutputSize(clear.remaining())); cipher.doFinal(clear, encrypted); encrypted.rewind(); return encrypted; } catch (Exception e) { throw new IllegalStateException(e); } }
From source file:org.apache.usergrid.persistence.Schema.java
public static ByteBuffer decrypt(ByteBuffer encrypted) { if (encrypted == null || !encrypted.hasRemaining()) { return encrypted; }/*w w w .j a va 2 s.c om*/ try { SecretKeySpec sKeySpec = new SecretKeySpec(getRawKey(encryptionSeed), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, sKeySpec); ByteBuffer decrypted = ByteBuffer.allocate(cipher.getOutputSize(encrypted.remaining())); cipher.doFinal(encrypted, decrypted); decrypted.rewind(); return decrypted; } catch (Exception e) { throw new IllegalStateException(e); } }