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 475 476 477 478 479 480 481 482 483 484 485
|
/*
* RSAEncryptor.java
*
* Created on 17 juin 2006, 15:58
*
*/
package org.cosmopol.crypto;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.util.ArrayList;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.ShortBufferException;
import javax.crypto.BadPaddingException;
/**
* This class provides methods to generate keys, encrypt or decrypt files and
* streams with the RSA crypting algorithm.
* @author Absil Romain
*/
public class RSAEncryptor extends FileEncryptor
{
private Key publicKey;
private Key privateKey;
private boolean isEncryptInitialized;
private boolean isDecryptInitialized;
/**
* Constructs a new RSA encryptor with the specified file containing one
* of the keys, in encrypt or decrypt mode (depends on the type of stored
* key, if the key is public, then the encryptor is in encrypt mode,
* otherwise it is in decrypt mode.
* @param keyFileName the name of the file containing a RSA key.
* @throws java.io.FileNotFoundException if the file containing the key doesn't
* exist.
* @throws java.io.IOException if an error occurs during reading the file
* containing the key.
* @throws java.lang.ClassNotFoundException if the class of the key is unknown.
* @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
*/
public RSAEncryptor(String keyFileName)
throws FileNotFoundException, IOException, ClassNotFoundException,
InvalidKeyException
{
ObjectInputStream keyIn = new ObjectInputStream(
new FileInputStream(keyFileName));
Object key = keyIn.readObject();
keyIn.close();
if(key instanceof PublicKey)
{
publicKey = (Key)key;
isEncryptInitialized = true;
}
else if(key instanceof PrivateKey)
{
privateKey = (Key)key;
isDecryptInitialized = true;
}
else
throw new InvalidKeyException("The file does not contain a " +
"valid key");
}
/**
* Constructs a new RSA encryptor with the specified file containing one
* of the keys, in encrypt or decrypt mode (depends on the type of stored
* key, if the key is public, then the encryptor is in encrypt mode,
* otherwise it is in decrypt mode.
* @param keyFile the file containing a RSA key.
* @throws java.io.FileNotFoundException if the file containing the key doesn't
* exist.
* @throws java.io.IOException if an error occurs during reading the file
* containing the key.
* @throws java.lang.ClassNotFoundException if the class of the key is unknown.
* @throws java.security.InvalidKeyException is the stored key is not a valid type of key.
*/
public RSAEncryptor(File keyFile)
throws FileNotFoundException, IOException, ClassNotFoundException, InvalidKeyException
{
ObjectInputStream keyIn = new ObjectInputStream(
new FileInputStream(keyFile));
Object key = keyIn.readObject();
keyIn.close();
if(key instanceof PublicKey)
{
publicKey = (Key)key;
isEncryptInitialized = true;
}
else if(key instanceof PrivateKey)
{
privateKey = (Key)key;
isDecryptInitialized = true;
}
else
throw new InvalidKeyException("The file does not contain a " +
"valid key");
}
/**
* Constructs a new RSA encryptor in encrypt mode with the specified
* public key.
* @param key the public key (used to encrypt files and streams).
**/
public RSAEncryptor(PublicKey key)
{
this.publicKey = key;
this.isEncryptInitialized = true;
}
/**
* Constructs a new RSA encryptor in decrypt mode with the specified
* private key.
* @param key the private key (used to decrypt files and streams).
**/
public RSAEncryptor(PrivateKey key)
{
this.privateKey = key;
this.isDecryptInitialized = true;
}
/**
* Constructs a new RSA encryptor in encrypt and decrypt mode with the
* specified files containing the public and private key.
* @param publicKeyFileName the name of the file containing the public key.
* @param privateKeyFileName the name of the file containing the private key.
* @throws java.io.FileNotFoundException if one of the files containing a key
* doen't exist.
* @throws java.io.IOException if an error occurs during reading one of the keys.
* @throws java.lang.ClassNotFoundException if one of the class of the keys is
* unknown.
* @throws java.security.InvalidKeyException if the files containing the keys don't
* contain valid keys.
*/
public RSAEncryptor(String publicKeyFileName, String privateKeyFileName)
throws FileNotFoundException, IOException, ClassNotFoundException,
InvalidKeyException
{
ObjectInputStream keyIn = new ObjectInputStream(
new FileInputStream(publicKeyFileName));
Object puKey = keyIn.readObject();
keyIn.close();
keyIn = new ObjectInputStream(
new FileInputStream(privateKeyFileName));
Object prKey = keyIn.readObject();
keyIn.close();
if(puKey instanceof PublicKey && prKey instanceof PrivateKey)
{
this.publicKey = (Key)puKey;
this.isEncryptInitialized = true;
this.privateKey = (Key)prKey;
this.isDecryptInitialized = true;
}
else
throw new InvalidKeyException("Some of the files don't contains" +
" a valid key");
}
/**
* Constructs a new RSA encryptor in encrypt and decrypt mode with the
* specified files containing the public and private key.
* @param publicKeyFile the file containing the public key.
* @param privateKeyFile the file containing the private key.
* @throws java.io.FileNotFoundException if one of the files containing a key
* doen't exist.
* @throws java.io.IOException if an error occurs during reading one of the keys.
* @throws java.lang.ClassNotFoundException if one of the class of the keys is
* unknown.
*/
public RSAEncryptor(File publicKeyFile, File privateKeyFile)
throws FileNotFoundException, IOException, ClassNotFoundException
{
ObjectInputStream keyIn = new ObjectInputStream(
new FileInputStream(publicKeyFile));
this.publicKey = (Key) keyIn.readObject();
this.isEncryptInitialized = true;
keyIn.close();
keyIn = new ObjectInputStream(
new FileInputStream(privateKeyFile));
this.privateKey = (Key) keyIn.readObject();
this.isDecryptInitialized = true;
keyIn.close();
}
/**
* Construct a new RSA encryptor in encrypt and decrypt mode with the
* specified public and private key.
* @param publicKey the public key (used to encrypt files and streams).
* @param privateKey the private key (used to decrypt files and streams).
**/
public RSAEncryptor(PublicKey publicKey, PrivateKey privateKey)
{
this.publicKey = publicKey;
this.isEncryptInitialized = true;
this.privateKey = privateKey;
this.isDecryptInitialized = true;
}
/**
* Construct a new RSA encryptor in encrypt and decrypt mode with the
* specified pair of keys.
* @param keyPair the pair of keys used to encrypt and decrypt files and
* streams.
**/
public RSAEncryptor(KeyPair keyPair)
{
this(keyPair.getPublic(), keyPair.getPrivate());
}
/**
* Returns the public key of the underlying encryptor.
* @return the public key of the underlying encryptor.
**/
public PublicKey getPublicKey()
{
return (PublicKey) publicKey;
}
/**
* Sets the public key of the underlying encryptor.
* @param key the public key to set.
**/
public void setPublicKey(PublicKey key)
{
this.publicKey = key;
}
/**
* Returns the private key of the underlying encryptor.
* @return the private key of the underlying encryptor.
**/
public PrivateKey getPrivateKey()
{
return (PrivateKey) privateKey;
}
/**
* Returns a new instance of RSAEncryptor with the specified size for
* generated keys.
* @param size the size of the generated keys.
* @return a new instance of RSAEncryptor.
**/
public static RSAEncryptor getInstance(int size)
{
return new RSAEncryptor(generateKeys(size));
}
/**
* Returns a new instance of RSAEncryptor with the specified size for
* generated keys and writes them into the specified files.
* @return a new instance of RSAEncryptor.
* @param size the size of the generated keys.
* @param publicKeyFileName the name of the file in wich youw ant to write
* the public key.
* @param privateKeyFileName the name of the file in wich youw ant to write
* the private key.
* @throws java.io.IOException if an error occurs during writing one of the keys.
*/
public static RSAEncryptor getInstance(int size, String publicKeyFileName,
String privateKeyFileName) throws IOException
{
return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFileName, privateKeyFileName));
}
/**
* Returns a new instance of RSAEncryptor with the specified size for
* generated keys and writes them into the specified files.
* @return a new instance of RSAEncryptor.
* @param size the size of the generated keys.
* @param publicKeyFile the file in wich youw ant to write the public key.
* @param privateKeyFile the file in wich youw ant to write the private key.
* @throws java.io.IOException if an error occurs during writing one of the keys.
*/
public static RSAEncryptor getInstance(int size, File publicKeyFile,
File privateKeyFile) throws IOException
{
return new RSAEncryptor(generateAndSaveKeys(size, publicKeyFile, privateKeyFile));
}
/**
* Returns a pair of keys generated with the specified size.
* @return a pair of keys generated with the specified size.
* @param size the size of the generated key.
*/
public static KeyPair generateKeys(int size)
{
KeyPairGenerator pairgen = null;
try
{
pairgen = KeyPairGenerator.getInstance("RSA");
}
catch (NoSuchAlgorithmException ex)//never launched
{
ex.printStackTrace();
}
SecureRandom random = new SecureRandom();
pairgen.initialize(size, random);
KeyPair keyPair = pairgen.generateKeyPair();
return keyPair;
}
/**
* Returns a pair of keys generated with the specified size and writes
* them into the specified files.
* @param size the size of the generated keys.
* @param publicKeyFileName the name of the file in wich youw ant to write
* the public key.
* @param privateKeyFileName the name of the file in wich youw ant to write
* the private key.
* @return a pair of keys with the specified size.
* @throws java.io.IOException if an error occurs during writing the keys.
**/
public static KeyPair generateAndSaveKeys(int size, String publicKeyFileName,
String privateKeyFileName) throws IOException
{
return generateAndSaveKeys(size, new File(publicKeyFileName), new File(privateKeyFileName));
}
/**
* Returns a pair of keys generated with the specified size and writes
* them into the specified files.
* @param size the size of the generated keys.
* @param publicKeyFile the file in wich you want to write the public key.
* @param privateKeyFile the file in wich you want to write the private key.
* @return a pair of keys with the specified size.
* @throws java.io.IOException if an error occurs during writing the keys.
**/
public static KeyPair generateAndSaveKeys(int size, File publicKeyFile,
File privateKeyFile) throws IOException
{
KeyPair keyPair = generateKeys(size);
ObjectOutputStream out = new ObjectOutputStream(
new FileOutputStream(publicKeyFile));
out.writeObject(keyPair.getPublic());
out.close();
out = new ObjectOutputStream(
new FileOutputStream(privateKeyFile));
out.writeObject(keyPair.getPrivate());
out.close();
return keyPair;
}
/**
* Encrypts the specified input stream to the specified output stream.
*
* @param in the stream to encrypt.
* @param out the stream where you want to write the encrypted stream.
* @throws java.io.IOException if an error occurs during writing encrypted
* datas.
* @throws java.security.InvalidKeyException if the key is not valid for
* this type of operation.
*/
public void encryptStream(InputStream in, OutputStream out)
throws InvalidKeyException, IOException
{
if(!this.isEncryptInitialized)
throw new IllegalStateException("The underlying encryptor is not" +
" initialized in encrypt mode. You must specify a " +
"public key.");
KeyGenerator keygen = null;
Cipher cipherRsa = null;
Cipher cipherAes= null;
try
{
keygen = KeyGenerator.getInstance("AES");
cipherRsa = Cipher.getInstance("RSA");
cipherAes = Cipher.getInstance("AES");
}
catch(NoSuchAlgorithmException e)//never launched
{
e.printStackTrace();
}
catch(NoSuchPaddingException e)
{
e.printStackTrace();
}
SecureRandom random = new SecureRandom();
keygen.init(random);
SecretKey key = keygen.generateKey();
cipherRsa.init(Cipher.WRAP_MODE, publicKey);
byte[] wrappedKey = null;
try
{
wrappedKey = cipherRsa.wrap(key);
}
catch (InvalidKeyException ex)
{
ex.printStackTrace();
}
catch (IllegalBlockSizeException ex)
{
ex.printStackTrace();
}
Integer length = wrappedKey.length;
DataOutputStream writer = new DataOutputStream(out);
writer.writeInt(length);
writer.write(wrappedKey);
cipherAes.init(Cipher.ENCRYPT_MODE, key);
super.crypt(in, writer, cipherAes);
// in.close();
// out.close();
//writer.close();
}
/**
* Decrypts the specified input stream to the specified output stream.
* @param in the stream to decrypt.
* @param out the stream where you want to write the decrypted stream.
* @throws java.io.IOException if an error occurs during writing encrypted
* datas.
* @throws java.security.InvalidKeyException if the key is not valid for
* this type of operation.
*/
public void decryptStream(InputStream in, OutputStream out)
throws IOException, InvalidKeyException
{
if(!this.isEncryptInitialized)
throw new IllegalStateException("The underlying encryptor is not" +
" initialized in decrypt mode. You must specify a " +
"private key.");
DataInputStream reader = new DataInputStream(in);
int length = reader.readInt();
byte[] wrappedKey = new byte[length];
in.read(wrappedKey, 0, length);
Cipher cipherRsa = null;
Cipher cipherAes = null;
Key key = null;
try
{
cipherRsa = Cipher.getInstance("RSA");
cipherAes = Cipher.getInstance("AES");
cipherRsa.init(Cipher.UNWRAP_MODE, privateKey);
key = cipherRsa.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
}
catch(NoSuchAlgorithmException e)//never thrown
{
e.printStackTrace();
}
catch(NoSuchPaddingException e)
{
e.printStackTrace();
}
cipherAes.init(Cipher.DECRYPT_MODE, key);
super.crypt(reader, out, cipherAes);
// in.close();
// out.close();
//reader.close();
}
} |
Partager