List of usage examples for org.bouncycastle.openpgp PGPPublicKeyRingCollection PGPPublicKeyRingCollection
public PGPPublicKeyRingCollection(InputStream in, KeyFingerPrintCalculator fingerPrintCalculator) throws IOException, PGPException
From source file:bisq.desktop.main.overlays.windows.downloadupdate.BisqInstaller.java
License:Open Source License
/** * Verifies detached PGP signatures against GPG/openPGP RSA public keys. Does currently not work with openssl or JCA/JCE keys. * * @param pubKeyFile Path to file providing the public key to use * @param sigFile Path to detached signature file * @param dataFile Path to signed data file * @return {@code true} if signature is valid, {@code false} if signature is not valid * @throws Exception throws various exceptions in case something went wrong. Main reason should be that key or * signature could be extracted from the provided files due to a "bad" format.<br> * <code>FileNotFoundException, IOException, SignatureException, PGPException</code> */// ww w. ja v a 2 s . c o m public static VerifyStatusEnum verifySignature(File pubKeyFile, File sigFile, File dataFile) throws Exception { InputStream inputStream; int bytesRead; PGPPublicKey publicKey; PGPSignature pgpSignature; boolean result; // Read keys from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(pubKeyFile)); PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(inputStream, new JcaKeyFingerprintCalculator()); inputStream.close(); Iterator<PGPPublicKeyRing> iterator = publicKeyRingCollection.getKeyRings(); PGPPublicKeyRing pgpPublicKeyRing; if (iterator.hasNext()) { pgpPublicKeyRing = iterator.next(); } else { throw new PGPException("Could not find public keyring in provided key file"); } // Would be the solution for multiple keys in one file // Iterator<PGPPublicKey> kIt; // kIt = pgpPublicKeyRing.getPublicKeys(); // publicKey = pgpPublicKeyRing.getPublicKey(0xF5B84436F379A1C6L); // Read signature from file inputStream = PGPUtil.getDecoderStream(new FileInputStream(sigFile)); PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(inputStream, new JcaKeyFingerprintCalculator()); Object o = pgpObjectFactory.nextObject(); if (o instanceof PGPSignatureList) { PGPSignatureList signatureList = (PGPSignatureList) o; checkArgument(!signatureList.isEmpty(), "signatureList must not be empty"); pgpSignature = signatureList.get(0); } else if (o instanceof PGPSignature) { pgpSignature = (PGPSignature) o; } else { throw new SignatureException("Could not find signature in provided signature file"); } inputStream.close(); log.debug("KeyID used in signature: %X\n", pgpSignature.getKeyID()); publicKey = pgpPublicKeyRing.getPublicKey(pgpSignature.getKeyID()); // If signature is not matching the key used for signing we fail if (publicKey == null) return VerifyStatusEnum.FAIL; log.debug("The ID of the selected key is %X\n", publicKey.getKeyID()); pgpSignature.init(new BcPGPContentVerifierBuilderProvider(), publicKey); // Read file to verify byte[] data = new byte[1024]; inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); while (true) { bytesRead = inputStream.read(data, 0, 1024); if (bytesRead == -1) break; pgpSignature.update(data, 0, bytesRead); } inputStream.close(); // Verify the signature result = pgpSignature.verify(); return result ? VerifyStatusEnum.OK : VerifyStatusEnum.FAIL; }
From source file:cc.arduino.contributions.GPGDetachedSignatureVerifier.java
License:Open Source License
private PGPPublicKey readPublicKey(InputStream input, String keyId) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new BcKeyFingerprintCalculator()); Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (Long.toHexString(key.getKeyID()).toUpperCase().endsWith(keyId)) { return key; }//from www . j a v a 2 s .c o m } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }
From source file:com.github.s4u.plugins.PGPKeysCache.java
License:Apache License
PGPPublicKey getKey(long keyID) throws IOException, PGPException { File keyFile = null;//ww w.j a v a 2s.c o m PGPPublicKey key = null; try { String path = String.format("%02X/%02X/%016X.asc", (byte) (keyID >> 56), (byte) (keyID >> 48 & 0xff), keyID); keyFile = new File(cachePath, path); if (!keyFile.exists()) { receiveKey(keyFile, keyID); } InputStream keyIn = PGPUtil.getDecoderStream(new FileInputStream(keyFile)); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); key = pgpRing.getPublicKey(keyID); } finally { if (key == null) { deleteFile(keyFile); } } return key; }
From source file:com.markuspage.jbinrepoproxy.standalone.trust.file.PropertiesFileTrustMap.java
License:Open Source License
private static List<PGPPublicKey> parsePublicKeys(File file) throws IOException, PGPException { final ArrayList<PGPPublicKey> results = new ArrayList<>(); BufferedReader reader = null; try {//from ww w . j a v a2 s.c o m reader = new BufferedReader(new FileReader(file)); String line; while ((line = reader.readLine()) != null) { if (!line.equals(BEGIN_PUBLIC_KEY)) { LOG.debug("Skipping: {}", line); } else { final StringBuilder buff = new StringBuilder(); buff.append(BEGIN_PUBLIC_KEY).append("\n"); while ((line = reader.readLine()) != null && !line.equals(END_PUBLIC_KEY)) { buff.append(line).append("\n"); } if (line == null) { throw new IOException("Premature end of file, expected " + END_PUBLIC_KEY); } buff.append(END_PUBLIC_KEY).append("\n"); // Now parse the key InputStream keyIn = PGPUtil .getDecoderStream(new ByteArrayInputStream(buff.toString().getBytes())); PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(keyIn, new BcKeyFingerprintCalculator()); Iterator<PGPPublicKeyRing> keyRings = pgpRing.getKeyRings(); while (keyRings.hasNext()) { PGPPublicKeyRing ring = keyRings.next(); Iterator<PGPPublicKey> publicKeys = ring.getPublicKeys(); while (publicKeys.hasNext()) { PGPPublicKey publicKey = publicKeys.next(); results.add(publicKey); } } } } } finally { if (reader != null) { try { reader.close(); } catch (IOException ex) { LOG.warn("Failed to close reader", ex); } } } return results; }
From source file:de.sandmage.opportunisticmail.crypto.OpenPGP.java
License:Open Source License
public PGPPublicKey getPublicKeyFromString(String data) { InputStream input = new ByteArrayInputStream(data.getBytes()); try {//from w w w . jav a 2s .c o m PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (PGPException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; }
From source file:divconq.pgp.EncryptedFileStream.java
License:Open Source License
public void loadPublicKey(Path keyring) throws IOException, PGPException { // TODO move some of this to dcPGPUtil PGPPublicKey pubKey = null;//from ww w.j ava 2s . c om InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring.toFile())); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && (pubKey == null)) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext() && (pubKey == null)) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) pubKey = key; } } if (pubKey == null) throw new IllegalArgumentException("Can't find encryption key in key ring."); this.methods.add(new JcePublicKeyKeyEncryptionMethodGenerator(pubKey)); }
From source file:divconq.test.pgp.PGPWriter2.java
License:Open Source License
@SuppressWarnings("resource") public void test2(String srcpath, String destpath, String keyring) throws Exception { Path src = Paths.get(srcpath); // file data byte[] fileData = Files.readAllBytes(src); // dest//from w w w. j av a2 s . com OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath)); // encryption key PGPPublicKey pubKey = null; InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && (pubKey == null)) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext() && (pubKey == null)) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) pubKey = key; } } if (pubKey == null) throw new IllegalArgumentException("Can't find encryption key in key ring."); String fileName = src.getFileName().toString(); byte[] encName = Utf8Encoder.encode(fileName); long modificationTime = System.currentTimeMillis(); SecureRandom rand = new SecureRandom(); int algorithm = PGPEncryptedData.AES_256; Cipher cipher = null; ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb // ******************************************************************* // public key packet // ******************************************************************* PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey); byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand); byte[] sessionInfo = new byte[key.length + 3]; // add algorithm sessionInfo[0] = (byte) algorithm; // add key System.arraycopy(key, 0, sessionInfo, 1, key.length); // add checksum int check = 0; for (int i = 1; i != sessionInfo.length - 2; i++) check += sessionInfo[i] & 0xff; sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8); sessionInfo[sessionInfo.length - 1] = (byte) (check); ContainedPacket packet1 = method.generate(algorithm, sessionInfo); byte[] encoded1 = packet1.getEncoded(); leadingbuf.writeBytes(encoded1); // ******************************************************************* // encrypt packet, add IV to encryption though // ******************************************************************* leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO); this.writePacketLength(leadingbuf, 0); // 0 = we don't know leadingbuf.writeByte(1); // version number String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding"; DefaultJcaJceHelper helper = new DefaultJcaJceHelper(); cipher = helper.createCipher(cName); byte[] iv = new byte[cipher.getBlockSize()]; cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv)); // ******************** start encryption ********************** // --- encrypt checksum for encrypt packet, part of the encrypted output --- byte[] inLineIv = new byte[cipher.getBlockSize() + 2]; rand.nextBytes(inLineIv); inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3]; inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; encbuf.writeBytes(inLineIv); System.out.println("bytes written a: " + encbuf.readableBytes()); // --- data packet --- int chunkpos = 0; int headerlen = 1 // format + 1 // name length + encName.length // file name + 4; // time encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA); int packetsize = 512 - headerlen; if (fileData.length - chunkpos < packetsize) { packetsize = fileData.length - chunkpos; this.writePacketLength(encbuf, headerlen + packetsize); } else { encbuf.writeByte(0xE9); // 512 packet length } System.out.println("bytes written b: " + encbuf.readableBytes()); encbuf.writeByte(PGPLiteralData.BINARY); // data format encbuf.writeByte((byte) encName.length); // file name encbuf.writeBytes(encName); encbuf.writeInt((int) (modificationTime / 1000)); // mod time System.out.println("bytes written c: " + encbuf.readableBytes()); encbuf.writeBytes(fileData, chunkpos, packetsize); System.out.println("bytes written d: " + encbuf.readableBytes()); chunkpos += packetsize; // write one or more literal packets while (chunkpos < fileData.length) { packetsize = 512; // check if this is the final packet if (fileData.length - chunkpos <= packetsize) { packetsize = fileData.length - chunkpos; this.writePacketLength(encbuf, packetsize); } else { encbuf.writeByte(0xE9); // full 512 packet length } encbuf.writeBytes(fileData, chunkpos, packetsize); chunkpos += packetsize; } // protection packet encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE); encbuf.writeByte(20); // packet length MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); byte[] rv = md.digest(); encbuf.writeBytes(rv); System.out.println("Pre-Encrypted Hex"); this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); System.out.println(); System.out.println(); // ***** encryption data ready ********* byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); // add encrypted data to main buffer leadingbuf.writeBytes(encdata); System.out.println("Final Hex"); this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); System.out.println(); System.out.println(); // write to file dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); dest.flush(); dest.close(); }
From source file:divconq.test.pgp.PGPWriter2.java
License:Open Source License
@SuppressWarnings("resource") public void test1(String srcpath, String destpath, String keyring) throws Exception { Path src = Paths.get(srcpath); // file data byte[] story = Files.readAllBytes(src); // dest/*from w w w .j a va 2s. co m*/ OutputStream dest = new BufferedOutputStream(new FileOutputStream(destpath)); // encryption key PGPPublicKey pubKey = null; InputStream keyIn = new BufferedInputStream(new FileInputStream(keyring)); PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection( org.bouncycastle.openpgp.PGPUtil.getDecoderStream(keyIn), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for encryption, in the real // world you would probably want to be a bit smarter about this. // @SuppressWarnings("rawtypes") Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext() && (pubKey == null)) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); @SuppressWarnings("rawtypes") Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext() && (pubKey == null)) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) pubKey = key; } } if (pubKey == null) throw new IllegalArgumentException("Can't find encryption key in key ring."); String fileName = src.getFileName().toString(); byte[] encName = Utf8Encoder.encode(fileName); long modificationTime = System.currentTimeMillis(); SecureRandom rand = new SecureRandom(); int algorithm = PGPEncryptedData.AES_256; Cipher cipher = null; ByteBuf leadingbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb ByteBuf encbuf = Hub.instance.getBufferAllocator().heapBuffer(1024 * 1024); // 1 mb // ******************************************************************* // public key packet // ******************************************************************* PGPKeyEncryptionMethodGenerator method = new JcePublicKeyKeyEncryptionMethodGenerator(pubKey); byte[] key = org.bouncycastle.openpgp.PGPUtil.makeRandomKey(algorithm, rand); byte[] sessionInfo = new byte[key.length + 3]; // add algorithm sessionInfo[0] = (byte) algorithm; // add key System.arraycopy(key, 0, sessionInfo, 1, key.length); // add checksum int check = 0; for (int i = 1; i != sessionInfo.length - 2; i++) check += sessionInfo[i] & 0xff; sessionInfo[sessionInfo.length - 2] = (byte) (check >> 8); sessionInfo[sessionInfo.length - 1] = (byte) (check); ContainedPacket packet1 = method.generate(algorithm, sessionInfo); byte[] encoded1 = packet1.getEncoded(); leadingbuf.writeBytes(encoded1); // ******************************************************************* // encrypt packet, add IV to // ******************************************************************* String cName = PGPUtil.getSymmetricCipherName(algorithm) + "/CFB/NoPadding"; DefaultJcaJceHelper helper = new DefaultJcaJceHelper(); cipher = helper.createCipher(cName); byte[] iv = new byte[cipher.getBlockSize()]; cipher.init(Cipher.ENCRYPT_MODE, PGPUtil.makeSymmetricKey(algorithm, key), new IvParameterSpec(iv)); // ******************** start encryption ********************** // --- encrypt checksum for encrypt packet, part of the encrypted output --- byte[] inLineIv = new byte[cipher.getBlockSize() + 2]; rand.nextBytes(inLineIv); inLineIv[inLineIv.length - 1] = inLineIv[inLineIv.length - 3]; inLineIv[inLineIv.length - 2] = inLineIv[inLineIv.length - 4]; encbuf.writeBytes(inLineIv); // --- data packet --- encbuf.writeByte(0xC0 | PacketTags.LITERAL_DATA); this.writePacketLength(encbuf, 1 // format + 1 // name length + encName.length // file name + 4 // time + story.length // data ); encbuf.writeByte(PGPLiteralData.BINARY); encbuf.writeByte((byte) encName.length); encbuf.writeBytes(encName); encbuf.writeInt((int) (modificationTime / 1000)); encbuf.writeBytes(story); // protection packet encbuf.writeByte(0xC0 | PacketTags.MOD_DETECTION_CODE); encbuf.writeByte(20); // packet length MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); byte[] rv = md.digest(); encbuf.writeBytes(rv); System.out.println("Encrypted Hex"); this.hexDump(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); System.out.println(); System.out.println(); // ***** encryption data ready ********* byte[] encdata = cipher.doFinal(encbuf.array(), encbuf.arrayOffset(), encbuf.writerIndex()); leadingbuf.writeByte(0xC0 | PacketTags.SYM_ENC_INTEGRITY_PRO); /* this.writePacketLength(leadingbuf, 1 // version + encdata.length // encrypted data ); */ this.writePacketLength(leadingbuf, 0); // 0 = we don't know leadingbuf.writeByte(1); // version number // add encrypted data to main buffer leadingbuf.writeBytes(encdata); System.out.println("Final Hex"); this.hexDump(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); System.out.println(); System.out.println(); // write to file dest.write(leadingbuf.array(), leadingbuf.arrayOffset(), leadingbuf.writerIndex()); dest.flush(); dest.close(); }
From source file:dorkbox.util.crypto.CryptoPGP.java
License:Apache License
/** * Find public gpg key in InputStream./*from www . j a va 2 s . co m*/ * * @param inputStream * the input stream * * @return the PGP public key */ private static PGPPublicKey findPublicGPGKey(InputStream inputStream) throws IOException, PGPException { // get all key rings in the input stream PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection( PGPUtil.getDecoderStream(inputStream), fingerprintCalculator); System.err.println("key ring size: " + publicKeyRingCollection.size()); Iterator<PGPPublicKeyRing> keyRingIter = publicKeyRingCollection.getKeyRings(); // iterate over keyrings while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = keyRingIter.next(); Iterator<PGPPublicKey> keyIter = keyRing.getPublicKeys(); // iterate over public keys in the key ring while (keyIter.hasNext()) { PGPPublicKey tmpKey = keyIter.next(); if (tmpKey == null) { break; } Iterator<String> userIDs = tmpKey.getUserIDs(); ArrayList<String> strings = new ArrayList<String>(); while (userIDs.hasNext()) { String next = userIDs.next(); strings.add(next); } System.err.println("Encryption key = " + tmpKey.isEncryptionKey() + ", Master key = " + tmpKey.isMasterKey() + ", UserId = " + strings); // we need a master encryption key if (tmpKey.isEncryptionKey() && tmpKey.isMasterKey()) { return tmpKey; } } } throw new PGPException("No public key found!"); }
From source file:hh.learnj.test.license.test.lincense3j.MyPGPUtil.java
/** * A simple routine that opens a key ring file and loads the first available * key suitable for encryption.// ww w .j a v a2 s . c o m * * @param input * data stream containing the public key data * @return the first public key found. * @throws IOException * @throws PGPException */ public static PGPPublicKey readPublicKey(InputStream input) throws IOException, PGPException { PGPPublicKeyRingCollection pgpPub = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(input), new JcaKeyFingerprintCalculator()); // // we just loop through the collection till we find a key suitable for // encryption, in the real // world you would probably want to be a bit smarter about this. // Iterator keyRingIter = pgpPub.getKeyRings(); while (keyRingIter.hasNext()) { PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIter.next(); Iterator keyIter = keyRing.getPublicKeys(); while (keyIter.hasNext()) { PGPPublicKey key = (PGPPublicKey) keyIter.next(); if (key.isEncryptionKey()) { return key; } } } throw new IllegalArgumentException("Can't find encryption key in key ring."); }