List of usage examples for org.bouncycastle.openpgp PGPException PGPException
public PGPException(String message, Exception underlying)
From source file:genkeys.java
License:Open Source License
private static Cipher cipher(int code) throws NoSuchProviderException, PGPException { String cName = symmetricCipherName(code); Cipher c = null;/* www.j av a2 s . c o m*/ if (cName != null) { try { c = Cipher.getInstance(cName + "/CFB/NoPadding", "BC"); } catch (NoSuchProviderException e) { throw e; } catch (Exception e) { throw new PGPException("Exception creating cipher", e); } } return c; }
From source file:genkeys.java
License:Open Source License
private static byte[] checksum(boolean useSHA1, byte[] bytes, int length) throws PGPException { if (useSHA1) { try {/* w w w.j a v a2s .com*/ MessageDigest dig = MessageDigest.getInstance("SHA1"); dig.update(bytes, 0, length); return dig.digest(); } catch (NoSuchAlgorithmException e) { throw new PGPException("Can't find SHA-1", e); } } else { int checksum = 0; for (int i = 0; i != length; i++) { checksum += bytes[i] & 0xff; } byte[] check = new byte[2]; check[0] = (byte) (checksum >> 8); check[1] = (byte) checksum; return check; } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Encrypt the specified input file//from w w w. ja v a 2s. c o m * @throws FileNotFoundException */ public void encryptFile(OutputStream out, File inFile, PGPPublicKeyRingCollection pubRing, PGPSecretKeyRingCollection secRing, String recipient, char[] passphrase, byte[] seed) throws PGPException, FileNotFoundException { long time = inFile.lastModified(); try { encryptFile(out, new FileInputStream(inFile), inFile.getName(), inFile.length(), new Date(time), readPublicKey(pubRing, recipient, true), false, false, false, passphrase, seed); } catch (IOException e) { throw new PGPException("Failed to read public key from keyring", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Encrypt the specified input file/* w ww. j ava 2s. c o m*/ */ public void encryptFile(OutputStream out, InputStream in, String inName, long inLength, Date inDate, PGPPublicKeyRingCollection pubRing, PGPSecretKeyRingCollection secRing, String recipient, char[] passphrase, byte[] seed) throws PGPException { try { encryptFile(out, in, inName, inLength, inDate, readPublicKey(pubRing, recipient, true), false, false, false, passphrase, seed); } catch (IOException e) { throw new PGPException("Failed to read public key from keyring", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * UNUSED IN FRIENDLY BACKUP//from ww w .j a v a 2s.c o m * Sign the passed in message stream (version 3 signature) */ private void signDataV3(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws PGPException { try { PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut)); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(true); PGPV3SignatureGenerator s3Gen = new PGPV3SignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC"); s3Gen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); s3Gen.generateOnePassVersion(false).encode(bOut); OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile); FileInputStream fIn = new FileInputStream(inFile); int ch; while ((ch = fIn.read()) >= 0) { lOut.write(ch); s3Gen.update((byte) ch); } fIn.close(); // close() finishes the writing of the literal data and flushes the stream // It does not close bOut so this is ok here lGen.close(); // Generate the signature s3Gen.generate().encode(bOut); // Must not close bOut here bOut.finish(); bOut.flush(); cGen.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in signing", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Sign the passed in message stream//from w ww . j ava2 s . co m */ private void signData(File inFile, OutputStream aOut, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws PGPException { try { PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(aOut)); PGPLiteralDataGenerator lGen = new PGPLiteralDataGenerator(); PGPSignatureGenerator sGen = new PGPSignatureGenerator(publicKey.getAlgorithm(), PGPUtil.SHA1, "BC"); sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey); @SuppressWarnings("unchecked") Iterator<String> users = publicKey.getUserIDs(); if (users.hasNext()) { PGPSignatureSubpacketGenerator spGen = new PGPSignatureSubpacketGenerator(); spGen.setSignerUserID(false, users.next()); sGen.setHashedSubpackets(spGen.generate()); } sGen.generateOnePassVersion(false).encode(bOut); OutputStream lOut = lGen.open(bOut, PGPLiteralData.BINARY, inFile); FileInputStream fIn = new FileInputStream(inFile); int ch; while ((ch = fIn.read()) >= 0) { lOut.write(ch); sGen.update((byte) ch); } fIn.close(); // close() finishes the writing of the literal data and flushes the stream // It does not close bOut so this is ok here lGen.close(); // Generate the signature sGen.generate().encode(bOut); // Must not close bOut here bOut.finish(); bOut.flush(); cGen.close(); } catch (PGPException e) { throw e; } catch (Exception e) { throw new PGPException("Error in signing", e); } }
From source file:com.geekcommune.identity.EncryptionUtil.java
License:Open Source License
/** * Compress the data in the input stream *///from w w w. j a v a 2s . c o m public void compressData(InputStream fIn, OutputStream bOut, String fileName, long dataLength, Date date, boolean oldFormat, Format compress) throws PGPException { try { if (compress == Format.COMPRESSED) { PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedData.ZIP); bOut = comData.open(bOut); } PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator(oldFormat); OutputStream pOut = lData.open(bOut, PGPLiteralData.BINARY, fileName, dataLength, date); byte[] bytes = new byte[4096]; int len; while ((len = fIn.read(bytes)) > 0) { pOut.write(bytes, 0, len); } fIn.close(); lData.close(); if (compress == Format.COMPRESSED) { bOut.close(); } } catch (Exception e) { throw new PGPException("Error in encryption", e); } }
From source file:divconq.pgp.EncryptedFileStream.java
License:Open Source License
public void close() throws PGPException { if (this.isClosed) return;//www . j a v a 2 s . com this.isClosed = true; if (this.packetbuf != null) { // flush data if any packet space is available this.writeData(new byte[0], 0, 0); this.packetsize = this.packetbuf.readableBytes(); this.packetpos = 0; // even if zero, this is fine, we need a final packet this.writeDataPacketLength(this.packetsize); if (this.packetsize > 0) this.writeData(new byte[0], 0, 0); this.packetbuf.release(); this.packetbuf = null; } if (this.algorithm != SymmetricKeyAlgorithmTags.NULL) { this.ensureBuffer(22); this.writeDataInternal((byte) (0xC0 | PacketTags.MOD_DETECTION_CODE)); this.writeDataInternal((byte) 20); // length of SHA-1 is always 20 bytes this.writeDataInternal(this.digest.digest(), 0, 20); // TODO final compression, pass into doFinal below byte[] fcipher; try { fcipher = this.cipher.doFinal(); } catch (Exception x) { throw new PGPException("Problem with PGP cipher", x); } this.ensureBuffer(fcipher.length); this.out.writeBytes(fcipher); // write raw } else { // TODO final compression, if any } this.readyBuffers.add(this.out); this.out = null; }
From source file:divconq.test.pgp.PGPWriter.java
License:Open Source License
public void open(int algorithm, PGPKeyEncryptionMethodGenerator... methods) throws IOException, PGPException, IllegalStateException { if (methods.length == 0) throw new IllegalStateException("no encryption methods specified"); this.algorithm = algorithm; // ******************************************************************* // public key packet // ******************************************************************* // TODO this condition untested and perhaps not helpful, review (PBE - password based encryption) if ((methods.length == 1) && (methods[0] instanceof PBEKeyEncryptionMethodGenerator)) { PBEKeyEncryptionMethodGenerator m = (PBEKeyEncryptionMethodGenerator) methods[0]; this.key = m.getKey(algorithm); this.writePacket(m.generate(algorithm, null)); } else {/*from w w w . java2 s .c o m*/ this.key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand); byte[] sessionInfo = this.createSessionInfo(); for (int i = 0; i < methods.length; i++) { PGPKeyEncryptionMethodGenerator m = (PGPKeyEncryptionMethodGenerator) methods[i]; this.writePacket(m.generate(algorithm, sessionInfo)); } } int packet1 = this.out.writerIndex(); System.out.println("packet 1: " + packet1 + " final bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet1 - 5, 5)); // ******************************************************************* // encrypt packet, add IV to // ******************************************************************* try { String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding"; DefaultJcaJceHelper helper = new DefaultJcaJceHelper(); this.cipher = helper.createCipher(cName); byte[] iv = new byte[this.cipher.getBlockSize()]; this.cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, this.key), new IvParameterSpec(iv)); // // we have to add block size + 2 for the generated IV and + 1 + 22 if integrity protected // this.ensureBuffer(this.cipher.getBlockSize() + 2 + 1 + 22); this.startPartialPacket(PacketTags.SYM_ENC_INTEGRITY_PRO); //, this.cipher.getBlockSize() + 2 + 1 + 22); this.out.writeByte(1); // version number byte[] inLineIv = new byte[this.cipher.getBlockSize() + 2]; this.rand.nextBytes(inLineIv); inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3]; inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; // TODO byte[] any = this.cipher.update(inLineIv); if (any != null) this.out.writeBytes(any); // we may include this in digest, TODO review } catch (InvalidKeyException e) { throw new PGPException("invalid key: " + e.getMessage(), e); } catch (InvalidAlgorithmParameterException e) { throw new PGPException("imvalid algorithm parameter: " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new PGPException("cannot create cipher: " + e.getMessage(), e); } int packet2 = this.out.writerIndex(); System.out.println("packet 2: first bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet1, 25)); System.out.println("packet 2: " + packet2 + " final bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet2 - 5, 5)); // ******************************************************************* // TODO compress packet, if any // ******************************************************************* int packet3 = this.out.writerIndex(); //System.out.println("packet 3: first bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet2, 25)); //System.out.println("packet 3: " + packet3 + " final bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet3 - 5, 5)); // ******************************************************************* // literal packet start // ******************************************************************* this.startPartialPacket(PacketTags.LITERAL_DATA); byte[] encName = Utf8Encoder.encode(this.fileName); // TODO don't hard code int len = 1 + 1 + encName.length + 4 + 99; // type + name length + name + mod time + file content //out.writeByte(len); this.writeNewPacketLength(len); out.writeByte(PGPLiteralData.BINARY); out.writeByte((byte) encName.length); out.writeBytes(encName); long modDate = this.modificationTime / 1000; out.writeByte((byte) (modDate >> 24)); out.writeByte((byte) (modDate >> 16)); out.writeByte((byte) (modDate >> 8)); out.writeByte((byte) (modDate)); int packet4 = this.out.writerIndex(); System.out.println("packet 4: first bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet3, 25)); System.out.println("packet 4: " + packet4 + " final bytes: " + HexUtil.bufferToHex(this.out.array(), this.out.arrayOffset() + packet4 - 5, 5)); // TODO new SHA1PGPDigestCalculator(); //if (digestCalc != null) // genOut = new TeeOutputStream(digestCalc.getOutputStream(), genOut); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Sign a message using our private PGP key file, this matches gpg -ab "hello.txt". This will save the signature of the passed-in * file to file name + .asc// w w w . jav a2s.c o m * * @param privateKeyInputStream * this is an armored key file, not a binary stream * @param userId * this is the userID to get out of the private key * @param password * this is the password to unlock the private key * @param file * this is the file to sign */ public static void signGpgCompatible(InputStream privateKeyInputStream, String userId, char[] password, File file) throws PGPException { // the signature type (in gpg terms), is "sigclass". gpg is BINARY_DOC (0x00) final byte[] sign = sign(privateKeyInputStream, userId, password, file, PGPSignature.BINARY_DOCUMENT, false, true, false, false, false); FileOutputStream fileOutputStream1 = null; try { fileOutputStream1 = new FileOutputStream(new File(file.getAbsolutePath() + ".asc")); fileOutputStream1.write(sign); fileOutputStream1.flush(); } catch (FileNotFoundException e) { throw new PGPException("Unable to save signature to file " + file.getAbsolutePath() + ".asc", e); } catch (IOException e) { throw new PGPException("Unable to save signature to file " + file.getAbsolutePath() + ".asc", e); } finally { IO.close(fileOutputStream1); } }