IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

API standards et tierces Java Discussion :

Décrypter des fichiers avec PGP


Sujet :

API standards et tierces Java

  1. #1
    Membre confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    65
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Août 2006
    Messages : 65
    Par défaut Décrypter des fichiers avec PGP
    Bonjour,
    j'ai des fichiers encryptés en PGP et je voudrais les décryptés j'ai la clé privé et le mot de passe voici mon code java j'appel cette class par une class main ,c'est avec ce meme code que les fichiers on été crypté! , j’utilise myeclipse et jdk et jre 1.6 avec les jars bcpg-jdk15-135.jar et bcprov-jdk15-135.jar pour pgp ,j'ai essayé avec jdk et jre 1.5 mais ça marche pas aussi !! voici les messages que je reçois!! une idée Svp?

    java.lang.Exception: org.bouncycastle.openpgp.PGPException: Exception creating cipher
    at com.cogeco.app.process.creditscoring.cryptography.PGPCryptography.decrypt(PGPCryptography.java:261)
    at com.cogeco.app.process.creditscoring.cryptography.DecryptFilesMain.main(DecryptFilesMain.java:18)
    Caused by: org.bouncycastle.openpgp.PGPException: Exception creating cipher
    at org.bouncycastle.openpgp.PGPSecretKey.extractKeyData(Unknown Source)
    at org.bouncycastle.openpgp.PGPSecretKey.extractPrivateKey(Unknown Source)
    at com.cogeco.app.process.creditscoring.cryptography.PGPCryptography.findSecretKey(PGPCryptography.java:306)
    at com.cogeco.app.process.creditscoring.cryptography.PGPCryptography.decrypt(PGPCryptography.java:189)
    ... 1 more
    Caused by: java.security.NoSuchAlgorithmException: No such algorithm: IDEA/CFB/NoPadding
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    at javax.crypto.Cipher.getInstance(DashoA13*..)
    ... 5 more
    Caused by: java.security.NoSuchAlgorithmException: Error constructing implementation (algorithm: IDEA, provider: BC, class: org.bouncycastle.jce.provider.JCEBlockCipher$IDEA)
    at java.security.Provider$Service.newInstance(Provider.java:1245)
    ... 7 more
    Caused by: java.lang.SecurityException: class "org.bouncycastle.crypto.CipherParameters"'s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(ClassLoader.java:776)
    at java.lang.ClassLoader.preDefineClass(ClassLoader.java:488)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:252)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Class.java:2389)
    at java.lang.Class.getConstructor0(Class.java:2699)
    at java.lang.Class.newInstance0(Class.java:326)
    at java.lang.Class.newInstance(Class.java:308)
    at java.security.Provider$Service.newInstance(Provider.java:1221)
    ... 7 more


    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
     
     
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.security.NoSuchProviderException;
    import java.security.SecureRandom;
    import java.security.Security;
    import java.util.Iterator;
     
    import org.apache.commons.lang.builder.ToStringBuilder;
    import org.apache.log4j.Logger;
    import org.bouncycastle.bcpg.ArmoredOutputStream;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    import org.bouncycastle.openpgp.PGPCompressedData;
    import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
    import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
    import org.bouncycastle.openpgp.PGPEncryptedDataList;
    import org.bouncycastle.openpgp.PGPException;
    import org.bouncycastle.openpgp.PGPLiteralData;
    import org.bouncycastle.openpgp.PGPObjectFactory;
    import org.bouncycastle.openpgp.PGPOnePassSignatureList;
    import org.bouncycastle.openpgp.PGPPrivateKey;
    import org.bouncycastle.openpgp.PGPPublicKey;
    import org.bouncycastle.openpgp.PGPPublicKeyEncryptedData;
    import org.bouncycastle.openpgp.PGPPublicKeyRing;
    import org.bouncycastle.openpgp.PGPPublicKeyRingCollection;
    import org.bouncycastle.openpgp.PGPSecretKey;
    import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
    import org.bouncycastle.openpgp.PGPUtil;
     
     
    public class PGPCryptography  {
     
    	static private final Logger logger = Logger.getLogger(PGPCryptography.class);
     
    	static {
    		Security.addProvider(new BouncyCastleProvider());
    	}
     
    	public PGPCryptography() throws Exception {
     
    	}
     
    	public void listPublicKeys(File publicKeyFile) throws Exception{
     
    		if(publicKeyFile == null || !publicKeyFile.exists()){
    			throw new IllegalArgumentException("publicKeyFile cannot be null and must be an existing file");
    		}
     
    		try {
     
    			InputStream in = new FileInputStream(publicKeyFile);
    			PGPPublicKeyRing publicKeyRing = new PGPPublicKeyRing(in);
     
    			Iterator it = publicKeyRing.getPublicKeys();
    			while(it.hasNext()){
     
    				PGPPublicKey k = (PGPPublicKey) it.next();
     
    				ToStringBuilder b = new ToStringBuilder(k);
    				b.append("isMasterKey", k.isMasterKey());
    				b.append("isEncryptionKey", k.isEncryptionKey());
    				b.append("isRevoked", k.isRevoked());
     
    				String userids = "";
    				Iterator useridIt = k.getUserIDs();
    				while(useridIt.hasNext()){
    					String uid = (String) useridIt.next();
    					if(userids.length() > 0){
    						userids += ", ";
    					}
    					userids += uid;
    				}
     
    				b.append("userids", userids);
     
    				logger.info(b);
    			}
     
    		} catch (Throwable e) {
    			throw new Exception(e);
    		}
     
    	}
     
    	public File encrypt(File publicKeyFile, String userid, File sourceFile) throws Exception {
     
    		if(publicKeyFile == null || !publicKeyFile.exists()){
    			throw new IllegalArgumentException("publicKeyFile cannot be null and must be an existing file");
    		}
    		if(sourceFile == null || !sourceFile.exists()){
    			throw new IllegalArgumentException("sourceFile cannot be null and must be an existing file");
    		}
     
    		logger.debug("About to encrypt content of file: " + sourceFile.getName());
     
    		try {
     
    			File encryptedFile = File.createTempFile("pgp_", ".encrypted", new File("C:\\pgp\\decryptedfile\\"));
    			FileOutputStream fileOut = new FileOutputStream(encryptedFile);
     
    			PGPPublicKey publicKey = findPublicKey(publicKeyFile, userid, true);
     
    			if(publicKey == null){
    				throw new IllegalArgumentException("no public key for " + userid + " in keyring " + publicKeyFile);
    			}
     
    			ArmoredOutputStream armoredOut = new ArmoredOutputStream(fileOut);
    			ByteArrayOutputStream byteArrayOut = new ByteArrayOutputStream();
    			PGPCompressedDataGenerator compressedData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
    			PGPUtil.writeFileToLiteralData(compressedData.open(byteArrayOut), PGPLiteralData.BINARY, sourceFile);
    			compressedData.close();
    			PGPEncryptedDataGenerator encryptedDataGenerator = new PGPEncryptedDataGenerator(PGPEncryptedDataGenerator.CAST5, new SecureRandom(), "BC");
    			encryptedDataGenerator.addMethod(publicKey);
     
    			byte[] bytes = byteArrayOut.toByteArray();
     
    			OutputStream encryptedOut = encryptedDataGenerator.open(armoredOut, bytes.length);
     
    			encryptedOut.write(bytes);
    			encryptedDataGenerator.close();
    			armoredOut.close();
    			fileOut.close();
     
    			logger.debug("file was encrypted : " + sourceFile.getName());
    			return encryptedFile;
     
    		} catch (Exception e) {
    			logger.error("Encrypt exception ", e);
    			throw new Exception(e);
    		}
     
    	}
     
    	public File decrypt(File privateKeyFile, String privateKeyPassword, File encryptedFile) throws Exception {
     
    		File decryptedFile = null;
     
    		if(privateKeyFile == null || !privateKeyFile.exists()){
    			throw new IllegalArgumentException("privateKeyFile cannot be null and must be an existing file");
    		}
    		if(encryptedFile == null || !encryptedFile.exists()){
    			throw new IllegalArgumentException("encryptedFile cannot be null and must be an existing file");
    		}
     
    		try {
     
    			InputStream encryptedFileIn = new FileInputStream(encryptedFile);
    			InputStream privateKeyIn = new FileInputStream(privateKeyFile);
     
    			decryptedFile = File.createTempFile("pgp_", ".decrypted");
    			logger.debug("About to decrypt content of file: " + decryptedFile.getName());
     
    			FileOutputStream out = new FileOutputStream(decryptedFile);
     
    			logger.debug("decrypting content of " + encryptedFile.getName() + " to " + decryptedFile.getName());
     
    			encryptedFileIn = PGPUtil.getDecoderStream(encryptedFileIn);
     
    			PGPObjectFactory pgpObjectFactory = new PGPObjectFactory(encryptedFileIn);
    			PGPEncryptedDataList encryptedDataList;
    			Object pgpObject = pgpObjectFactory.nextObject();
     
    			if (pgpObject instanceof PGPEncryptedDataList) {
    				encryptedDataList = (PGPEncryptedDataList) pgpObject;
    			} else {
    				encryptedDataList = (PGPEncryptedDataList) pgpObjectFactory.nextObject();
    			}
     
    			Iterator encryptedDataListIt = encryptedDataList.getEncryptedDataObjects();
     
    			PGPPrivateKey privateKey = null;
    			PGPPublicKeyEncryptedData privateKeyEncryptedData = null;
     
    			while (privateKey == null && encryptedDataListIt.hasNext()) {
    				privateKeyEncryptedData = (PGPPublicKeyEncryptedData) encryptedDataListIt.next();
    				privateKey = findSecretKey(privateKeyIn, privateKeyEncryptedData.getKeyID(), privateKeyPassword.toCharArray());
    			}
     
    			if (privateKey == null){
    				encryptedFileIn.close();
    				privateKeyIn.close();
    				throw new IllegalStateException("no private key could be found");
    			}
     
    			InputStream clear = privateKeyEncryptedData.getDataStream(privateKey, "BC");
     
    			PGPObjectFactory plainFact = new PGPObjectFactory(clear);
     
    			Object thing = plainFact.nextObject();
    			Object message = null;
     
    			if (thing instanceof PGPLiteralData) {
     
    				message = thing;
     
    			} else if (thing instanceof PGPCompressedData) {
     
    				PGPCompressedData cData = (PGPCompressedData) thing;
     
    				InputStream compressedStream = new BufferedInputStream(cData.getDataStream());
    				PGPObjectFactory pgpFact = new PGPObjectFactory(compressedStream);
     
    				message = pgpFact.nextObject();
     
    				if (message instanceof PGPOnePassSignatureList) {
    					message = pgpFact.nextObject();
    				}
     
    			}
     
    			if (message instanceof PGPLiteralData) {
     
    				// decrypt as normal
    				PGPLiteralData literal = (PGPLiteralData) message;
    				BufferedReader w = new BufferedReader(new InputStreamReader(literal.getInputStream()));
     
    				String s = null;
    				while((s = w.readLine()) != null){
    					//logger.debug("decrypted: " + s);
    					out.write(s.getBytes());
    				}
     
    			} else {
    				logger.error("message type " + message.toString() + " not supported.");
    				return null;
    			}
    			if (privateKeyEncryptedData.isIntegrityProtected()) {
    				if (!privateKeyEncryptedData.verify()) {
    					logger.error("message failed integrity check");
    					return null;
    				}
    			}
     
    			out.close();
    			encryptedFileIn.close();
    			privateKeyIn.close();
     
    			return decryptedFile;
     
    		} catch (Exception e) {
     
    			if(decryptedFile != null){
    				decryptedFile.delete();
    			}
     
    			logger.error("An error occured during PGP decryption: \n", e);
     
    			throw new Exception(e);
    		}
     
    	}
     
     
    	public PGPPublicKey findPublicKey(File publicKeyFile, String userid, boolean encryption) throws IOException, PGPException {
     
    		PGPPublicKeyRingCollection publicKeyRingCollection = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(new FileInputStream(publicKeyFile)));
     
    		Iterator keyRingIt = publicKeyRingCollection.getKeyRings();
     
    		while (keyRingIt.hasNext()) {
     
    			PGPPublicKeyRing keyRing = (PGPPublicKeyRing) keyRingIt.next();
     
    			Iterator keysIt = keyRing.getPublicKeys();
    			while (keysIt.hasNext()) {
     
    				PGPPublicKey key = (PGPPublicKey) keysIt.next();
     
    				Iterator userIt = key.getUserIDs();
    				while(userIt.hasNext()){
    					String user = (String) userIt.next();
    					if(user.equalsIgnoreCase(userid) && key.isEncryptionKey() == encryption){
    						return key;
    					}
     
    				}
     
    			}
    		}
     
    		return null;
    	}
     
    	private PGPPrivateKey findSecretKey(InputStream privateKeyIn, long privateKeyID, char[] password) throws IOException, PGPException, NoSuchProviderException {
     
    		PGPSecretKeyRingCollection secretKeyRingCollection = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(privateKeyIn));
    		PGPSecretKey secretKey = secretKeyRingCollection.getSecretKey(privateKeyID);
     
    		if (secretKey == null) {
    			return null;
    		}
     
    		return secretKey.extractPrivateKey(password, "BC");
    	}
     
    }

  2. #2
    Membre très actif
    Profil pro
    Inscrit en
    Février 2010
    Messages
    765
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2010
    Messages : 765
    Par défaut
    Bonjour,

    Comme l'indique l'exception java.lang.SecurityException, tu as un soucis d'ordre général de signature de jar dans le même package.

    Peut-être des versions mélangées ou modifiées, difficile de savoir comme ça.

  3. #3
    Membre confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    65
    Détails du profil
    Informations personnelles :
    Localisation : Canada

    Informations forums :
    Inscription : Août 2006
    Messages : 65
    Par défaut
    Tout a fait Jimmy_ ,il y'avait des jars en plus que j'ai ajouté a la va vite car je n'avais pas le projet au complet ,j'ai fait un peu le ménage j'ai laissé que les jars dont j'avais besoin et ca marche encore une fois merci.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Recherche des fichiers avec ksh
    Par mzt.insat dans le forum Linux
    Réponses: 3
    Dernier message: 15/05/2006, 22h51
  2. Manipulation des fichiers avec fstream.
    Par Pragmateek dans le forum SL & STL
    Réponses: 4
    Dernier message: 04/04/2006, 13h12
  3. trier des fichiers avec un tableau flexgrid
    Par digger dans le forum VB 6 et antérieur
    Réponses: 1
    Dernier message: 08/12/2005, 15h20
  4. Transférer des fichiers avec un câble réseau
    Par denis finch dans le forum Développement
    Réponses: 5
    Dernier message: 08/11/2005, 16h08
  5. [ZIP]besoin de lire des fichiers avec l'extension tar.gz
    Par mathieublanc13 dans le forum Entrée/Sortie
    Réponses: 3
    Dernier message: 24/05/2004, 13h35

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo