📄 crypt.java
字号:
/*
Name: Crypt.java
Licensing: LGPL
API: Sun (http://java.sun.com) JCE 1.2.2 API (cleanroom implementation by Bouncy Castle)
Provider: Bouncy Castle (http://www.bouncycastle.org)
Disclaimer:
COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY OF ANY KIND,
EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED CODE
IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE
RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED CODE IS WITH YOU. SHOULD ANY COVERED CODE
PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR)
ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY
CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED
HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
(C) Copyright 2003 Gert Van Ham
*/
package net.sourceforge.jcetaglib.lib;
import net.sourceforge.jcetaglib.exceptions.CryptoException;
import net.sourceforge.jcetaglib.exceptions.KeystoreException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.IvParameterSpec;
import java.io.*;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
/**
* Symmetric block/stream cipher encryption & decryption routines for use with BouncyCastle JCE provider
*
* @author Gert Van Ham
* @author hamgert@users.sourceforge.net
* @author http://jcetaglib.sourceforge.net
* @version $Id: Crypt.java,v 1.3 2004/04/15 07:28:25 hamgert Exp $
*/
public class Crypt {
// buffersizes in bytes
private static int BUFFERSIZE_TEXT = 64;
private static int BUFFERSIZE_FILE = 8192;
/**
* Encrypts a message with a symmetric key
*
* @param text the message to encrypt
* @param keyfile keyfile(name)
* @param passphrase the passphrase for the keystore
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param seed seed for SecureRandom (optional)
* @return encrypted message in BASE64
* @throws CryptoException for encryption errors
* @throws KeystoreException when keystore could not be loaded
*/
public static StringBuffer encrypt(StringBuffer text
, String keyfile
, StringBuffer passphrase
, String algorithm
, String mode
, String padding
, byte[] seed) throws CryptoException, KeystoreException {
// read secret key
Key secretKey = Keystore.loadKey(algorithm, keyfile, passphrase);
// encrypt text
return encrypt(text, secretKey, algorithm, mode, padding, seed);
}
/**
* Encrypts a message with a symmetric key
*
* @param text the message to encrypt
* @param secretKey the secret key
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param seed seed for SecureRandom (optional)
* @return encrypted message in BASE64
* @throws CryptoException for encryption errors
*/
public static StringBuffer encrypt(StringBuffer text
, Key secretKey
, String algorithm
, String mode
, String padding
, byte[] seed) throws CryptoException {
ByteArrayOutputStream bao = null;
DataOutputStream dao = null;
try {
bao = new ByteArrayOutputStream();
dao = new DataOutputStream(bao);
// encrypt text
encrypt(new ByteArrayInputStream(text.toString().getBytes()), dao, secretKey, algorithm, mode, padding, seed, BUFFERSIZE_TEXT);
return new StringBuffer(new String(Base64.encode(bao.toByteArray())));
} catch (IOException ioe) {
ioe.printStackTrace();
throw new CryptoException(ioe.getMessage());
} finally {
if (dao != null) {
// close outputstream
try {
dao.close();
} catch (IOException e) {
;
}
}
}
}
/**
* Encrypts a file with a symmetric key
*
* @param file the file to encrypt
* @param newfile the encrypted file
* @param keyfile keyfile(name)
* @param passphrase the passphrase for the keystore
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param seed seed for SecureRandom (optional)
* @throws CryptoException encryption errors
* @throws IOException I/O errors
* @throws KeystoreException when keystore could not be loaded
*/
public static void encryptFile(String file
, String newfile
, String keyfile
, StringBuffer passphrase
, String algorithm
, String mode
, String padding
, byte[] seed) throws CryptoException, IOException, KeystoreException {
FileInputStream fis = null;
FileOutputStream fos = null;
DataOutputStream dao = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(newfile);
dao = new DataOutputStream(fos);
// read secret key
Key secretKey = Keystore.loadKey(algorithm, keyfile, passphrase);
// encrypt file
encrypt(fis, dao, secretKey, algorithm, mode, padding, seed, 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) {
;
}
}
}
}
/**
* Encrypts any inputstream with a symmetric key
*
* @param is the inputstream to encrypt
* @param daos the encrypted outputstream
* @param secretKey the secret key
* @param algorithm encryption algorithm (e.g. "Rijndael")
* @param mode encryption mode (e.g. "CBC")
* @param padding padding scheme (e.g."PKCS7Padding")
* @param seed seed for SecureRandom (optional)
* @param bufferlength buffer length in bytes
* @exception CryptoException for encryption errors
* @exception IOException I/O errors
**/
public static void encrypt(InputStream is
, DataOutputStream daos
, Key secretKey
, String algorithm
, String mode
, String padding
, byte[] seed
, int bufferlength)
throws CryptoException, IOException {
IvParameterSpec spec = null; // initialization vector
byte[] iv = null; // initialization vector as byte[]
Cipher cipher = null;
CipherOutputStream cStr = null;
try {
if (algorithm.equalsIgnoreCase("RC4")) {
// create a stream cipher object (ignore mode & padding)
cipher = Cipher.getInstance("RC4");
} else {
// create a block cipher object: ("algorithm/mode/padding", provider)
cipher = Cipher.getInstance(algorithm + "/" + mode + "/" + padding, "BC");
}
if (mode.equalsIgnoreCase("ECB") || algorithm.equalsIgnoreCase("RC4")) {
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
} else {
// These modes need an iv with a valid block size in order
// to be used.
SecureRandom sr = Seed.getSecureRandom(seed);
// allocate memory for iv.
iv = new byte[cipher.getBlockSize()];
// Get next bytes from the PRNG.
sr.nextBytes(iv);
// create the IV class.
spec = new IvParameterSpec(iv);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, spec);
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -