Showing posts with label Cryptography. Show all posts
Showing posts with label Cryptography. Show all posts

Sunday, September 26, 2021

Java JSON Web Tokens example

 What is JSON Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. For more details, click here.



In this example, User object is encrypted to jwt also validating it and decrypting token to user object again. For complete github source code, click here

JwtTokenService.java

Saturday, June 29, 2019

Spring Boot + Jasypt example to encrypt database password in property file

In this example we will see how to encrypted database password in property file (application.properties or application.yml). We will use Jasypt library for this purpose.

Jasypt (Java Simplified Encryption) is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

To know more about Jasypt, click here. Go to Jasypt website and download the latest version of jasypt client. I am using jasypt-1.9.2-dist.zip. Once downloaded extract the zip file and go to folder /jasypt-1.9.2/bin and execute the below command. Here input is your password or any other text that you want to encrypt and password is the secret key used by Jasypt to encode and decode the input.

encrypt.bat input="dummy_password" password="SECRET_KEY"


To know about encrypting from the command line using Jasypt CLI Tools. click here.

Add below maven dependency in your pom.xml file

<dependency>
<groupId>com.github.ulisesbocchio</groupId>
<artifactId>jasypt-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>

application.yml
Note - the encrypted password in parenthesis with keyword ENC 


There are various options by which you can feed the SECRET_KEY to your application

- From java code you can set system property jasypt.encryptor.password as shown below. You can do this in a separate secure JAR file.

System.setProperty("jasypt.encryptor.password", "SECRET_KEY");


- From command line you can pass system properties

$ Java -Djasypt.encryptor.password=SECRET_KEY Application

Tuesday, October 7, 2014

Java : File Encryption and Decryption using Blowfish

The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
Source : http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.html

javax.crypto.Cipher
This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
Cipher API : http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html

Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA)
http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

Blowfish  
Blowfish has a 64-bit block size and a variable key length from 1 bit up to 448 bits
Blowfish Wiki : http://en.wikipedia.org/wiki/Blowfish_%28cipher%29

Here are the general steps to encrypt/decrypt a file in Java -

  • Create a Key from a given byte array for a given algorithm.
  • Get an instance of Cipher class for a given algorithm transformation.
  • Initialize the Cipher with an appropriate mode (encrypt or decrypt) and the given Key.
  • Invoke doFinal(input_bytes) method of the Cipher class to perform encryption or decryption on the input_bytes, which returns an encrypted or decrypted byte array.
  • Read an input file to a byte array and write the encrypted/decrypted byte array to an output file accordingly.


Please see the below java code

Monday, March 17, 2014

UNIX/LINUX - How to encrypt/decrypt a text file

crypt command can be used to encrypt/decrypt a particular text file in UNIX/LINUX. It is a simple encryption algorithm which works on a secret-key basis. It encrypts or decrypts a stream of data from standard input, and writes the result to standard output. Encryption and decryption is a symmetric process.

Encryption
This will create an encrypted file enTextFile.txt  from a text file textFile.txt. You can use either of the commands both does one and the same task.

crypt ENCRYPTION_KEY < textFile.txt > enTextFile.txt

OR

cat textFile.txt | crypt > enTextFile.txt

Decryption
This will decrypt an encrypted file enTextFile.txt and store the output in textFile.txt

crypt ENCRYPTION_KEY < enTextFile.txt (to show data on console)
crypt ENCRYPTION_KEY < enTextFile.txt > textFile.txt

OR

cat enTextFile.txt | crypt > textFile.txt

Saturday, February 22, 2014

Java : Encode/Decode Base64

We will be using Apache Commons codec to Encode and Decode Base64 data.

Apache Commons Codec (TM) software provides implementations of common encoders and decoders such as Base64, Hex, Phonetic and URLs. To know more, click here.

To run below example you will need to add commons-codec.jar in your classpath. Download commons-codec-1.4.jar.

Please see the self explantory java code below.

Friday, February 21, 2014

Linux : Base64 Encode & Decode with OpenSSL

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding.

Base64 encoding schemes are commonly used when there is a need to encode binary data that needs to be stored and transferred over media that is designed to deal with textual data. This is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications including email via MIME, and storing complex data in XML.

In Linux you can achieve Base64 Encoding and Decoding using pre-installed OpenSSL package.

Encode

Below command will encode any text contents within the quotes and display the encoded contents on a new line.

echo 'text content' | openssl base64

You can also encode multiple lines using below command

echo 'text content' | openssl base64 && echo 'another text content' | openssl base64

Decode

Similarly you can decode using '-d' flag as shown below

echo 'dGV4dCBjb250ZW50Cg==' | openssl base64 -d


Using the OpenSSL package, you can also encode or decode a specific file, as shown below:

encode file
openssl base64 -in 'file.txt' -out 'encodedFile.txt'

decode file
openssl base64 -d -in 'encodedFile.txt' -out 'file.txt'

Wednesday, November 13, 2013

How to use scp command without prompting for password

You may need to write a shell script in which you want to copy a file from one server to another. OfCouse you can easily achieve it with SCP command however when you automate the shell script using crontab it will get stuck because of password prompt. To avoid this you want SCP command to work without prompting for password.

Secure Copy (SCP) allows files to be copied to, from, or between different hosts

Let’s assume you want to copy a file from host server (HOST) to destination server (DEST).

1. On HOST server run below command

$ ssh-keygen -t rsa

First it will prompt for "Enter file in which to save the key" just keep it blank by pressing enter. Then it will prompt for passphrase, again keep it blank by pressing enter. It will generate a public key (id_rsa.pub) and a private key (id_rsa) in the folder <your_home_dir>/.ssh

Output -

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/.ssh/id_rsa.
Your public key has been saved in /home/.ssh/id_rsa.pub.
The key fingerprint is:
1a:7b:3b:d7:5c:f0:6d:f1:01:75:0f:b1:71:6a:15:be user@HOST

2. Share the public key (id_rsa.pub) with DEST server

Copy the file id_rsa.pub from HOST to <your_home_dir>/.ssh folder of DEST. You can use scp or ftp anyway you are comfortable with.

3. Copy the contents of id_rsa.pub to <your_home_dir>/.ssh/authorized_keys2 in DEST server

Below command will append the content of id_rsa.pub to authorized_keys2. Note - you may even copy to authorized_keys whichever file exits on <your_home_dir>/.ssh in DEST server

$ cat id_rsa.pub >> authorized_keys2

Now if you use SCP command to transfer a file from HOST to DEST it won’t prompt for password. I hope it helped you.

Friday, April 27, 2012

Java : Simple AES Cryptography example

Advanced Encryption Standard (AES) is a specification for the encryption of electronic data. It has been adopted by the U.S. government and is now used worldwide. It supersedes DES.[3] The algorithm described by AES is a symmetric-key algorithm, meaning the same key is used for both encrypting and decrypting the data. (To know more click here).

To run this example you will need below mentioned JAR files in classpath.
  • jce.jar
  • rt.jar

If you are using JDK 6 or higher version, These JAR files are implicitly present. You can cross verify in JRE folder. Probably in "C:\Program Files\Java\jre6\lib"

Hence C:\Program Files\Java\jre6\lib\jce.jar and C:\Program Files\Java\jre6\lib\rt.jar are implicitly set in your classpath. Below is the sample self explanatory Java program using AES Cipher. Directly you can run the program and see output.

Simple AES Cipher Example in java

/* SimpleCryptography.java */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SimpleCryptography {
    
    private String AlgoName = "AES";
    
    private String keyString = "Desire_SecretKey";
    
    public String encrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        
        byte[] encrypted = cipher.doFinal(sValue.getBytes());
        
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        String enStr = bASE64Encoder.encodeBuffer(encrypted);    
        
        return enStr;
    }
    
    public String decrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        BASE64Decoder bASE64Decoder = new BASE64Decoder();
        byte decrytByt[] = bASE64Decoder.decodeBuffer(sValue);
        
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        
        byte decrypted[] = cipher.doFinal(decrytByt);
        
        String deStr = new String(decrypted).trim();
        
        return deStr;
    }
    
    public static void main(String[] args) throws Exception {
        
        SimpleCryptography obj = new SimpleCryptography();
        
        String password = "MadanChaudhary";
        
        System.out.println("password : "+password);
        
        String encrypted_password = obj.encrypt(password);
        
        System.out.println("encrypted_password : "+encrypted_password);
        
        String decrypted_password = obj.decrypt(encrypted_password);
        
        System.out.println("decrypted_password : "+decrypted_password);

    }
}

Wednesday, December 7, 2011

Simple Cryptography example in Java

The Java security APIs span a wide range of areas, including cryptography, public key infrastructure, secure communication, authentication, and access control. Java security technology provides the developer with a comprehensive security framework for writing applications, and also provides the user or administrator with a set of tools to securely manage applications.
Source : http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136007.html

javax.crypto.Cipher
This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework.
Cipher API : http://docs.oracle.com/javase/6/docs/api/javax/crypto/Cipher.html

Cipher: initialized with keys, these used for encrypting/decrypting data. There are various types of algorithms: symmetric bulk encryption (e.g. AES, DES, DESede, Blowfish, IDEA)
http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html

Blowfish 
Blowfish has a 64-bit block size and a variable key length from 1 bit up to 448 bits
Blowfish Wiki : http://en.wikipedia.org/wiki/Blowfish_%28cipher%29

To run this example you will need below mentioned JAR files in classpath.
jce.jar
rt.jar


If you are using JDK 6 or higher version, These JAR files are implicitly present. You can cross verify in JRE folder. Probably in "C:\Program Files\Java\jre6\lib"

Hence C:\Program Files\Java\jre6\lib\jce.jar and C:\Program Files\Java\jre6\lib\rt.jar are implicitly set in your classpath.

Below is the sample self explanatory Java program using Blowfish Cipher. Directly you can run the program and see output.

Simple Blowfish Cipher Example in java

/* SimpleCryptography.java */

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class SimpleCryptography {
    
    private String AlgoName = "Blowfish";
    
    private String keyString = "DesireSecretKey";
    
    public String encrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        
        byte[] encrypted = cipher.doFinal(sValue.getBytes());
        
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        String enStr = bASE64Encoder.encodeBuffer(encrypted);    
        
        return enStr;
    }
    
    public String decrypt(String sValue) throws Exception {
        
        SecretKeySpec skeySpec = new SecretKeySpec(keyString.getBytes(), AlgoName);
        Cipher cipher = Cipher.getInstance(AlgoName);
        
        BASE64Decoder bASE64Decoder = new BASE64Decoder();
        byte decrytByt[] = bASE64Decoder.decodeBuffer(sValue);
        
        cipher.init(Cipher.DECRYPT_MODE, skeySpec);
        
        byte decrypted[] = cipher.doFinal(decrytByt);
        
        String deStr = new String(decrypted).trim();
        
        return deStr;
    }
    
    public static void main(String[] args) throws Exception {
        
        SimpleCryptography obj = new SimpleCryptography();
        
        String password = "MadanChaudhary";
        
        System.out.println("password : "+password);
        
        String encrypted_password = obj.encrypt(password);
        
        System.out.println("encrypted_password : "+encrypted_password);
        
        String decrypted_password = obj.decrypt(encrypted_password);
        
        System.out.println("decrypted_password : "+decrypted_password);

    }
}

Output :

password : MadanChaudhary
encrypted_password : 0LpwIuI0V+44sbZ5w3CCZw==

decrypted_password : MadanChaudhary

Below are the known Errors and exceptions I observed while writing this program.

1.
javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

2.
java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)

3.
java.security.NoSuchAlgorithmException: Cannot find any provider supporting MyAlgo
    at javax.crypto.Cipher.getInstance(DashoA13*..)
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting MyAlgo
    at javax.crypto.Cipher.getInstance(DashoA13*..)

4.
java.security.InvalidKeyException: Invalid key length: 16 bytes
    at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
    at javax.crypto.Cipher.b(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
Exception in thread "main" java.security.InvalidKeyException: Invalid key length: 16 bytes
    at com.sun.crypto.provider.DESCipher.engineGetKeySize(DashoA13*..)
    at javax.crypto.Cipher.b(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)

5.
java.security.NoSuchAlgorithmException: Cannot find any provider supporting DSA
    at javax.crypto.Cipher.getInstance(DashoA13*..)
Exception in thread "main" java.security.NoSuchAlgorithmException: Cannot find any provider supporting DSA
    at javax.crypto.Cipher.getInstance(DashoA13*..)

6.
javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.BlowfishCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

7.
java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
Exception in thread "main" java.lang.IllegalStateException: Cipher not initialized
    at javax.crypto.Cipher.c(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)

8.
Exception in thread "main" java.security.InvalidKeyException: Illegal key size or default parameters
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.a(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)
    at javax.crypto.Cipher.init(DashoA13*..)


9. Warnings

$javac SimpleCryptography.java

SimpleCryptography.java:6: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Decoder;
               ^
SimpleCryptography.java:7: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Encoder;
               ^
SimpleCryptography.java:24: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
        ^
SimpleCryptography.java:24: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
        BASE64Encoder bASE64Encoder = new BASE64Encoder();
                                          ^
SimpleCryptography.java:35: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
                BASE64Decoder bASE64Decoder = new BASE64Decoder();
                ^
SimpleCryptography.java:35: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
                BASE64Decoder bASE64Decoder = new BASE64Decoder();
                                                  ^
6 warnings

Thursday, October 20, 2011

RA layer request failed

If you get below mentioned SVN error in Eclipse or My Eclipse, possibly there could be two reasons.

RA layer request failed
svn: Server sent unexpected return value (403 Forbidden) in response to OPTIONS request for 'https://svn.example.com/test'

1. Check whether you have access to the SVN repository.

Hit the SVN url https://svn.example.com/test in your browser and check whether you can access it, if required put user name and password. if you do not have access then ask SVN admin to grant access to you.

2. If you have access and still getting above error.

Go to below mentioned folder and Clean up the folder. Take files backup or simply delete those files.

C:\Documents and Settings\Your User Name\Application Data\Subversion\auth

Now try to access your SVN in Eclipse, Hope you may able to access it, if not let us discuss it.