Cipher
Cipher
Cipher
byte[] keyBytes="12345678".getBytes();
byte[] ivBytes="input123"getBytes();
SecretKeySpec key=new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
Cipher cipher;
byte[] ciphertext;
int cipherlength;
try{
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
input=simple_text.getText.getBytes();
SecretKeySpec key=new SecretKeySpec(keyBytes,"DES");
IvParameterSpec ivSpec=new IvParameterSpec(ivBytes);
cipher=Cipher.getInstance("DES/CTR/NoPadding","BC");
cipher.init(Cipher.ENCRYPT_MODE,key,ivSpec);
ciphertext=new byte[cipher.getOutputSize(input.length)];
cipherlength=cipher.update(input,0,input.length,ciphertext);
cipherlength+=cipher.doFinal(ciphertext,cipherlength);
Encrypt_text.setText(new String(ciphertext));
System.out.println(" cipher"+ new String(ciphertext));
}catch(Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
decrypt
CBC using DES with an IV based on a nonce. In this case a hypothetical message n
umber.
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainClass {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider(
));
byte[] input = "input".getBytes();
byte[] keyBytes = "input123".getBytes();
byte[] msgNumber = "input".getBytes();
IvParameterSpec zeroIv = new IvParameterSpec(new byte[8]);
SecretKeySpec key = new SecretKeySpec(keyBytes, "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS7Padding", "BC");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
IvParameterSpec encryptionIv = new IvParameterSpec(cipher.doFinal(msgNumber)
, 0, 8);
cipher.init(Cipher.ENCRYPT_MODE, key, encryptionIv);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
System.out.println("cipher: " + new String(cipherText) + " bytes: " + ctLeng
th);
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
IvParameterSpec decryptionIv = new IvParameterSpec(cipher.doFinal(msgNumber)
, 0, 8);
cipher.init(Cipher.DECRYPT_MODE, key, decryptionIv);
byte[] plainText = new byte[cipher.getOutputSize(ctLength)];
int ptLength = cipher.update(cipherText, 0, ctLength, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
System.out.println("plain : " + new String(plainText, ptLength));
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import javax.crypto.Cipher;
import javax.crypto.SealedObject;
import javax.crypto.SecretKey;
public class Main {
private static Object readFromFile(String filename) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File(f
ilename)));
Object object = ois.readObject();
ois.close();
return object;
}
public static void main(String[] args) throws Exception {
SecretKey key = (SecretKey) readFromFile("secretkey.dat");
SealedObject sealedObject = (SealedObject) readFromFile("sealed.dat");
String algorithmName = sealedObject.getAlgorithm();
Cipher cipher = Cipher.getInstance(algorithmName);
cipher.init(Cipher.DECRYPT_MODE, key);
String text = (String) sealedObject.getObject(cipher);
System.out.println("Text = " + text);
}
}
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
DesEncrypter(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");
// Encrypt
byte[] enc = ecipher.doFinal(utf8);
// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
// Decode using utf-8
return new String(utf8, "UTF8");
}
}
public class Main {
public static void main(String[] argv) throws Exception {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
DesEncrypter encrypter = new DesEncrypter(key);
String encrypted = encrypter.encrypt("Don"t tell anybody!");
String decrypted = encrypter.decrypt(encrypted);
}
}
Message without tampering with MAC (DES), encryption AES in CTR mode
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class MainClass {
public static void main(String[] args) throws Exception {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider(
));
SecureRandom random = new SecureRandom();
IvParameterSpec ivSpec = createCtrIvForAES();
Key key = createKeyForAES(256, random);
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding", "BC");
String input = "12345678";
Mac mac = Mac.getInstance("DES", "BC");
byte[] macKeyBytes = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08 };
Key macKey = new SecretKeySpec(macKeyBytes, "DES");
cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] cipherText = new byte[cipher.getOutputSize(input.length() + mac.getMa
cLength())];
int ctLength = cipher.update(input.getBytes(), 0, input.length(), cipherText
, 0);
mac.init(macKey);
mac.update(input.getBytes());
ctLength += cipher.doFinal(mac.doFinal(), 0, mac.getMacLength(), cipherText,
ctLength);
cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] plainText = cipher.doFinal(cipherText, 0, ctLength);
int messageLength = plainText.length - mac.getMacLength();
mac.init(macKey);
mac.update(plainText, 0, messageLength);
byte[] messageHash = new byte[mac.getMacLength()];
System.arraycopy(plainText, messageLength, messageHash, 0, messageHash.lengt
h);
System.out.println("plain : " + new String(plainText) + " verified: "
+ MessageDigest.isEqual(mac.doFinal(), messageHash));
}
public static SecretKey createKeyForAES(int bitLength, SecureRandom random)
throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator generator = KeyGenerator.getInstance("AES", "BC");
generator.init(128, random);
return generator.generateKey();
}
public static IvParameterSpec createCtrIvForAES() {
return new IvParameterSpec("1234567812345678".getBytes());
}
}
package com.journaldev.misc;
import
import
import
import
import
import
import
import
import
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.io.OutputStream;
java.security.InvalidAlgorithmParameterException;
java.security.InvalidKeyException;
java.security.NoSuchAlgorithmException;
java.security.spec.AlgorithmParameterSpec;
import
import
import
import
import
import
import
javax.crypto.Cipher;
javax.crypto.CipherInputStream;
javax.crypto.CipherOutputStream;
javax.crypto.KeyGenerator;
javax.crypto.NoSuchPaddingException;
javax.crypto.SecretKey;
javax.crypto.spec.IvParameterSpec;
try {
//create SecretKey using KeyGenerator
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec paramSpec = new IvParameterSpec(iv);
//get Cipher instance and initiate in encrypt mode
encryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
//get Cipher instance and initiate in decrypt mode
decryptCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
//method to encrypt clear text file to encrypted file
encrypt(new FileInputStream(clearTextFile), new FileOutputStream(cip
herTextFile));
//method to decrypt encrypted file to clear text file
decrypt(new FileInputStream(cipherTextFile), new FileOutputStream(cl
earTextNewFile));
System.out.println("DONE");
} catch (NoSuchAlgorithmException |
NoSuchPaddingException |
InvalidKeyException |
InvalidAlgorithmParameterException |
IOException e) {
e.printStackTrace();
}
}
private static void encrypt(InputStream is, OutputStream os) throws IOExcept
ion {
//create CipherOutputStream to encrypt the data using encryptCipher
os = new CipherOutputStream(os, encryptCipher);
writeData(is, os);
}
private static void decrypt(InputStream is, OutputStream os) throws IOExcept
ion {
//create CipherOutputStream to decrypt the data using decryptCipher
is = new CipherInputStream(is, decryptCipher);
writeData(is, os);
}
//utility method to read data from input stream and write to output stream
private static void writeData(InputStream is, OutputStream os) throws IOExce
ption{
byte[] buf = new byte[1024];
int numRead = 0;
//read and write operation
while ((numRead = is.read(buf)) >= 0) {
os.write(buf, 0, numRead);
}
os.close();
is.close();
}
}