?? hybrid.java
字號:
ioe.printStackTrace();
throw new CryptoException(ioe.getMessage());
} finally {
if (dao != null) {
// close outputstream
try {
dao.close();
} catch (IOException e) {
;
}
}
}
}
/**
* Encrypt and sign a file
*
* @param file file to encrypt
* @param newfile encrypted file
* @param receiverKey the public key of the receiver
* @param signingKey the private key of the signer
* @param cert the signer's certificate
* @param signame the signature's algorithm (e.g."MD5withRSA")
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param seed for SecureRandom (optional)
* @param strength the keysize in bits (e.g. 128)
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @throws CryptoException encryption errors
* @throws IOException I/O errors
*/
public static void encryptFileAndSign(String file
, String newfile
, PublicKey receiverKey
, PrivateKey signingKey
, X509Certificate cert
, String signame
, String algorithm
, byte[] seed
, int strength
, String mode
, String padding)
throws CryptoException, IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
DataOutputStream dao = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(newfile);
dao = new DataOutputStream(fos);
// encrypt file
encryptAndSign(fis, dao, receiverKey, signingKey, cert, signame, algorithm, seed, strength, mode, padding, BUFFERSIZE_FILE);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new IOException(ioe.getMessage());
} finally {
if (dao != null) {
// close outputstream
try {
dao.close();
} catch (IOException e) {
;
}
}
if (fis != null) {
// close outputstream
try {
fis.close();
} catch (IOException e) {
;
}
}
}
}
/**
* Encrypt and sign any inputstream
*
* @param is inputstream to encrypt
* @param daos outputstream to store the encrypted & signed data
* @param receiverKey the public key of the receiver
* @param signingKey the private key of the signer
* @param cert the signer's certificate
* @param signame the signature's algorithm (e.g."MD5withRSA")
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param seed for SecureRandom (optional)
* @param strength the keysize in bits (e.g. 128)
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param bufferlength buffer length in bytes
* @throws CryptoException encryption errors
* @throws IOException I/O errors
*/
public static void encryptAndSign(InputStream is
, DataOutputStream daos
, PublicKey receiverKey
, PrivateKey signingKey
, X509Certificate cert
, String signame
, String algorithm
, byte[] seed
, int strength
, String mode
, String padding
, int bufferlength)
throws CryptoException, IOException {
SecureRandom secRand = null;
KeyGenerator keyGen = null;
Key symKey = null;
Cipher outputCipher = null;
SignatureOutputStream sigStr = null;
DataOutputStream dataStr = null;
try {
Security.addProvider(new BouncyCastleProvider());
secRand = Seed.getSecureRandom(seed);
// Generate symmetric key
keyGen = KeyGenerator.getInstance(algorithm, "BC");
keyGen.init(strength, secRand);
symKey = keyGen.generateKey();
// Instantiate Symmetric cipher for encryption.
outputCipher = Cipher.getInstance(algorithm + "/" + mode + "/" + padding, "BC");
outputCipher.init(Cipher.ENCRYPT_MODE, symKey, secRand);
// Get key and IV for cipher so that they can be later
// encrypted to build a header.
byte[] keyEnc = symKey.getEncoded();
byte[] keyIV = outputCipher.getIV();
byte[] lock = new byte[24];
secRand.nextBytes(lock);
// Setup Signature
Signature sig = Signature.getInstance(signame, "BC");
sig.initSign(signingKey, secRand); // Initialize with my private signing key.
sig.update(lock); // put plain text of lock data into signature.
// Setup RSA to encrypt secrets.
Cipher rsaEng = Cipher.getInstance("RSA/None/OAEPPadding", "BC");
rsaEng.init(Cipher.ENCRYPT_MODE, receiverKey, secRand);
// Setup to process File.
//FileInputStream inStr = new FileInputStream(filename); // Source of plain text.
//FileOutputStream outStr = new FileOutputStream(newfilename); // Final output stream.
sigStr = new SignatureOutputStream(daos, sig);
dataStr = new DataOutputStream(sigStr);
// Form HEADER for the encrypted string
dataStr.writeShort(FILE_HEADER); // Write a file or string header.
// Write out a block for the key of the cipher.
dataStr.writeShort(KEY_BLOCK); // Block header.
byte[] tmp = rsaEng.doFinal(keyEnc); // Encrypt it with RSA.
dataStr.writeInt(tmp.length); // Write length.
dataStr.write(tmp); // Write data.
Clean.blank(tmp); // Erase tmp array.
// Write out IV block
dataStr.writeShort(IV_BLOCK); // Block header
tmp = rsaEng.doFinal(keyIV); // Encrypt with RSA.
dataStr.writeInt(tmp.length); // Write length.
dataStr.write(tmp); // Write data.
Clean.blank(tmp); // Erase tmp array.
// Write out lock data for SIGNATURE.
dataStr.writeShort(LOCK_BLOCK); // Write header.
tmp = outputCipher.doFinal(lock); // Encrypt with AES.
dataStr.writeInt(tmp.length); // Write length.
dataStr.write(tmp); // Write data.
Clean.blank(tmp); // Erase tmp array.
// Reset cipher back to original
outputCipher.init(Cipher.ENCRYPT_MODE, symKey, new IvParameterSpec(keyIV)); // initialize with aes_key.
// Encrypt the message
int l = 0; // Universal length variable.
byte[] buf = new byte[bufferlength]; // A buffer to work in.
byte[] out = null; // Output buffer.
// Read while length is > -1
while ((l = is.read(buf)) > -1) {
out = outputCipher.update(buf, 0, l); // Encrypt data.
if (out != null) {
dataStr.writeShort(DATA_BLOCK); // Write data block header.
dataStr.writeInt(out.length); // Write length.
dataStr.write(out); // Write encrypted data.
}
}
// This is the last block
out = outputCipher.doFinal(); // Do final encryption.
dataStr.writeShort(FINAL_DATA_BLOCK); // Write header.
dataStr.writeInt(out.length); // Write length.
dataStr.write(out); // Write Data.
Clean.blank(buf); // Clear buffer.
buf = null; // Set Null
// Write out our certificate
dataStr.writeShort(CERT_BLOCK); // Cert block header.
tmp = cert.getEncoded(); // Get encoded in a byte array.
dataStr.writeInt(tmp.length); // Write length.
dataStr.write(tmp); // Write data.
// Write out signature block
dataStr.writeShort(SIG_BLOCK); // Write Header.
dataStr.flush(); // Flush it..
tmp = sig.sign(); // Get signature code.
dataStr.writeInt(tmp.length); // Write length.
dataStr.write(tmp); // Write data.
Clean.blank(tmp); // Clear.
// Flush and close output.
dataStr.flush();
dataStr.close();
} catch (IOException ioe) {
ioe.printStackTrace();
throw new IOException(ioe.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
throw new CryptoException(ex.getMessage());
} finally {
if (dataStr != null) {
try {
dataStr.close();
} catch (IOException ioe) {
;
}
}
}
}
/**
* decrypt and verify text signature
*
* @param text the text to decrypt and verify
* @param privKey the private key of the receiver
* @param signercert returns the signer's certificate
* @param signame the signature's algorithm (e.g."MD5withRSA")
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @return the plaintext
* @throws HeaderException thrown when package header is broken
* @throws InvalidSignatureException thrown when the signature is invalid
* @throws CryptoException all encryption errors
*/
public static StringBuffer decryptAndVerify(StringBuffer text
, PrivateKey privKey
, SignerCertificate signercert
, String signame
, String algorithm
, String mode
, String padding) throws HeaderException, InvalidSignatureException, CryptoException {
ByteArrayOutputStream bao = null;
DataOutputStream dao = null;
try {
bao = new ByteArrayOutputStream();
dao = new DataOutputStream(bao);
// decrypt & verify
decryptAndVerify(new ByteArrayInputStream(Base64.decode(text.toString())), dao, privKey, signercert, signame, algorithm, mode, padding, BUFFERSIZE_TEXT);
return new StringBuffer(new String(bao.toByteArray()));
} catch (HeaderException he) {
throw new HeaderException(he.getMessage());
} catch (InvalidSignatureException ise) {
throw new InvalidSignatureException(ise.getMessage());
} catch (Exception ioe) {
ioe.printStackTrace();
throw new CryptoException(ioe.getMessage());
} finally {
if (dao != null) {
// close outputstream
try {
dao.close();
} catch (IOException e) {
;
}
}
}
}
/**
* decrypt and verify inputstream signature (which must support mark/reset)
*
* @param is the inputstream to decrypt and verify (NOTE: the inputstream must support mark/reset because it must be read three times)
* @param daos the outputstream containing the deciphered data
* @param privKey the private key of the receiver
* @param signercert returns the signer's certificate
* @param signame the signature's algorithm (e.g."MD5withRSA")
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param bufferlength buffer length in bytes
* @throws IOException I/O errors
* @throws HeaderException thrown when package header is broken
* @throws InvalidSignatureException thrown when the signature is invalid
* @throws CryptoException all encryption errors
*/
public static void decryptAndVerify(InputStream is
, DataOutputStream daos
, PrivateKey privKey
, SignerCertificate signercert
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -