Tutorialspoint

Java Cryptography Encrypting Data

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.Signature;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;

public class CipherSample {
   public static void main(String args[]) throws Exception{
   
      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withRSA");
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();      
	
      //Creating a Cipher object
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        
      //Initializing a Cipher object
      cipher.init(Cipher.ENCRYPT_MODE, pair.getPublic());
	  
      //Adding data to the cipher
      byte[] input = "Welcome to Tutorialspoint".getBytes();	  
      cipher.update(input);
	  
      //encrypting the data
      byte[] cipherText = cipher.doFinal();	 
      System.out.println(new String(cipherText, "UTF8"));
   }
}

Java Cryptography Creating Signature

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;

public class CreatingDigitalSignature {
   public static void main(String args[]) throws Exception {
      //Accepting text from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter some text");
      String msg = sc.nextLine();
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
      
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();
      
      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withDSA");
      
      //Initialize the signature
      sign.initSign(privKey);
      byte[] bytes = "msg".getBytes();
      
      //Adding data to the signature
      sign.update(bytes);
      
      //Calculating the signature
      byte[] signature = sign.sign();
      
      //Printing the signature
      System.out.println("Digital signature for given text: "+new String(signature, "UTF8"));
   }
}

Java Cryptography Encrypting data

import java.security.MessageDigest;
import java.util.Scanner;

public class MessageDigestExample {
   public static void main(String args[]) throws Exception{
	  
      //Reading data from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the message");
      String message = sc.nextLine();
	  
      //Creating the MessageDigest object  
      MessageDigest md = MessageDigest.getInstance("SHA-256");

      //Passing data to the created MessageDigest Object
      md.update(message.getBytes());
      
      //Compute the message digest
      byte[] digest = md.digest();      
      
      System.out.println(digest);  
     
      //Converting the byte array in to HexString format
      StringBuffer hexString = new StringBuffer();
      for (int i = 0;i<digest.length;i++) {
         hexString.append(Integer.toHexString(0xFF & digest[i]));
      }
      System.out.println("Hex format : " + hexString.toString());     
   }
}

Java Cryptography Verifying signature

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;

public class SignatureVerification {
   public static void main(String args[]) throws Exception{

      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
	      
      //Initializing the key pair generator
      keyPairGen.initialize(2048);
	      
      //Generate the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the privatekey from the key pair
      PrivateKey privKey = pair.getPrivate();

      //Creating a Signature object
      Signature sign = Signature.getInstance("SHA256withDSA");

      //Initializing the signature
      sign.initSign(privKey);
      
      byte[] bytes = "Hello how are you".getBytes();
      //Adding data to the signature
      sign.update(bytes);
      
      //Calculating the signature
      byte[] signature = sign.sign();      
      
      //Initializing the signature
      sign.initVerify(pair.getPublic());
      sign.update(bytes);
      
      //Verifying the signature
      boolean bool = sign.verify(signature);
      
      if(bool) {
         System.out.println("Signature verified");   
      }else{
         System.out.println("Signature failed");
      }
   }
}

Java Cryptography KeyPairGenerator

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;

public class KeyPairGenertor {
   public static void main(String args[]) throws Exception{
      
      //Creating KeyPair generator object
      KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
      
      //Initializing the KeyPairGenerator
      keyPairGen.initialize(2048);
      
      //Generating the pair of keys
      KeyPair pair = keyPairGen.generateKeyPair();
      
      //Getting the private key from the key pair
      PrivateKey privKey = pair.getPrivate();   
      
      //Getting the public key from the key pair
      PublicKey publicKey = pair.getPublic(); 
      System.out.println("Keys generated");
   }
}

Java Cryptography KeyGenerator

import java.security.MessageDigest;
import java.util.Scanner;

public class MessageDigestExample {
   public static void main(String args[]) throws Exception{
	  
      //Reading data from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the message");
      String message = sc.nextLine();
	  
      //Creating the MessageDigest object  
      MessageDigest md = MessageDigest.getInstance("SHA-256");

      //Passing data to the created MessageDigest Object
      md.update(message.getBytes());
      
      //Compute the message digest
      byte[] digest = md.digest();      
      
      System.out.println(digest);  
     
      //Converting the byte array in to HexString format
      StringBuffer hexString = new StringBuffer();
      for (int i = 0;i<digest.length;i++) {
         hexString.append(Integer.toHexString(0xFF & digest[i]));
      }
      System.out.println("Hex format : " + hexString.toString());     
   }
}

Java Cryptography Creating a MAC

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;
import javax.crypto.Mac;

public class MacSample {
   public static void main(String args[]) throws Exception{
      
      //Creating a KeyGenerator object
      KeyGenerator keyGen = KeyGenerator.getInstance("DES");

      //Creating a SecureRandom object
      SecureRandom secRandom = new SecureRandom();

      //Initializing the KeyGenerator
      keyGen.init(secRandom);

      //Creating/Generating a key
      Key key = keyGen.generateKey();	 

      //Creating a Mac object
      Mac mac = Mac.getInstance("HmacSHA256");

      //Initializing the Mac object
      mac.init(key);

      //Computing the Mac
      String msg = new String("Hi how are you");
      byte[] bytes = msg.getBytes();      
      byte[] macResult = mac.doFinal(bytes);

      System.out.println("Mac result:");
      System.out.println(new String(macResult));     
   }
}

Java Cryptography Message Digest

import java.security.MessageDigest;
import java.util.Scanner;

public class MessageDigestExample {
   public static void main(String args[]) throws Exception{
	  
      //Reading data from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the message");
      String message = sc.nextLine();
	  
      //Creating the MessageDigest object  
      MessageDigest md = MessageDigest.getInstance("SHA-256");

      //Passing data to the created MessageDigest Object
      md.update(message.getBytes());
      
      //Compute the message digest
      byte[] digest = md.digest();      
      
      System.out.println(digest);  
     
      //Converting the byte array in to HexString format
      StringBuffer hexString = new StringBuffer();
      for (int i = 0;i<digest.length;i++) {
         hexString.append(Integer.toHexString(0xFF & digest[i]));
      }
      System.out.println("Hex format : " + hexString.toString());     
   }
}

java.util.zip.Inflater.read() Method Example

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.zip.DataFormatException;
import java.util.zip.Deflater;
import java.util.zip.InflaterInputStream;

public class InflaterInputStreamDemo {
   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");
      int length = message.length();
      // Compress the bytes
      byte[] output = new byte[1024];
      Deflater deflater = new Deflater();
      deflater.setInput(input);
   
      deflater.finish();
      int compressedDataLength = deflater.deflate(output,0 , output.length, Deflater.NO_FLUSH);
      System.out.println("Total uncompressed bytes input :" + deflater.getTotalIn());
      System.out.println("Compressed Message Checksum :" + deflater.getAdler());     
      deflater.finished();

      System.out.println("Compressed Message length : " + compressedDataLength);
   
      ByteArrayInputStream bin = new ByteArrayInputStream(output);
      InflaterInputStream inflaterInputStream = new InflaterInputStream(bin);
      byte[] result = new byte[1024];

      inflaterInputStream.read(result, 0, result.length);

      inflaterInputStream.close();
      // Decode the bytes into a String
      String message1 = new String(result,0, length,"UTF-8");
      System.out.println(message.equals(message1));
   }
}

java.util.zip.GZIPOutputStream.write() Method Example

package com.tutorialspoint;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.DataFormatException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZIPOutputStreamDemo {

   public static void main(String[] args) throws DataFormatException, IOException {
      String message = "Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;"
         +"Welcome to TutorialsPoint.com;";
    
      System.out.println("Original Message length : " + message.length());
      byte[] input = message.getBytes("UTF-8");

      // Compress the bytes
      ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
      GZIPOutputStream outputStream = new GZIPOutputStream(arrayOutputStream);
      outputStream.write(input,0, input.length);
      outputStream.close();

      //Read and decompress the data
      byte[] readBuffer = new byte[5000];
      ByteArrayInputStream arrayInputStream = 
         new ByteArrayInputStream(arrayOutputStream.toByteArray());
      GZIPInputStream inputStream = new GZIPInputStream(arrayInputStream);
      int read = inputStream.read(readBuffer,0,readBuffer.length);
      inputStream.close();
      //Should hold the original (reconstructed) data
      byte[] result = Arrays.copyOf(readBuffer, read);

      // Decode the bytes into a String
      message = new String(result, "UTF-8");
    
      System.out.println("UnCompressed Message length : " + message.length());
   }
}

1 2 3 4 5 6 7 ... 320 Next
Advertisements
Loading...