Java Tutorial/Security/Blowfish
Версия от 17:44, 31 мая 2010; (обсуждение)
A Blowfish example
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Encoder;
public final class MainClass {
public static void main(String[] args) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey = keyGenerator.generateKey();
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
BASE64Encoder encoder = new BASE64Encoder();
byte iv[] = cipherOut.getIV();
if (iv != null) {
System.out.println("Initialization Vector of the Cipher:\n" + encoder.encode(iv));
}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new FileOutputStream("outputFile.txt");
CipherOutputStream cout = new CipherOutputStream(fout, cipherOut);
int input = 0;
while ((input = fin.read()) != -1) {
cout.write(input);
}
fin.close();
cout.close();
}
}
Create a Blowfish key, encrypts some text,prints the ciphertext, then decrypts the text
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
public class MainClass {
public static void main(String[] args) throws Exception {
String text = "jexp";
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key key = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] ciphertext = cipher.doFinal(text.getBytes("UTF8"));
for (int i = 0; i < ciphertext.length; i++) {
System.out.print(ciphertext[i] + " ");
}
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedText = cipher.doFinal(ciphertext);
System.out.println(new String(decryptedText, "UTF8"));
}
}
//-126 -104 127 -75 -34 -71 -94 -96 jexp
Generate a Blowfish key
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class MainClass {
public static void main(String[] args) throws Exception {
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = cipher.doFinal("This is a test.".getBytes("UTF8"));
System.out.println(new String(cipherText));
}
}