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 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474
|
package security;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.util.Date;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedData;
import org.bouncycastle.openpgp.PGPEncryptedDataGenerator;
import org.bouncycastle.openpgp.PGPEncryptedDataList;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignature;
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.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRingCollection;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPSignatureList;
import org.bouncycastle.openpgp.PGPSignatureSubpacketGenerator;
import org.bouncycastle.openpgp.PGPUtil;
import com.altenor.pqs.boursorama.commons.ConstantsBoursorama;
public class test {
public static final String BEGIN_PUBLIC_PGP_KEY = "-----BEGIN PGP PUBLIC KEY BLOCK-----";
public static final String END_PUBLIC_PGP_KEY = "-----END PGP PUBLIC KEY BLOCK-----";
public static final String END_PGP_PRIVATE_KEY = "-----END PGP PRIVATE KEY BLOCK-----";
public static final String BEGIN_PGP_PRIVATE_KEY = "-----BEGIN PGP PRIVATE KEY BLOCK-----";
// --------------------------------------------------------------------------
static {
try {
Security.addProvider(new BouncyCastleProvider());
} catch (Exception e) {
System.err.println("le provider Bouncy Castle n'a pas été ajouté");
}
}
// --------------------------------------------------------------------------
public static PGPPublicKey readPublicKey(InputStream p_input_stream) throws Exception {
InputStream l_input_stream = null;
PGPPublicKeyRingCollection l_pgp_pub = null;
PGPPublicKey l_public_key = null;
Iterator l_ring_itr = null;
try {
l_input_stream = PGPUtil.getDecoderStream(p_input_stream);
l_pgp_pub = new PGPPublicKeyRingCollection(l_input_stream);
l_ring_itr = l_pgp_pub.getKeyRings();
while (l_public_key == null && l_ring_itr.hasNext()) {
PGPPublicKeyRing l_ring = (PGPPublicKeyRing) l_ring_itr.next();
Iterator l_key_itr = l_ring.getPublicKeys();
while (l_public_key == null && l_key_itr.hasNext()) {
PGPPublicKey l_key = (PGPPublicKey) l_key_itr.next();
if (l_key.isEncryptionKey()) {
l_public_key = l_key;
}
}
}
if (l_public_key == null) {
throw new Exception("Can't find encryption key in key ring.");
}
return l_public_key;
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
} finally {
try {
l_input_stream.close();
} catch (Exception e) {
System.out.println("stream non clos");
}
}
}
// --------------------------------------------------------------------------
public static PGPPrivateKey findSecretKey(PGPSecretKeyRingCollection p_pgp_sec, long p_key_id, char[] p_pass) throws Exception {
PGPSecretKey l_pgp_sec_key = null;
try {
l_pgp_sec_key = p_pgp_sec.getSecretKey(p_key_id);
if (l_pgp_sec_key == null) {
return null;
}
return l_pgp_sec_key.extractPrivateKey(p_pass, "BC");
} catch (Exception e) {
throw new Exception(e.getMessage());
}
} // --------------------------------------------------------------------------
// -----------------------------------------------------------------
public static PGPSecretKey readSecretKey(InputStream p_in) throws Exception {
PGPSecretKey l_secret_key = null;
PGPSecretKeyRingCollection l_keyring_coll = null;
Iterator l_iter = null;
try {
p_in = PGPUtil.getDecoderStream(p_in);
l_keyring_coll = new PGPSecretKeyRingCollection(p_in);
l_iter = l_keyring_coll.getKeyRings();
while (l_secret_key == null && l_iter.hasNext()) {
PGPSecretKeyRing l_key_ring = (PGPSecretKeyRing) l_iter.next();
Iterator l_key_iter = l_key_ring.getSecretKeys();
while (l_secret_key == null && l_key_iter.hasNext()) {
PGPSecretKey l_key = (PGPSecretKey) l_key_iter.next();
if (l_key.isSigningKey()) {
l_secret_key = l_key;
}
}
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
if (l_secret_key == null) {
throw new Exception("Can't find signing key in key ring.");
}
return l_secret_key;
}
public static ByteArrayOutputStream encrypt(byte[] clearData, InputStream keyInputStream, boolean armor) throws IOException,
PGPException, Exception, java.security.NoSuchProviderException {
ByteArrayOutputStream encOut = new ByteArrayOutputStream();
OutputStream out = encOut;
if (armor) {
out = new ArmoredOutputStream(out);
}
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZIP);
OutputStream cos = comData.open(bOut); // open it with the final destination
PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
// we want to generate compressed data. This might be a user option later,
// in which case we would pass in bOut.
OutputStream pOut = lData.open(cos, PGPLiteralData.BINARY, "", clearData.length, new Date());
pOut.write(clearData);
lData.close();
comData.close();
PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, new SecureRandom(), "BC");
System.out.println(keyInputStream.toString());
PGPPublicKey l_public_key = readPublicKey(keyInputStream);
cPk.addMethod(l_public_key);
byte[] bytes = bOut.toByteArray();
OutputStream cOut = cPk.open(out, bytes.length);
cOut.write(bytes); // obtain the actual bytes from the compressed stream
cOut.close();
out.close();
return encOut;
}
public static ByteArrayOutputStream decrypt(byte[] encrypted, char[] passPhrase, InputStream keyInputStream) {
try {
InputStream l_in_stream = null;
InputStream l_clear = null;
InputStream l_com_stream = null;
ByteArrayOutputStream l_f_out = null;
InputStream l_unc = null;
PGPObjectFactory l_pgp_fac = null;
PGPEncryptedDataList l_enc_dlist = null;
Iterator l_itr = null;
PGPPrivateKey l_secret_key = null;
PGPPublicKeyEncryptedData l_enc_data = null;
PGPSecretKeyRingCollection l_skey_ring_coll = null;
l_in_stream = PGPUtil.getDecoderStream(new ByteArrayInputStream(encrypted));
l_pgp_fac = new PGPObjectFactory(l_in_stream);
Object l_obj = l_pgp_fac.nextObject();
if (l_obj instanceof PGPEncryptedDataList) {
l_enc_dlist = (PGPEncryptedDataList) l_obj;
} else {
l_enc_dlist = (PGPEncryptedDataList) l_pgp_fac.nextObject();
}
l_itr = l_enc_dlist.getEncryptedDataObjects();
l_skey_ring_coll = new PGPSecretKeyRingCollection(PGPUtil.getDecoderStream(keyInputStream));
while (l_secret_key == null && l_itr.hasNext()) {
l_enc_data = (PGPPublicKeyEncryptedData) l_itr.next();
l_secret_key = findSecretKey(l_skey_ring_coll, l_enc_data.getKeyID(), passPhrase);
if (l_secret_key != null) {
break;
}
}
if (l_secret_key == null) {
throw new Exception("secret key for message not found.");
}
l_clear = l_enc_data.getDataStream(l_secret_key, "BC");
PGPObjectFactory l_plain_fact = new PGPObjectFactory(l_clear);
PGPCompressedData l_c_data = (PGPCompressedData) l_plain_fact.nextObject();
l_com_stream = new BufferedInputStream(l_c_data.getDataStream());
PGPObjectFactory l_pgp_fact = new PGPObjectFactory(l_com_stream);
Object l_message = l_pgp_fact.nextObject();
if (l_message instanceof PGPLiteralData) {
PGPLiteralData l_ld = (PGPLiteralData) l_message;
l_f_out = new ByteArrayOutputStream();
l_unc = l_ld.getInputStream();
int l_ch = 0;
while ((l_ch = l_unc.read()) >= 0) {
l_f_out.write(l_ch);
}
l_f_out.flush();
} else if (l_message instanceof PGPOnePassSignatureList) {
throw new Exception("encrypted message contains a signed message - not literal data.");
} else {
throw new Exception("message is not a simple encrypted file - type unknown.");
}
return l_f_out;
} catch (NoSuchProviderException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (PGPException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex.getUnderlyingException());
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (Exception ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static ByteArrayOutputStream unSign(InputStream in, InputStream keyInputStream) {
try {
in = PGPUtil.getDecoderStream(in);
//Logger.getLogger(test.class.getName()).log(Level.WARNING, "\n\n Before unsigning : getDecoderStream\n", "\n\nnBefore unsigning : getDecoderStream\n");
PGPObjectFactory pgpFact = new PGPObjectFactory(in);
PGPCompressedData c1 = (PGPCompressedData) pgpFact.nextObject();
pgpFact = new PGPObjectFactory(c1.getDataStream());
PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) pgpFact.nextObject();
PGPOnePassSignature ops = p1.get(0);
PGPLiteralData p2 = (PGPLiteralData) pgpFact.nextObject();
InputStream dIn = p2.getInputStream();
int ch;
PGPPublicKeyRingCollection pgpRing = new PGPPublicKeyRingCollection(PGPUtil.getDecoderStream(keyInputStream));
PGPPublicKey key = pgpRing.getPublicKey(ops.getKeyID());
ByteArrayOutputStream out = new ByteArrayOutputStream();
ops.initVerify(key, "BC");
while ((ch = dIn.read()) >= 0) {
ops.update((byte) ch);
out.write(ch);
}
out.close();
PGPSignatureList p3 = (PGPSignatureList) pgpFact.nextObject();
if (ops.verify(p3.get(0))) {
System.out.println("stream non clos5");
} else {
System.out.println("stream non clos6");
}
return out;
} catch (SignatureException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchProviderException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
} catch (PGPException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex.getUnderlyingException());
} catch (IOException ex) {
Logger.getLogger(test.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
public static void signBytes(byte[] data, InputStream p_key_in, OutputStream p_out, char[] p_pass, boolean p_armor) throws Exception {
PGPLiteralDataGenerator l_data_gen = null;
PGPCompressedDataGenerator l_com_gen = null;
OutputStream l_out = null;
try {
if (p_armor) {
p_out = new ArmoredOutputStream(p_out);
}
PGPSecretKey l_sec_key = readSecretKey(p_key_in);
PGPPrivateKey l_pri_key = l_sec_key.extractPrivateKey(p_pass, "BC");
PGPSignatureGenerator l_sig_gen = new PGPSignatureGenerator(l_sec_key.getPublicKey().getAlgorithm(), PGPUtil.SHA1, "BC");
l_sig_gen.initSign(PGPSignature.BINARY_DOCUMENT, l_pri_key);
Iterator l_iter_ids = l_sec_key.getPublicKey().getUserIDs();
if (l_iter_ids.hasNext()) {
PGPSignatureSubpacketGenerator l_sub_pac_gen = new PGPSignatureSubpacketGenerator();
l_sub_pac_gen.setSignerUserID(false, (String) l_iter_ids.next());
l_sig_gen.setHashedSubpackets(l_sub_pac_gen.generate());
}
l_com_gen = new PGPCompressedDataGenerator(PGPCompressedData.ZLIB);
BCPGOutputStream l_bout = new BCPGOutputStream(l_com_gen.open(p_out));
l_sig_gen.generateOnePassVersion(false).encode(l_bout);
l_data_gen = new PGPLiteralDataGenerator();
l_out = l_data_gen.open(l_bout, PGPLiteralData.BINARY, "", data.length, new Date());
l_out.write(data);
l_sig_gen.update(data);
l_data_gen.close();
l_sig_gen.generate().encode(l_bout);
l_com_gen.close();
p_out.flush();
p_out.close();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e.getMessage());
} finally {
try {
l_data_gen.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("stream non clos1");
}
try {
l_com_gen.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("stream non clos2");
}
try {
p_out.flush();
} catch (Exception e) {
e.printStackTrace();
System.out.println("stream non clos3");
}
try {
p_out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("stream non clos4");
}
try {
l_out.close();
} catch (Exception e) {
e.printStackTrace();
System.out.println("stream non clos5");
}
}
}
public String process(String str) {
/*try {
BufferedReader brin = new BufferedReader(
new InputStreamReader(
new DataInputStream(
new FileInputStream(new File("C:\\DevTools\\tests\\test.txt")))));
String thisLine;
while ((thisLine = brin.readLine()) != null)
str+=thisLine;
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
//System.out.println(str);
try {
// P2
ByteArrayOutputStream destinationStream = encrypt(str.getBytes(), new FileInputStream(new File(new File(new URL("file:C:\\DevTools\\tests\\").getPath()), "public1.asc")), true);
OutputStream signedStream = new ByteArrayOutputStream();
// S1
signBytes(destinationStream.toByteArray(), new FileInputStream("C:\\DevTools\\tests\\secret1.gpg"), signedStream, "1testtest1".toCharArray(), true);
InputStream is = new ByteArrayInputStream(((ByteArrayOutputStream) signedStream).toByteArray());
//InputStream is = new FileInputStream("C:\\DevTools\\tests\\test.txt.gpg");
System.out.println("OK passe "+is.toString());
// P1
ByteArrayOutputStream unSignedStream = unSign(is, new FileInputStream(new File(new File(new URL("file:C:\\DevTools\\tests\\").getPath()), "public1.asc")));
// S2
ByteArrayOutputStream decryptedStream = decrypt(unSignedStream.toByteArray(), "1testtest1".toCharArray(), new FileInputStream(new File(new File(new URL("file:C:\\DevTools\\tests\\").getPath()), "secret1.gpg")));
System.out.println("\n"+decryptedStream.toString());
return null;
} catch (Exception e) {
System.err.println(e.getStackTrace().toString());
} finally {
}
return str;
}
public static void main(String[] args) throws Exception {
test engine = new test();
String signedString = engine.process("GnuPG allows to encrypt and sign your data and communication, features a versatile key managment system as well as access modules for all kind of public key directories.");
//System.out.println("\n"+signedString);
}
} |
Partager