Search This Blog

Showing posts with label decrypt. Show all posts
Showing posts with label decrypt. Show all posts

Wednesday, October 13, 2021

Security : Java PHP encryption decryption for AES-128-CTR or AES/CTR/NoPadding

 Java

package com.security;

import java.util.Base64;


import javax.crypto.Cipher;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.SecretKeySpec;


/**

 * @author drvijay

 * @date 13-0ct-2021

 */


public class EncryptDecrypt

{

private static String encrypt ( String data, String cipherType, String key, String iv )

{

String encrypted = "";


try

{

Cipher encryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, encryptionCipher.getBlockSize () );

encryptionCipher.init ( Cipher.ENCRYPT_MODE, new SecretKeySpec ( key.getBytes (), "AES" ), ivv );

// encrypt

byte [] cipherText = encryptionCipher.doFinal ( data.getBytes () );


encrypted = new String ( Base64.getEncoder ().encode ( cipherText ) );

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return encrypted;

}


private static String decrypt ( String encryptData, String cipherType, String key, String iv )

{

String decrypted = "";

try

{


Cipher decryptionCipher = Cipher.getInstance ( cipherType );

IvParameterSpec ivv = new IvParameterSpec ( iv.getBytes ( "UTF-8" ), 0, decryptionCipher.getBlockSize () );


SecretKeySpec secretKeySpec = new SecretKeySpec ( key.getBytes (), "AES" );

decryptionCipher.init ( Cipher.DECRYPT_MODE, secretKeySpec, ivv );

// decrypt

byte [] finalCipherText = decryptionCipher.doFinal ( Base64.getDecoder ().decode ( encryptData ) );

// converting to string

String finalDecryptedValue = new String ( finalCipherText );

decrypted = finalDecryptedValue;

}

catch ( Exception e )

{

throw new IllegalStateException ( e );

}

return decrypted;

}


public static void main ( String [] args )

{

String cipherType = "AES/CTR/NoPadding";

String valueToEncrypt = "hello, vijay";

String key = "0123456789abcdef";

String iv = "2208250639374785";


String encrypted = encrypt ( valueToEncrypt, cipherType, key, iv );

String decrypted = decrypt ( encrypted, cipherType, key, iv );


//System.out.println(Base64.getDecoder ().decode ( "ycbnIE8vn2lTUi/9F/FEa+5v86qzOU09yjdxfGDc8wA=" ));

// END OF ENCODE CODE

System.out.println ( "encrypted and saved as Base64 : " + encrypted );


System.out.println ( "decrypted from Base64->aes128 : " + decrypted );

// END OF DECRYPT CODE


}

}




PHP code

<!DOCTYPE html>

<html>

<body>

<?php

$simple_string = "hello, vijay";

echo ($simple_string .'<br/>');

        $ciphering = 'AES-128-CTR';

        $iv_length = openssl_cipher_iv_length($ciphering);

        $options = 0;

        // Non-NULL Initialization Vector for encryption

        $iv = '2208250639374785';


       

        $key = '0123456789abcdef';


                $encryption = openssl_encrypt($simple_string, $ciphering,

                    $key, $options, $iv); 

                    echo($encryption .'<br/>');

                    

                  $decryption=openssl_decrypt ($encryption, $ciphering,

                $key, $options, $iv);

                echo($decryption .'<br/>');

                

?>


</body>

</html>



output

hello, vijay
0iQoUVC/QZG3cM20
hello, vijay

Thursday, April 26, 2018

Nodejs - Decrypt for AES-256-CBC with no padding.

var crypto = require ( 'crypto' );
algorithm  = 'aes-256-cbc';

function decrypt ( key, data )
{
    var sha256 = crypto.createHash ( 'sha256' );
    sha256.update ( key );

    var input      = new Buffer ( data, 'base64' ),
        iv         = Buffer.alloc(16);
        ciphertext = input,
        decipher   = crypto.createDecipheriv( algorithm, sha256.digest (), iv ),
        plaintext  = decipher.update ( ciphertext );
    plaintext += decipher.final ();

    return plaintext
};

var deCodeValue = new Buffer ( "encrypted-content-place-here", 'base64' ).toString ( 'utf-8' );
console.log(deCodeValue);
var p           = decrypt ( 'password', deCodeValue );
console.log ( p );

Wednesday, March 7, 2018

PHP - Aes-256-cbc Encrypt Decrypt with IV vector


function encrypt_decrypt($action, $string) {
    $output = false;
    $encrypt_method = "aes-256-cbc";
    $secret_key = 'abcdefghi1234567890';
    $secret_iv = '';
 
// hash
    $key = hash('sha256', $secret_key);
    echo "

".$key;

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    if ( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if( $action == 'decrypt' ) {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}
$plain_txt = "I am vijay";
echo "

Plain Text =" .$plain_txt. "\n";
$encrypted_txt = encrypt_decrypt('encrypt', $plain_txt);
echo "

Encrypted Text = " .$encrypted_txt. "\n";

$decrypted_txt = encrypt_decrypt('decrypt', $encrypted_txt);
echo "

Decrypted Text =" .$decrypted_txt. "\n";

if ( $plain_txt === $decrypted_txt ) echo "

SUCCESS";
else echo "

FAILED";
echo "\n";

?>



Output

Plain Text =I am vijay

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Encrypted Text = THRtUkJYWFUzb1NzUFRoOUw5T3Q2UT09

681448fb66d8704c7d52f6770f6087882db21c899fe48d21012a587bbe70cdd3

Decrypted Text =I am vijay

SUCCESS

PHP - Encrypt / Decrypt with out IV Vector with AES-256-CBC



const PASSWORD = 'abcdefghi1234567890';
const CIPHER_METHOD = 'AES-256-CBC';

function encrypt($str) {
    $val = openssl_encrypt($str, CIPHER_METHOD, hash('sha256', PASSWORD, true));
    return $val;    
}

function decrypt($str) {
   return openssl_decrypt($str, CIPHER_METHOD, hash('sha256', PASSWORD, true));
}

$plain_data = 'I am vijay';

$encrypted = encrypt($plain_data);
echo "Encrypted : ".$encrypted."

";


$decrypted = decrypt($encrypted);
echo "Decrypted : ".$decrypted."

";


?>


Output

: openssl_encrypt(): Using an empty Initialization Vector (iv) is potentially insecure and not recommended in D:\php\test.php >

Encrypted :
zmuNrqZ+GwtQC5B0riJoMw==

Decrypted : I am vijay


Wednesday, March 4, 2015

Password Encrypt in JavaScript and Decrypt in Java

here is the steps,

1. create two jsps. [ login.jsp, validate.jsp ]
2. create one java.
3. Add cryptojs lib [ aes.js ] in your javascript path and mentioned in login.jsp.

here is the sample code.


1. login.jsp

<%@page import="java.util.Arrays"%>
<%@page import="package.Security"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
  
<%
    session.setAttribute ( "RANDKEY", Security.generateSecret (  ) );
%>
  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script src="./js/rollups/aes.js"></script>
<script src="./js/rollups/pbkdf2.js"></script>
<script type="text/javascript">
    function convertAndSubmit()
    {
         var salt = CryptoJS.lib.WordArray.random(128/8);
        var iv = CryptoJS.lib.WordArray.random(128/8);          
        //console.log('salt  '+ salt );
        //console.log('iv  '+ iv );
        var key128Bits100Iterations = CryptoJS.PBKDF2( '<%=session.getAttribute ( "RANDKEY" ) %>', salt, { keySize: 128/32, iterations: 100 });
        //console.log( 'key128Bits100Iterations '+ key128Bits100Iterations);
        var encrypted = CryptoJS.AES.encrypt(document.login.password.value, key128Bits100Iterations, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7  });
        document.login.salt.value = salt;
        document.login.iv.value = iv;
        document.login.password.value = encrypted;
        document.login.submit();
    }
</script>
</head>
<body>
    <form action="validate.jsp" method="post" name="login" autocomplete="off">
        <p>User Name : <input type="text" name="userName"/></p>
        <p>
                       <input type="text" style="display:none;">
            Password : <input type="password" name="password"/>
        </p>
        <p>
            <input type="hidden" name="salt"/>
            <input type="hidden" name="iv"/>
            <input type="button" value="Login" onclick="javascript:convertAndSubmit()"/>
        </p>
    </form>
</body>
</html>





Insert title here




   

        User Name :

       
                      
            Password :
       

       
           
           
           
       

   


2. validate.jsp


<%@page import="java.util.Arrays"%>
<%@page import="package.Security"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
    <%
        out.println ("<br/>Encrypted Password     :    " + request.getParameter("password"));
        out.println ("<br/>Salt                 :    " + request.getParameter("salt"));
        out.println ("<br/>IV                     :    " + request.getParameter("iv"));
        out.println ("<br/>Key                 :    " + session.getAttribute ( "RANDKEY" ) );
        out.println ("<br/>Original Password     :    " + Security.decryptAESEncryptWithSaltAndIV(request.getParameter("password"), session.getAttribute ( "RANDKEY" ).toString (  ), request.getParameter("salt"), request.getParameter("iv") ) );   
    %>
</body>
</html>






    <%
        out.println ("
Encrypted Password     :    " + request.getParameter("password"));
        out.println ("
Salt                 :    " + request.getParameter("salt"));
        out.println ("
IV                     :    " + request.getParameter("iv"));
        out.println ("
Key                 :    " + session.getAttribute ( "RANDKEY" ) );
        out.println ("
Original Password     :    " + YourJava.decryptAESEncryptWithSaltAndIV(request.getParameter("password"), session.getAttribute ( "RANDKEY" ).toString (  ), request.getParameter("salt"), request.getParameter("iv") ) );   
    %>

3. Security.java [add the below methods ]

/**
     * Hex string to byte array.
     *
     * @param s the s
     * @return the byte[]
     */
    public static byte [] hexStringToByteArray ( String s )
    {
        int len = s.length ();
        byte [] data = new byte[len / 2];
        for ( int i = 0; i < len; i += 2 )
        {
            data[i / 2] = (byte) ( ( Character.digit ( s.charAt ( i ), 16 ) << 4 ) + Character.digit ( s.charAt ( i + 1 ), 16 ) );
        }
        return data;
    }

   
    /**
     * Generate key from password with salt.
     *
     * @param password the password
     * @param saltBytes the salt bytes
     * @return the secret key
     * @throws GeneralSecurityException the general security exception
     */
    public static SecretKey generateKeyFromPasswordWithSalt ( String password, byte [] saltBytes ) throws GeneralSecurityException
    {
        KeySpec keySpec = new PBEKeySpec ( password.toCharArray (), saltBytes, 100, 128 );
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance ( PBKDF2_WITH_HMAC_SHA1 );
        SecretKey secretKey = keyFactory.generateSecret ( keySpec );

        return new SecretKeySpec ( secretKey.getEncoded (), AES );
    }

    /**
     * Decrypt aes encrypt with salt and iv.
     *
     * @param encryptedData the encrypted data
     * @param key the key
     * @param salt the salt
     * @param iv the iv
     * @return the string
     * @throws Exception the exception
     */
    public static String decryptAESEncryptWithSaltAndIV ( String encryptedData, String key, String salt, String iv ) throws Exception
    {

        byte [] saltBytes = hexStringToByteArray ( salt );
        byte [] ivBytes = hexStringToByteArray ( iv );
        IvParameterSpec ivParameterSpec = new IvParameterSpec ( ivBytes );
        SecretKeySpec sKey = (SecretKeySpec) generateKeyFromPasswordWithSalt ( key, saltBytes );

        Cipher c = Cipher.getInstance ( AES_CBC_PKCS5_PADDING );
        c.init ( Cipher.DECRYPT_MODE, sKey, ivParameterSpec );
        byte [] decordedValue = new BASE64Decoder ().decodeBuffer ( encryptedData );
        byte [] decValue = c.doFinal ( decordedValue );
        String decryptedValue = new String ( decValue );

        return decryptedValue;
    }

public String generateSecret (  )
{
    return "1234455553dsfdfdsfdsf";   //generate always random number and send for each request
}

 // enjoy madi.

Hit Counter


View My Stats