Search This Blog

Showing posts with label security. Show all posts
Showing posts with label security. 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

Tuesday, March 24, 2020

Java : Static method to get classes/Resources folder and copy from inside zip to outter



URL url = MethodHandles.lookup().lookupClass().getResource ( "text.json" );
FileUtils.copyURLToFile(url,  new File ( "D:/text.json" ) );

Wednesday, February 26, 2020

Pytesseract Read a image and labeled or Rename as filename

pytesseract_image.py

import cv2
import os
import pytesseract
try:
    from PIL import Image
except ImportError:
    import Image

pytesseract.pytesseract.tesseract_cmd = 'C:/Program Files/Tesseract-OCR/tesseract.exe'

#for x in range (1,1000): 
#    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ str(x) + '.png')

folderpath = "D:/Temp/Captcha/program/"
for filename in os.listdir(folderpath):   
    img_cv = cv2.imread(r'D:/Temp/Captcha/program/'+ filename )
    # By default OpenCV stores images in BGR format and since pytesseract assumes RGB format,
    # we need to convert from BGR to RGB format/mode:
    img_rgb = cv2.cvtColor(img_cv, cv2.COLOR_BGR2RGB)
    imagetext = pytesseract.image_to_string(img_rgb)
    print (imagetext)
    # OR
    #img_rgb = Image.frombytes('RGB', img_cv.shape[:2], img_cv, 'raw', 'BGR', 0, 0)
    #imagetext = pytesseract.image_to_string(img_rgb)
    #print (imagetext)
    src =folderpath+ filename
    dst =folderpath+ imagetext + ".png"
    os.rename(src, dst)


NOTE:
save filenmae other than pytesseract.py - Note: to avoid pytesseract.image_to_string not found error

Python - Download Captcha Images

import requests
import os
from random import randint

for x in range(100, 1000):
    url = ""
    payload = {}
    headers= {}
    response = requests.request("GET", url, headers=headers, data = payload)
    #print(response.text.encode('utf8'))
   
    url = ""
    payload = {}
    response = requests.request("GET", url, cookies=response.cookies)
   
    f_ext = x
    f_name = 'D:/Temp/Captcha/{}.png'.format(f_ext)
    with open(f_name, 'wb') as f:
        f.write(response.content)
   
    print("Iteration : " + str(x) )

print( "Done !")

Tuesday, February 11, 2020

Joomla - You are not authorised to view this resource

1. Basically we are not using the latest version of PHP and Joomla
2. So please download the latest version from joomla 3.9.x
3. Install XAMPP latest in your local 
4. Go to xmapp/htdocs folder,
5. Extract the latest joomla into htdocs [for ex: infovijaysite ]
6. Open it in browser http://localhost/infovijaysite
7. Joomla installation page will come. setup with the new database
8. Remove the installation folder



9. Now check the latest database with your old database. 
    9.1 you can see additionally 10+ tables are newly added in latest joomla version.
    9.2 you can see some of the columns like client_id, package_id, asset_id in few tables. 
    9.3 truncate drv_sessions table  [_session] table.
    9.4 check few table, values also changed from the old to new. possible change that too. I have taken that only table dump from new and replaced with old if the rows are same or more/less.
    9.5 verify each old table columns with new table columns. if any thing added, please add the same in your old database itself. 
    9.6  Keep remember, add those columns in the same table in your old DB and also create those 10+ tables in old DB. 



10. change the old DB name in configuration.php under your folder [ex: infovijaysite ]. 
11. ctrl+f5 or clear cache and refresh your site [point 6].


ENJOY.
I have done the same for ma own site, please visit -  www.infovijay.com



Note: But the menu may be looks diff than your old style. but your site is reborn. 






Wednesday, January 22, 2020

Java CMD -D arguments Custom

Note your java class or jar name should be at last and not first before -D.

Ex:
YES = java -jar -Dfiles=c1 -Dexcludes=va2 filename.jar
NO = java -jar filename.jar -Dfiles=c1 -Dexcludes=va2


In Program
Properties systemProperties = System.getProperties();
System.out.println( systemProperties.get ( "files" ) );
System.out.println( systemProperties.get ( "excludes" ) );


Monday, January 13, 2020

Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

1. You are missing the @SpringBootApplication annotation on your Start class 
2. SpringApplication.run ( , args );  
3. in all the area in that java file.

Tuesday, December 10, 2019

Python Google Speech Setup and Example (WINDOWS)

1. Download SOX latest version - https://sourceforge.net/projects/sox/files/sox/

2. Install it (ex: C:\Program Files (x86)\sox-14-4-2 )
     2.1 download 2 (libmad-0.dll, libmp3lame-0.dll) DLLs and copy to C:\Program Files (x86)\sox-14-4-2;

                 https://app.box.com/s/tzn5ohyh90viedu3u90w2l2pmp2bl41t


3. Set environment path in system variable

4. Restart the IDE or CMD prompt

5. in cmd prompt
        set path=%path%;C:\Program Files (x86)\sox-14-4-2;
       echo %path%

6. pip install google_speech
    pip install sox

7. create a sample test.py


from google_speech import Speech

# say "Hello World"
text = "Hello This is Vijay DR";
lang = "en";
speech = Speech(text, lang);
speech.play();

# you can also apply audio effects while playing (using SoX)
# see http://sox.sourceforge.net/sox.html#EFFECTS for full effect documentation
sox_effects = ("speed", "1.5");
speech.play(sox_effects);

# save the speech to an MP3 file (no effect is applied)
speech.save("output.mp3");


8. cmp prompt py test.py



enjoy !
vijay

Tuesday, September 24, 2019

Python - Map Nested Map

Input

[{
"groupId": "a1",
"orderId": "b1"
}, {
"groupId": "a2",
"orderId": "b2"
}, {
"groupId": "a2",
"orderId": "b3"
}]

Output 
{
'a1': {
'b1': {
'groupId': 'a1',
'orderId': 'b1'
}
},
'a2': {
'b2': {
'groupId': 'a2',
'orderId': 'b2'
},
'b3': {
'groupId': 'a2',
'orderId': 'b3'
}
}
}


Code

data = [{"groupId":"a1","orderId":"b1"},{"groupId":"a2","orderId":"b2"}, {"groupId":"a2","orderId":"b3"}]

groupMap = {}


for x in data:
    if ( helpers.isKeyExists (groupMap, x['groupId']) == False ):
        orderMap = {}
        orderMap[x['orderId']] = x;
        groupMap[x['groupId']] = orderMap;
    else:
        tempOrderMap = {}
        #if ( helpers.isKeyExists (orderMap, x['groupId']) == False ):
        tempOrderMap = groupMap[x['groupId']]
        tempOrderMap[x['orderId']] = x;
        groupMap[x['groupId']] = tempOrderMap;
       

print (groupMap);


Friday, August 2, 2019

Cors - Cross Site - Angular 2 7 8 Spring boot

1. Create a java file, add spring security jar in pom.xml
2. Angular just set what you want as custom header

SecurityConfig.java

package com.product.rpa.api.config;

import java.util.Arrays;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @author drvijay
 * @description main class
 * @version 1.0
 * @date 02-08-2019 1:30 PM
 */

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{

/* (non-Javadoc)
* @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
*/
@Override
protected void configure ( HttpSecurity http ) throws Exception
{
http.cors ().and ().csrf ().disable ();
}

/**
* Cors configuration source.
*
* @return the cors configuration source
*/
@Bean
CorsConfigurationSource corsConfigurationSource ()
{
CorsConfiguration configuration = new CorsConfiguration ();
configuration.setAllowedOrigins ( Arrays.asList ( "*" ) );
configuration.setAllowedMethods ( Arrays.asList ( "*" ) );
configuration.setAllowedHeaders ( Arrays.asList ( "*" ) );
configuration.setAllowCredentials ( true );
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource ();
source.registerCorsConfiguration ( "/**", configuration );
return source;
}

}



Angular JS

DataTableComponent.ts

import { HttpHeaders } from  '@angular/common/http';

export class DataTableComponent implements OnInit {
    public tableData;

 
    public baseURL = "http://localhost:8080/";

    constructor(private _httphelperService: HttphelperService) { }

    ngOnInit() {
        this.loadData();
    }

    loadData() {
        console.log("loadData calling");

        let jsonBody = {                     
            "key": "value"
        }

        let headers = new HttpHeaders({
            "Access-Control-Allow-Origin": "*",
            "Content-Type": "application/json",
            "appToken": "abcde12345"
        })

        let response = this._httphelperService.performPOST(this.baseURL + "/api", jsonBody , headers)
            .subscribe(data => {
                this.tableData = data;
                //alert (JSON.stringify(this.tableData));
            },
            err => {
                console.log(err.message);
            }
            );
        //console.log(response);
    }
}



HttphelperService.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from  '@angular/common/http';
import { CustomPromisify } from 'util';
import { Observable } from 'rxjs/Observable';
import { catchError, map } from "rxjs/operators";

@Injectable()
export class HttphelperService {
    public httpOptions: any;

    constructor(private _http: HttpClient) {
        //Http Headers Options
        this.httpOptions = {
            headers: new HttpHeaders(
                {
                    "Access-Control-Allow-Origin": "*",
                    "Content-Type": "application/json"
                })
        }
    }

    public performPOST(baseUrl: string, inputBody: any, apiHeaders: any) {
        if (apiHeaders === "" || apiHeaders === null || typeof apiHeaders === "undefined") {
            return this._http.post(baseUrl, inputBody, this.httpOptions);
        }
        else {
            console.log (apiHeaders);
            return this._http.post(baseUrl, inputBody, { headers: apiHeaders });
        }
    }


    public performGET(baseUrl: string, apiHeaders: any) {
        if (apiHeaders === "" || apiHeaders === null || typeof apiHeaders === "undefined") {
            return this._http.get(baseUrl, this.httpOptions);
        }
        else {
            return this._http.get(baseUrl, { headers: apiHeaders });
        }
    }

}



ENJOY


Thursday, June 13, 2019

Subversion - SVN Clean UP - previous operation has not finished

  • Right click on folder
  • Go to TortoiseSVN -> Clean Up...
  • Make sure the option to Break Locks is ticked and click OK

- Enjoy

Tuesday, May 28, 2019

Python - Type inconsistent dedent at line XX, column X



First 2 lines are used tab and teh 3rd line used space button to align which causes the dedent problem.

So select that 3rd line, Shift + tab in eclipse or hit backspace to move to first column, then press tab. this will align to the same with tab rather than space bar align.

fixed
enjoy.

Wednesday, May 8, 2019

ObjectMapper - read JSON list to VO object

ObjectMapper mapper = new ObjectMapper ();

mapper.enable ( DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY );
mapper.configure ( JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true );

List queryBuilderVOList = Arrays.asList ( mapper.readValue ( mapper.writeValueAsString ( map.get ( "data" ) ).getBytes (), QueryBuilderVO [].class ) );

Thursday, May 2, 2019

How to get Financial Year - Java

package com.rule.xxx;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/*
author - dr vijay
*/

public class FinancialYear
{

/**
* Gets the financial year.
*
* @param d the d
* @return the financial year
*/
public static int getFinancialYear ( Date d )
{
int month;
int year;
Calendar cal = Calendar.getInstance ();
cal.setTime ( d );

//calendar will start from 0-11 [0=jan, 11=dec]
month = cal.get ( Calendar.MONTH );
int advance = ( month < 3 ) ? 0 : 1;
year = cal.get ( Calendar.YEAR ) + advance;
return year;
}

public static void main ( String [] args ) throws Exception
{
String sDate1 = "01/04/2019";
Date date1 = new SimpleDateFormat ( "dd/MM/yyyy" ).parse ( sDate1 );
System.out.println ( sDate1 + " \t " + date1 );
System.out.println ( FinancialYear.getFinancialYear ( date1 ) );
}
}


OUTPUT

01/04/2018 Sun Apr 01 00:00:00 IST 2018
2019


Wednesday, February 27, 2019

Stock Market Walk Though - Weekly Expiry - 28-02-19

1. Monthly Expiry
2. Features- Nifty looks like bearish, BN slightly looks strong bearish.
3. Option PCR - Nifty/BN - Netural
4. Up side 75-100 and BN - 150-200 pts expected. down side 50-75 and the BN - 200 Pts
5. FII/DII are net buyers
6. SGX are positive now.
7. Surprisingly NIFTY 10400 PE is added and it is not 7rs. Open nifty in green may reduce the premium,
8. Today trade will confuse us. coz of IND/PAK and Trade war.
9. Nifty  may close in between 10700 - 10900 [range will be 200 pts, point 8th], BN may close inbetween 26850-27100
10. Max Pain on nifty - 10800, BN 27000.

TRADE WITH EXTRA CAUTION,


My Trade Plan

 1. ATM in stocks, OTM on Nifty
 2. LOTS - Confidential*


HAPPY TRADING
Vijay

Wednesday, February 6, 2019

Stock Market Walk Though - Weekly Expiry - 07-02-19

1. Bank Nifty Weekly Expiry
2. RBI policy announcement is there today and there is a little chance to impact the market.
3. If any rate cut is happens, then that will impact the bank nifty expiry and becomes volatile
4. BN will be in the range of 27000 - 27650 and more chances to close in down side 27200 - 27300 & up side 27350 -27500, coz max pain at 27300.
5. BN daily charts in bullish and it formed like spinning TOP, so take trade after the HIGH or LOW breakouts.
6. MACD & DMA 50,200 golden crossover signal shows the bullish trend,


TRADE WITH CAUTION,


My Trade Plan

 1. BN - Stradle, Strangle [depends]
 2. LOTS - Confidential*


HAPPY TRADING
Vijay


Friday, November 16, 2018

Java Dynamic Method Call with params by using reflection

package com.product.rpa.api.ws;

import java.lang.reflect.Method;

public class DynamicMethodCall
{
public String sample ()
{
return "vijay";
}

public String sampleWithParam ( String x )
{
return x + " " + x;
}

public String sampleWithMultipleParams ( String x, int i )
{
return x + " " + i;
}

public static void main ( String args[] ) throws Exception
{
DynamicMethodCall dynamicMethodCall = new DynamicMethodCall ();

// with out param
Method method = dynamicMethodCall.getClass ().getMethod ( "sample" );
String result = (String) method.invoke ( dynamicMethodCall );
System.out.println ( result );

// with param
// String parameter
Class [] paramString = new Class[1];
paramString[0] = String.class;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithParam", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - param" );
System.out.println ( result );

// with multiple params
// String parameter
paramString = new Class[2];
paramString[0] = String.class;
paramString[1] = Integer.TYPE;

method = dynamicMethodCall.getClass ().getMethod ( "sampleWithMultipleParams", paramString );
result = (String) method.invoke ( dynamicMethodCall, "hi - ", 100 );
System.out.println ( result );

}
}

Friday, September 28, 2018

Nodejs code to convert string date to another date format.

Sample nodejs code to convert string date to another format.


date.js

var moment = require('moment');
bar ('1980-08-29', 'YYYY-MM-DD', 'DD/MM/YYYY');    //calling method

function bar(date, currentFormat, requiredFormat )
{
    var date = moment(date,currentFormat);
    var train_date = date.format(requiredFormat);
    console.log(train_date);        // 29/08/1980
    return train_date;
}
exports.bar = bar;



//npm install --save
//node date.js

Monday, September 17, 2018

NodeJS - Request Plugin for file attachment MULTIPART/FORM-DATA

package.json

{
  "name": "sample",
  "version": "1.0.0",
  "description": "",
  "main": "apicall.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "dependencies": { 
    "request": "^2.83.0" 
  }
}



apicall.js

var fs = require("fs");
var request = require("request");

var fs = require('fs');
var request = require('request');
request.post({
    url: 'https://url/upload',
    formData: {
keyName1: 'value1',
                keyName2: 'value2',               
               file: fs.createReadStream('d:/temp/30off.jpg')
    },
}, function(error, response, body) {
    console.log(body);
});


steps

npm install
node apicall.js

Tuesday, September 11, 2018

JSoup - HTML Parser for image audio video attributes

SAMPLE

package com.jsoup;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.safety.Whitelist;
import org.jsoup.select.Elements;

public class HtmlParser
{
public static String html = "<html><head><title>Sample Title</title></head>"
         + "<body>"
         + "<p>Sample Content1</p>"              
         + "<img name='pic1' id='picid1' src='test.jpg' />"  
         + "<p>Sample Content2</p>"
         + "<p>Sample Content3</p>"
         + "<img name='pic2' id='picid2' src='test2.jpg' />"
         + "<video width='320' height='240' controls>"
        + "<source id='1' src='movie.mp4' type='video/mp4'>"
        + " <source  id='2' src='movie.ogg' type='video/ogg'>"
        + "<Br/>Your browser does not support the video tag."
        + "</video>"
        + "<audio controls>"
        + "<source id='1' src='horse.ogg' type='audio/ogg'>"
        + "<source id='2' src='horse.mp3' type='audio/mpeg'>"
        + "<Br/>Your browser does not support the audio tag."
        + "</audio>"
        + "<p><a href='http://example.com/'" + " onclick='checkData()'>Link</a></p>"
         +"</body></html>";


/*output
Initial HTML: <p><a href='http://example.com/' onclick='checkData()'>Link</a></p>
Cleaned HTML: <p><a href="http://example.com/" rel="nofollow">Link</a></p>*/
public static void safeGuardHtmlSanitize ()
{
System.out.println ( "Initial HTML: " + html );
String safeHtml = Jsoup.clean ( html, Whitelist.basic () );
System.out.println ( "Cleaned HTML: " + safeHtml );
}

public static void main ( String [] args )
{

Document document = Jsoup.parse ( html );
// img with src ending .png
Elements imgs = document.select ( "img" );
for ( Element img : imgs )
{
System.out.println ( "Name: " + img.attr ( "name" ) + " id: " + img.id () + " src: " + img.attr ( "src" ) );
//to replace the value existing
img.attr ( "src", "replacedImage.jpg" ) ;
}
System.out.println ( "\n\n" );

Elements videos = document.select ( "video" );
Elements videoSrc = videos.select ( "source" );
for ( Element vSrc : videoSrc )
{
System.out.println ( " id: " + vSrc.id () + " src: " + vSrc.attr ( "src" ) + " type: " + vSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

Elements audios = document.select ( "audio" );
Elements audioSrc = audios.select ( "source" );
for ( Element aSrc : audioSrc )
{
System.out.println ( " id: " + aSrc.id () + " src: " + aSrc.attr ( "src" ) + " type: " + aSrc.attr ( "type" ));
}
System.out.println ( "\n\n" );

safeGuardHtmlSanitize();
}
}



OUTPUT

Name: pic1 id: picid1 src: test.jpg
Name: pic2 id: picid2 src: test2.jpg



 id: 1 src: movie.mp4 type: video/mp4
 id: 2 src: movie.ogg type: video/ogg



 id: 1 src: horse.ogg type: audio/ogg
 id: 2 src: horse.mp3 type: audio/mpeg



Initial HTML: Sample TitleSample Content1
Sample Content2
Sample Content3
Link
Cleaned HTML: Sample Title
Sample Content1
Sample Content2
Sample Content3


Your browser does not support the video tag.

Your browser does not support the audio tag.
Link



Hit Counter


View My Stats