List of usage examples for org.bouncycastle.util Arrays copyOf
public static BigInteger[] copyOf(BigInteger[] original, int newLength)
From source file:org.cryptomator.filesystem.crypto.BlockAlignedReadableFileTest.java
License:Open Source License
private void testRead(File file, int blockSize) { try (ReadableFile r = new BlockAlignedReadableFile(file.openReadable(), blockSize)) { ByteBuffer buf = ByteBuffer.allocate(3); // 3.../*from www. ja v a 2s. c o m*/ r.position(3); r.read(buf); buf.flip(); Assert.assertArrayEquals(new byte[] { 0x03, 0x04, 0x05 }, Arrays.copyOf(buf.array(), buf.remaining())); // go on... buf.clear(); r.read(buf); buf.flip(); Assert.assertArrayEquals(new byte[] { 0x06, 0x07, 0x08 }, Arrays.copyOf(buf.array(), buf.remaining())); // go on till EOF... buf.clear(); r.read(buf); buf.flip(); Assert.assertArrayEquals(new byte[] { 0x09 }, Arrays.copyOf(buf.array(), buf.remaining())); // back to 4... r.position(4); buf.clear(); r.read(buf); buf.flip(); Assert.assertArrayEquals(new byte[] { 0x04, 0x05, 0x06 }, Arrays.copyOf(buf.array(), buf.remaining())); } }
From source file:org.ethereum.util.RLP.java
License:Open Source License
public static byte[] encodeElement(@Nullable byte[] srcData) { if (srcData == null || srcData.length == 0) { return new byte[] { (byte) OFFSET_SHORT_ITEM }; } else if (isSingleZero(srcData)) { return srcData; } else if (srcData.length == 1 && (srcData[0] & 0xFF) < OFFSET_SHORT_ITEM) { return srcData; } else if (srcData.length < SIZE_THRESHOLD) { // length = 8X byte length = (byte) (OFFSET_SHORT_ITEM + srcData.length); byte[] data = Arrays.copyOf(srcData, srcData.length + 1); System.arraycopy(data, 0, data, 1, srcData.length); data[0] = length;/*from w ww . j av a2 s . com*/ return data; } else { // length of length = BX // prefix = [BX, [length]] int tmpLength = srcData.length; byte byteNum = 0; while (tmpLength != 0) { ++byteNum; tmpLength = tmpLength >> 8; } byte[] lenBytes = new byte[byteNum]; for (int i = 0; i < byteNum; ++i) { lenBytes[byteNum - 1 - i] = (byte) ((srcData.length >> (8 * i)) & 0xFF); } // first byte = F7 + bytes.length byte[] data = Arrays.copyOf(srcData, srcData.length + 1 + byteNum); System.arraycopy(data, 0, data, 1 + byteNum, srcData.length); data[0] = (byte) (OFFSET_LONG_ITEM + byteNum); System.arraycopy(lenBytes, 0, data, 1, lenBytes.length); return data; } }
From source file:org.hyperledger.common.MasterPrivateKey.java
License:Apache License
/** * Recreate a key from BIP32 serialization * * @param serialized/* w w w . j av a 2s. c o m*/ * @return MasterPrivateKey * @throws HyperLedgerException */ public static MasterPrivateKey parse(String serialized) throws HyperLedgerException { byte[] data = ByteUtils.fromBase58WithChecksum(serialized); if (data.length != 78) { throw new HyperLedgerException("invalid master key"); } byte[] type = Arrays.copyOf(data, 4); if (!Arrays.areEqual(type, xprv) && !Arrays.areEqual(type, tprv)) { throw new HyperLedgerException("invalid magic number for a master private key"); } int depth = data[4] & 0xff; int parent = data[5] & 0xff; parent <<= 8; parent |= data[6] & 0xff; parent <<= 8; parent |= data[7] & 0xff; parent <<= 8; parent |= data[8] & 0xff; int sequence = data[9] & 0xff; sequence <<= 8; sequence |= data[10] & 0xff; sequence <<= 8; sequence |= data[11] & 0xff; sequence <<= 8; sequence |= data[12] & 0xff; byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32); byte[] pubOrPriv = Arrays.copyOfRange(data, 13 + 32, data.length); return new MasterPrivateKey(new PrivateKey(new BigInteger(1, pubOrPriv), true), chainCode, depth, parent, sequence); }
From source file:org.hyperledger.common.MasterPublicKey.java
License:Apache License
/** * Parse a MasterPublickey from its BIP32 compliant serialization. * * @param serialized a Base58 string/*from w ww.ja v a2 s .c o m*/ * @return a master key * @throws HyperLedgerException for invalid format */ public static MasterPublicKey parse(String serialized) throws HyperLedgerException { byte[] data = ByteUtils.fromBase58WithChecksum(serialized); if (data.length != 78) { throw new HyperLedgerException("invalid extended key"); } byte[] type = Arrays.copyOf(data, 4); if (!Arrays.areEqual(type, xpub) && !Arrays.areEqual(type, tpub)) { throw new HyperLedgerException("invalid magic number for an master public key"); } int depth = data[4] & 0xff; int parent = data[5] & 0xff; parent <<= 8; parent |= data[6] & 0xff; parent <<= 8; parent |= data[7] & 0xff; parent <<= 8; parent |= data[8] & 0xff; int sequence = data[9] & 0xff; sequence <<= 8; sequence |= data[10] & 0xff; sequence <<= 8; sequence |= data[11] & 0xff; sequence <<= 8; sequence |= data[12] & 0xff; byte[] chainCode = Arrays.copyOfRange(data, 13, 13 + 32); byte[] pubOrPriv = Arrays.copyOfRange(data, 13 + 32, data.length); return new MasterPublicKey(new PublicKey(pubOrPriv, true), chainCode, depth, parent, sequence); }
From source file:org.multibit.viewsystem.swing.action.CreateRemoteWalletSubmitAction.java
License:MIT License
public void createNewWallet(String newWalletFilename) { String message;/* w w w. ja v a 2s.co m*/ if (new File(newWalletFilename).isDirectory()) { message = controller.getLocaliser().getString("createNewWalletAction.walletFileIsADirectory", new Object[] { newWalletFilename }); log.debug(message); MessageManager.INSTANCE.addMessage(new Message(message)); return; } // If the filename has no extension, put on the wallet extension. if (!newWalletFilename.contains(".")) { newWalletFilename = newWalletFilename + "." + BitcoinModel.WALLET_FILE_EXTENSION; } File newWalletFile = new File(newWalletFilename); boolean theWalletWasNotOpenedSuccessfully = false; try { // If file exists, load the existing wallet. if (newWalletFile.exists()) { WalletData perWalletModelData = this.bitcoinController.getFileHandler().loadFromFile(newWalletFile); if (perWalletModelData != null) { // Use the existing wallet. this.bitcoinController.addWalletFromFilename(newWalletFile.getAbsolutePath()); this.bitcoinController.getModel().setActiveWalletByFilename(newWalletFilename); controller.getModel().setUserPreference(BitcoinModel.GRAB_FOCUS_FOR_ACTIVE_WALLET, "true"); controller.fireRecreateAllViews(true); controller.fireDataChangedUpdateNow(); } } else { // Create a new wallet - protobuf.2 initially for backwards compatibility. Wallet newWallet = new Wallet(this.bitcoinController.getModel().getNetworkParameters()); SecureRandom prGen = new SecureRandom(); byte[] oneTimePass = new byte[256]; prGen.nextBytes(oneTimePass); SignatureTest t = new SignatureTest(2); PublicParameters params = new PublicParameters(SignatureTest.CURVE, t.nHat, t.kPrime, t.h1, t.h2, t.alicesPallierPubKey, t.otherPallierPubKey); Alice alice = new Alice(t.aliceShare, t.publicKey, new SecureRandom(), t.paillier, params); File keystore = new File(KEYSTORE_FILENAME); Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); KeyStore ks = KeyStore.getInstance("BKS"); if (!keystore.exists()) { MakeCertificate.generateSelfSignedCertificate("compTLSCert", keystore, KEYSTORE_PASSWORD); } ks.load(new FileInputStream(keystore), KEYSTORE_PASSWORD.toCharArray()); X509Certificate cert = (X509Certificate) ks.getCertificate("compTLSCert"); byte[] certBytes = cert.getEncoded(); System.out.println("cert is " + certBytes.length + " bytes"); byte[] fullBytes = Arrays.copyOf(oneTimePass, oneTimePass.length + certBytes.length); System.arraycopy(certBytes, 0, fullBytes, oneTimePass.length, certBytes.length); String fullString = DatatypeConverter.printBase64Binary(fullBytes); QRCodeWriter writer = new QRCodeWriter(); Map<EncodeHintType, Object> hints = new EnumMap<EncodeHintType, Object>(EncodeHintType.class); hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, 0); BitMatrix matrix = writer.encode(fullString, BarcodeFormat.QR_CODE, 300, 300, hints); BufferedImage image = new BufferedImage(TAM_QRCODE, TAM_QRCODE, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, TAM_QRCODE, TAM_QRCODE); graphics.setColor(Color.BLACK); for (int i = matrix.getTopLeftOnBit()[0]; i < TAM_QRCODE; i++) { for (int j = matrix.getTopLeftOnBit()[1]; j < TAM_QRCODE; j++) { if (matrix.get(i, j)) { graphics.fillRect(i, j, 1, 1); } } } ByteArrayOutputStream os = new ByteArrayOutputStream(); ImageIO.write(image, "png", os); Icon icon = new ImageIcon(image); JLabel iconLabel = new JLabel(icon); JPanel iconPanel = new JPanel(new GridBagLayout()); iconPanel.add(iconLabel); JPanel mainPanel = new JPanel(new BorderLayout()); JLabel label = new JLabel( "Capture this image to pair with phone. Warning: This will never be shown again"); Border paddingBorder = BorderFactory.createEmptyBorder(30, 10, 10, 10); label.setBorder(paddingBorder); mainPanel.add(label); mainPanel.add(iconPanel, BorderLayout.NORTH); log.debug("Showing wallet qr panel"); JOptionPane.showMessageDialog(null, mainPanel, "Two Factor", JOptionPane.PLAIN_MESSAGE); log.debug("Showed wallet qr panel"); log.debug("Trying to create ECKey"); RemoteECKey newKey = new RemoteECKey(alice, params, t.bobShare, t.publicKey, oneTimePass, keystore, KEYSTORE_PASSWORD); log.debug("Finished trying to create ECKey"); String filename = Utils.bytesToHexString(newKey.getPubKeyHash()); FileOutputStream fileOut = new FileOutputStream("/Users/hkalodner/btfa_work/" + filename + ".key"); ObjectOutputStream out = new ObjectOutputStream(fileOut); out.writeObject(newKey); out.close(); fileOut.close(); log.debug("Created ECKey"); newWallet.addKey(newKey); WalletData perWalletModelData = new WalletData(); perWalletModelData.setWalletInfo( new WalletInfoData(newWalletFilename, newWallet, MultiBitWalletVersion.PROTOBUF)); perWalletModelData.setWallet(newWallet); perWalletModelData.setWalletFilename(newWalletFilename); perWalletModelData.setWalletDescription( controller.getLocaliser().getString("createNewWalletSubmitAction.defaultDescription")); this.bitcoinController.getFileHandler().savePerWalletModelData(perWalletModelData, true); // Start using the new file as the wallet. this.bitcoinController.addWalletFromFilename(newWalletFile.getAbsolutePath()); this.bitcoinController.getModel().setActiveWalletByFilename(newWalletFilename); controller.getModel().setUserPreference(BitcoinModel.GRAB_FOCUS_FOR_ACTIVE_WALLET, "true"); // Save the user properties to disk. FileHandler.writeUserPreferences(this.bitcoinController); log.debug("User preferences with new wallet written successfully"); // Backup the wallet and wallet info. BackupManager.INSTANCE.backupPerWalletModelData(bitcoinController.getFileHandler(), perWalletModelData); controller.fireRecreateAllViews(true); controller.fireDataChangedUpdateNow(); } } catch (WalletLoadException e) { e.printStackTrace(); message = controller.getLocaliser().getString("createNewWalletAction.walletCouldNotBeCreated", new Object[] { newWalletFilename, e.getMessage() }); log.error(message); MessageManager.INSTANCE.addMessage(new Message(message)); theWalletWasNotOpenedSuccessfully = true; } catch (WalletSaveException e) { e.printStackTrace(); message = controller.getLocaliser().getString("createNewWalletAction.walletCouldNotBeCreated", new Object[] { newWalletFilename, e.getMessage() }); log.error(message); MessageManager.INSTANCE.addMessage(new Message(message)); theWalletWasNotOpenedSuccessfully = true; } catch (WalletVersionException e) { e.printStackTrace(); message = controller.getLocaliser().getString("createNewWalletAction.walletCouldNotBeCreated", new Object[] { newWalletFilename, e.getMessage() }); log.error(message); MessageManager.INSTANCE.addMessage(new Message(message)); theWalletWasNotOpenedSuccessfully = true; } catch (IOException e) { e.printStackTrace(); message = controller.getLocaliser().getString("createNewWalletAction.walletCouldNotBeCreated", new Object[] { newWalletFilename, e.getMessage() }); log.error(message); MessageManager.INSTANCE.addMessage(new Message(message)); theWalletWasNotOpenedSuccessfully = true; } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (WriterException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } if (theWalletWasNotOpenedSuccessfully) { WalletData loopData = this.bitcoinController.getModel() .getPerWalletModelDataByWalletFilename(newWalletFilename); if (loopData != null) { // Clear the backup wallet filename - this prevents it being automatically overwritten. if (loopData.getWalletInfo() != null) { loopData.getWalletInfo().put(BitcoinModel.WALLET_BACKUP_FILE, ""); } } } }
From source file:org.panbox.core.crypto.Obfuscator.java
License:Open Source License
private synchronized byte[] createIV(String originalFileName, SecretKey obKey) throws ObfuscationException { try {/*from w w w . ja va 2s .c om*/ ivDigest.update(originalFileName.getBytes(PanboxConstants.STANDARD_CHARSET)); ivDigest.update(obKey.getEncoded()); byte[] hash = ivDigest.digest(); // truncate to IV size return Arrays.copyOf(hash, KeyConstants.SYMMETRIC_BLOCK_SIZE); } catch (UnsupportedEncodingException e) { logger.error("Unsupported encoding", e); throw new ObfuscationException("Error creating IV for filename due to unsupported encoding!", e); } }
From source file:org.sejda.sambox.encryption.Algorithm1.java
License:Apache License
private Algorithm1(EncryptionAlgorithmEngine engine, byte[] key) { requireNotNullArg(engine, "Encryption engine cannot be null"); requireArg(key != null && key.length > 0, "Encryption key cannot be blank"); this.engine = engine; keyCalculator = (cosKey) -> {//from w w w. java2s.c o m requireNotNullArg(cosKey, "Cannot encrypt a reference with a null key"); byte[] append = new byte[5]; append[0] = (byte) (cosKey.objectNumber() & 0xff); append[1] = (byte) (cosKey.objectNumber() >> 8 & 0xff); append[2] = (byte) (cosKey.objectNumber() >> 16 & 0xff); append[3] = (byte) (cosKey.generation() & 0xff); append[4] = (byte) (cosKey.generation() >> 8 & 0xff); return concatenate(key, append); }; md5Initializer = (newKey) -> { digest.reset(); digest.update(newKey); return newKey; }; md5ToKey = (newKey) -> { return Arrays.copyOf(digest.digest(), Math.min(newKey.length, 16)); }; }
From source file:org.sejda.sambox.encryption.Algorithm2BExtensionLevel3.java
License:Apache License
@Override public byte[] computeHash(byte[] input, byte[] password) { return Arrays.copyOf(digest.digest(input), 32); }
From source file:org.sejda.sambox.encryption.Algorithm3.java
License:Apache License
@Override public byte[] computePassword(EncryptionContext context) { byte[] ownerBytes = context.security.getOwnerPassword(); byte[] userBytes = context.security.getUserPassword(); byte[] padded = padOrTruncate(of(ownerBytes).filter(p -> p.length > 0).orElseGet(() -> userBytes)); byte[] paddedUser = padOrTruncate(userBytes); digest.reset();/*w w w.ja v a 2s .c o m*/ byte[] arc4Key = digest.digest(padded); if (StandardSecurityHandlerRevision.R3.compareTo(context.security.encryption.revision) <= 0) { for (int i = 0; i < 50; ++i) { digest.update(arc4Key, 0, context.security.encryption.revision.length); arc4Key = Arrays.copyOf(digest.digest(), context.security.encryption.revision.length); } byte[] encrypted = engine.encryptBytes(paddedUser, arc4Key); byte[] iterationKey = new byte[arc4Key.length]; for (int i = 1; i < 20; i++) { iterationKey = Arrays.copyOf(arc4Key, arc4Key.length); for (int j = 0; j < iterationKey.length; j++) { iterationKey[j] = (byte) (iterationKey[j] ^ (byte) i); } encrypted = engine.encryptBytes(encrypted, iterationKey); } return encrypted; } return engine.encryptBytes(paddedUser, arc4Key); }
From source file:org.sejda.sambox.encryption.Algorithm5.java
License:Apache License
@Override public byte[] computePassword(EncryptionContext context) { context.security.encryption.revision.requireAtLeast(StandardSecurityHandlerRevision.R3, "Algorithm 5 requires a security handler of revision 3 or greater"); digest.reset();//w ww .j av a 2 s. com digest.update(ENCRYPT_PADDING); byte[] encrypted = engine.encryptBytes(Arrays.copyOf(digest.digest(context.documentId()), 16), context.key()); byte[] iterationKey = new byte[context.key().length]; for (int i = 1; i < 20; i++) { iterationKey = Arrays.copyOf(context.key(), context.key().length); for (int j = 0; j < iterationKey.length; j++) { iterationKey[j] = (byte) (iterationKey[j] ^ (byte) i); } encrypted = engine.encryptBytes(encrypted, iterationKey); } return Arrays.concatenate(Arrays.copyOf(encrypted, 16), Arrays.copyOf(ENCRYPT_PADDING, 16)); }