List of usage examples for org.bouncycastle.crypto.paddings PKCS7Padding addPadding
public int addPadding(byte[] in, int inOff)
From source file:com.geoxp.oss.CryptoHelper.java
License:Apache License
/** * Pad data using PKCS7.// ww w . ja va 2 s . c om * * @param alignment Alignement on which to pad, e.g. 8 * @param data Data to pad * @return The padded data */ public static byte[] padPKCS7(int alignment, byte[] data, int offset, int len) { // // Allocate the target byte array. Its size is a multiple of 'alignment'. // If data to pad is a multiple of 'alignment', the target array will be // 'alignment' bytes longer than the data to pad. // byte[] target = new byte[len + (alignment - len % alignment)]; // // Copy the data to pad into the target array // System.arraycopy(data, offset, target, 0, len); // // Add padding bytes // PKCS7Padding padding = new PKCS7Padding(); padding.addPadding(target, len); return target; }
From source file:io.warp10.continuum.gts.GTSEncoder.java
License:Apache License
/** * Return the bytes currently in this encoder. * If 'wrappingKey' is non null, encrypt the bytes prior to returning them. * //from w w w. ja v a 2 s. co m * @return The (possibly encrypted bytes) or null if an exception is raised * while encrypting. * */ public byte[] getBytes() { if (null == this.wrappingKey) { return this.stream.toByteArray(); } else { AESWrapEngine engine = new AESWrapEngine(); KeyParameter params = new KeyParameter(this.wrappingKey); engine.init(true, params); PKCS7Padding padding = new PKCS7Padding(); byte[] unpadded = this.stream.toByteArray(); // // Add padding // byte[] padded = new byte[unpadded.length + (8 - unpadded.length % 8)]; System.arraycopy(unpadded, 0, padded, 0, unpadded.length); padding.addPadding(padded, unpadded.length); // // Wrap // byte[] encrypted = engine.wrap(padded, 0, padded.length); // // Add 0x0 flag and encrypted data size // ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { baos.write(GTSEncoder.FLAGS_ENCRYPTED); baos.write(Varint.encodeUnsignedLong(encrypted.length)); baos.write(encrypted); return baos.toByteArray(); } catch (IOException ioe) { return null; } } }
From source file:io.warp10.crypto.CryptoUtils.java
License:Apache License
public static byte[] wrap(byte[] key, byte[] data) { AESWrapEngine engine = new AESWrapEngine(); KeyParameter params = new KeyParameter(key); engine.init(true, params);// www . j a v a 2s . co m PKCS7Padding padding = new PKCS7Padding(); byte[] unpadded = data; // // Add padding // byte[] padded = new byte[unpadded.length + (8 - unpadded.length % 8)]; System.arraycopy(unpadded, 0, padded, 0, unpadded.length); padding.addPadding(padded, unpadded.length); // // Wrap // byte[] encrypted = engine.wrap(padded, 0, padded.length); return encrypted; }
From source file:net.sourceforge.keepassj2me.keydb.KeydbDatabase.java
License:Open Source License
/** * Encode database// ww w. j a v a2 s . c o m * @return encoded database * @throws KeydbException */ public byte[] getEncoded() throws KeydbException {//Encrypt content if (isLocked()) return this.encodedContent; if ((this.header.numGroups == 0) && (this.header.numEntries == 0)) throw new KeydbException(Config.getLocaleString(keys.KD_NOTHING_SAVE)); BufferedBlockCipher cipher = new BufferedBlockCipher(new CBCBlockCipher(new AESEngine())); //calc padding size int block_size = cipher.getBlockSize(); int pad_size = block_size - this.contentSize % block_size; // #ifdef DEBUG System.out.println("contentSize: " + this.contentSize); System.out.println("block_size: " + block_size); System.out.println("pad_size: " + pad_size); // #endif //add padding to content byte temp[] = new byte[this.contentSize + pad_size]; System.arraycopy(this.plainContent, 0, temp, 0, this.contentSize); KeydbUtil.fill(this.plainContent, (byte) 0); this.plainContent = temp; temp = null; PKCS7Padding padding = new PKCS7Padding(); padding.addPadding(this.plainContent, this.contentSize); byte encoded[] = new byte[KeydbHeader.SIZE + this.contentSize + pad_size]; //encode cipher.init(true, new ParametersWithIV(new KeyParameter(this.key), this.header.encryptionIV)); int paddedEncryptedPartSize = cipher.processBytes(this.plainContent, 0, this.plainContent.length, encoded, KeydbHeader.SIZE); if (paddedEncryptedPartSize != this.plainContent.length) { // #ifdef DEBUG System.out.println("Encoding: " + paddedEncryptedPartSize + " != " + this.plainContent.length); // #endif throw new KeydbException(Config.getLocaleString(keys.KD_ENCRYPTING_FAILED)); } //Set header this.header.contentsHash = KeydbUtil.hash(this.plainContent, 0, this.contentSize); this.header.write(encoded, 0); return encoded; }
From source file:org.cesecore.keys.token.BaseCryptoToken.java
License:Open Source License
/** * This method extracts a PrivateKey from the keystore and wraps it, using a symmetric encryption key * * @param privKeyTransform - transformation algorithm * @param spec - transformation algorithm spec (e.g: IvParameterSpec for CBC mode) * @param encryptionKeyAlias - alias of the symmetric key that will encrypt the private key * @param privateKeyAlias - alias for the PrivateKey to be extracted * @return byte[] with the encrypted extracted key * @throws NoSuchAlgorithmException if privKeyTransform is null, empty, in an invalid format, or if no Provider supports a CipherSpi * implementation for the specified algorithm. * @throws NoSuchPaddingException if privKeyTransform contains a padding scheme that is not available. * @throws NoSuchProviderException if BouncyCastle is not registered in the security provider list. * @throws InvalidKeyException if the encryption key derived from encryptionKeyAlias was invalid. * @throws IllegalBlockSizeException if the Cipher created using privKeyTransform is a block cipher, no padding has been requested, and the length * of the encoding of the key to be wrapped is not a multiple of the block size. * @throws CryptoTokenOfflineException if Crypto Token is not available or connected, or key with alias does not exist. * @throws InvalidAlgorithmParameterException if spec id not valid or supported. * @throws PrivateKeyNotExtractableException if the key is not extractable, does not exist or encryption fails *//*from ww w.ja v a2 s . c o m*/ public byte[] extractKey(String privKeyTransform, AlgorithmParameterSpec spec, String encryptionKeyAlias, String privateKeyAlias) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException, InvalidKeyException, IllegalBlockSizeException, CryptoTokenOfflineException, PrivateKeyNotExtractableException, InvalidAlgorithmParameterException { if (doPermitExtractablePrivateKey()) { // get encryption key Key encryptionKey = getKey(encryptionKeyAlias); // get private key to wrap PrivateKey privateKey = getPrivateKey(privateKeyAlias); if (privateKey == null) { throw new PrivateKeyNotExtractableException( "Extracting key with alias '" + privateKeyAlias + "' return null."); } // since SUN PKCS11 Provider does not implements WRAP_MODE, // ENCRYPT_MODE with encoded private key will be used instead, giving the same result Cipher c = null; c = Cipher.getInstance(privKeyTransform, getEncProviderName()); if (spec == null) { c.init(Cipher.ENCRYPT_MODE, encryptionKey); } else { c.init(Cipher.ENCRYPT_MODE, encryptionKey, spec); } // wrap key byte[] encryptedKey; try { byte[] data = privateKey.getEncoded(); if (StringUtils.containsIgnoreCase(privKeyTransform, "NoPadding")) { // We must add PKCS7/PKCS5 padding ourselves to the data final PKCS7Padding padding = new PKCS7Padding(); // Calculate the number of pad bytes needed final int rem = data.length % c.getBlockSize(); final int padlen = c.getBlockSize() - rem; if (log.isDebugEnabled()) { log.debug("Padding key data with " + padlen + " bytes, using PKCS7/5Padding. Total len: " + (data.length + padlen)); } byte[] newdata = Arrays.copyOf(data, data.length + padlen); padding.addPadding(newdata, data.length); data = newdata; } encryptedKey = c.doFinal(data); } catch (BadPaddingException e) { throw new PrivateKeyNotExtractableException( "Extracting key with alias '" + privateKeyAlias + "' failed."); } return encryptedKey; } else { final String msg = intres.getLocalizedMessage("token.errornotextractable", privateKeyAlias, encryptionKeyAlias); throw new PrivateKeyNotExtractableException(msg); } }