migrating encrypted data to Sql server from MYSQL server - mysql

We have aes-256 encryption for some data in one of the tables and we are migrating this to sql server. The problem is that we cannot decrypt the data in sql server due to incompatibility. Is there any way we can encrypt data in MYSQL in a way which is compatible with sql server aswell. Any advise ?

if you know the secretkey then you can decrypt the data see following code for encryption and decryption of AES-256 . the code is written in JAVA
check this link AES-256 Password Based Encryption/Decryption in Java
import java.security.AlgorithmParameters;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
public class EncryptionDecryption {
private static String salt;
private static int iterations = 65536 ;
private static int keySize = 256;
private static byte[] ivBytes;
private static SecretKey secretKey;
public static void main(String []args) throws Exception {
salt = getSalt();
char[] message = "PasswordToEncrypt".toCharArray();
System.out.println("Message: " + String.valueOf(message));
System.out.println("Encrypted: " + encrypt(message));
System.out.println("Decrypted: " + decrypt(encrypt(message).toCharArray()));
}
public static String encrypt(char[] plaintext) throws Exception {
byte[] saltBytes = salt.getBytes();
SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(plaintext, saltBytes, iterations, keySize);
secretKey = skf.generateSecret(spec);
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretSpec);
AlgorithmParameters params = cipher.getParameters();
ivBytes = params.getParameterSpec(IvParameterSpec.class).getIV();
byte[] encryptedTextBytes = cipher.doFinal(String.valueOf(plaintext).getBytes("UTF-8"));
return DatatypeConverter.printBase64Binary(encryptedTextBytes);
}
public static String decrypt(char[] encryptedText) throws Exception {
System.out.println(encryptedText);
byte[] encryptedTextBytes = DatatypeConverter.parseBase64Binary(new String(encryptedText));
SecretKeySpec secretSpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretSpec, new IvParameterSpec(ivBytes));
byte[] decryptedTextBytes = null;
try {
decryptedTextBytes = cipher.doFinal(encryptedTextBytes);
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
return new String(decryptedTextBytes);
}
public static String getSalt() throws Exception {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[20];
sr.nextBytes(salt);
return new String(salt);
}
}

Related

Azure Webapp is not updating Azure database for mysql

I have a web application that needs to communicate with azure mysql database. I have included the connection string for jdbc as given in the portal and also modified the connection parameters to allow all inbound IPs. Still the database wont update with the input data. What should I do more?
My connection string is:
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students? useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
My controller servlet code:
package Controller;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.util.Base64;
import java.sql.*;
import Model.*;
#WebServlet(name = "controller")
#MultipartConfig(maxFileSize = 16177215)
public class controller extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String v1 = request.getParameter("email");
String v2 = request.getParameter("password");
String v4 = request.getParameter("act");
String v5 = request.getParameter("name");
if(v4.equals("Register"))
{
request.getRequestDispatcher("/SignUp.jsp").forward(request, response);
}
if (v4.equals("SignUp"))
{
Part filePart = request.getPart("photo");
String email="";
String name="";
String base64Image="";
InputStream image= filePart.getInputStream();
newuser r = new newuser();
r.register(v5, v1, v2, image);
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//Class.forName("com.mysql.jdbc.Driver");
//Connection con = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
if(v4.equals("Log In"))
{
request.getRequestDispatcher("/SignIn.jsp").forward(request, response);
}
if(v4.equals("SignIn"))
{
String email="";
String name="";
String base64Image="";
Check c= new Check();
String res=c.checker(v1,v2);
if(res.equals("SUCCESS")) {
try{
PreparedStatement statement = null;
ResultSet resultSet = null;
//sClass.forName("com.mysql.jdbc.Driver");
//Connection myDbConn = DriverManager.getConnection("jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false", "****", "****");
String url ="jdbc:mysql://upes.mysql.database.azure.com:3306/students?useSSL=true&requireSSL=false";
Connection myDbConn = DriverManager.getConnection(url, "****", "****");
statement = myDbConn.prepareStatement("select * from studentdata where email=?");
statement.setString(1, v1);
resultSet=statement.executeQuery();
while(resultSet.next()) {
email=resultSet.getString("email");
name=resultSet.getString("name");
Blob blob = resultSet.getBlob("photo");
InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] imageBytes = outputStream.toByteArray();
base64Image = Base64.getEncoder().encodeToString(imageBytes);
inputStream.close();
outputStream.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
request.setAttribute("name", name);
request.setAttribute("email", email);
request.setAttribute("image",base64Image);
request.getRequestDispatcher("/UserAccount.jsp").forward(request, response);
}
}
if(v4.equals("Sign Out"))
{
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}```
If you haven't turned the "Allow access to Azure services" option to 'ON', kindly turn it On and then verify the connection.
To do this > On the MySQL server blade > open 'Settings' blade >> click 'Connection Security' > Select ON in "Allow access to Azure services", then Save.
I believe when you mentioned 'modified the connection parameters to allow all inbound IPs' - You have added/allowed Firewall rules for App Service 'outbound IP address' list to MySQL 'Connection security'.
Note that Azure Database for MySQL has SSL enabled by default. If your application is not using SSL to connect to the database, then you need to disable SSL on the MySQL server.
Just to isolate, also please to review the connections via "Diagnose and solve problems'

ActionScript synax-error

as 2.0 was like java, now in 3.0, I cannot find my error in this code:
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class Main {
public static void main(String[] args){
String hostName = "localhost";
Int portNumber = 16834;
String str = "starttimer\r\n";
try {
#SuppressWarnings("resource")
Socket socket = new Socket(hostName, portNumber);
OutputStreamWriter osw = new <br>OutputStreamWriter(socket.getOutputStream(), "UTF-8");$
send(str, osw);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
static void send(String str, OutputStreamWriter o) throws IOException {
o.write(str, 0, str.length());
o.flush();
}
}
By the way dont worry about where is the data going
Obviously, it's not valid ActionScript code. It is Java. That's why you have syntax error. I suggest reading some required minimum about the ActionScript language to be able at least to distinguish it from other one before trying to implement something.

Starting Jenkins parameterized build with Jersey REST and JSON parameters

I have to start Jenkins parameterized build programmatically using Jersey REST API and the values for the parameters must be provided as a JSON object. Any hint or example is welcome.
So, seems like you have not tried it yourself. I can give you a fast 5 minute solution, that should be reworked to be clear and not so ugly, but it works :)
import java.util.ArrayList;
import java.util.List;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
public class JenkinsJob {
public static void main(String[] args) {
runParamJob("http://jenkins.host/", "SOME_JOB", "{\"object\":\"test\"}");
}
public static String runParamJob(String url, String jobName, String paramsJSON) {
String USERNAME = "user";
String PASSWORD = "pass";
Client client = Client.create();
client.addFilter(new com.sun.jersey.api.client.filter.HTTPBasicAuthFilter(USERNAME, PASSWORD));
WebResource webResource = client.resource(url + jobName + "/buildWithParameters?PARAMETER=" + paramsJSON);
ClientResponse response = webResource.type("application/json").get(ClientResponse.class, paramsJSON);
String jsonResponse = response.getEntity(String.class);
client.destroy();
System.out.println("Server response:" + jsonResponse);
return jsonResponse;
}
}
In order to use rest API for parameterized build you should use POST and not get according to Jenkins wiki. Here is an example. Make sure that the json you send is as instructed at the documentation.
take this json for example:
{"parameter": [{"name":"id", "value":"123"}, {"name":"verbosity", "value":"high"}]}
You have two parameters with name and value for each. If I will use what was written at the former answer by #stanjer the json should look like that:
{"parameter": [{"name":"object", "value":"test"}]}
In addition there is a good discussion about it here
I would not recommend to use USER:PASSWORD but use token that could be configured in Jenkins job UI. Here is a class that implements builder pattern for with/without parameters.
import java.util.Map;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.core.util.MultivaluedMapImpl;
public class JenkinsTrigger {
private String host;
private String jenkinsToken;
private String jobParams;
private MultivaluedMap<String,String> queryParams = new MultivaluedMapImpl();
private Client client = Client.create();
private WebResource webResource;
private JenkinsTrigger(JenkinsTriggerBuilder jenkinsTriggerBuilder){
this.host = jenkinsTriggerBuilder.host;
this.jenkinsToken = jenkinsTriggerBuilder.jenkinsToken;
this.jobParams = getJobParams(jenkinsTriggerBuilder.jobParams);
webResource = client.resource(this.host);
queryParams.add("token", jenkinsToken);
}
public void trigger(){
ClientResponse response = webResource.path(this.host).queryParams(queryParams)
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
.header("Content-type", "application/x-www-form-urlencoded")
.post(ClientResponse.class, jobParams);
if (response.getStatus() != 201) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.toString());
} else {
System.out.println("Job Trigger: " + host);
}
}
private String getJobParams(Map<String,String> jobParams){
StringBuilder sb = new StringBuilder();
sb.append("json={\"parameter\":[");
jobParams.keySet().forEach(param -> {
sb.append("{\"name\":\""+param+"\",");
sb.append("\"value\":\""+ jobParams.get(param) + "\"},");
});
sb.setLength(sb.length() - 1);
sb.append("]}");
System.out.println("Job Parameters:" + sb.toString());
return sb.toString();
}
public static class JenkinsTriggerBuilder {
private String host;
private String jenkinsToken;
private Map<String,String> jobParams = null;
public JenkinsTriggerBuilder(String host, String jenkinsToken){
this.host = host;
this.jenkinsToken = jenkinsToken;
}
public JenkinsTriggerBuilder jobParams(Map<String,String> jobParams){
this.jobParams = jobParams;
return this;
}
public JenkinsTrigger build(){
return new JenkinsTrigger(this);
}
}
}
And here is usage sample:
Map<String, String> params = new HashMap<>();
params.put("ENV", "DEV103");
JenkinsTrigger trigger = new JenkinsTriggerBuilder("https://JENKINS_HOST/job/JOB_NAME/buildWithParameters","JOB_TOKEN").jobParams(params).build();
trigger.trigger();
best of luck

Using XPages to get data from managed bean

I am trying to create a list of Twitter users, populating it with the number of followers for the user and their profile image. Because of Twitter's API, you need to get an access token for your application prior to using their REST API. I thought the best way to do this was via Java and a managed bean. I posted the code below, which currently works. I get the access token from Twitter, then make the API call to get the user info, which is in JSON.
My question is, what is the best way to parse the JSON and iterate over a list of user names to create a table/grid on the XPage?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
import org.apache.commons.codec.binary.Base64;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
public class TwitterUser implements Serializable {
private static final String consumerKey = "xxxx";
private static final String consumerSecret = "xxxx";
private static final String twitterApiUrl = "https://api.twitter.com";
private static final long serialVersionUID = -2084825539627902622L;
private static String accessToken;
private String twitUser;
public TwitterUser() {
this.twitUser = null;
}
public String getTwitterUser(String screenName) {
try {
this.requestTwitterUserInfo(screenName);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return twitUser;
}
public void setTwitterUser() {
twitUser = twitUser;
}
//Encodes the consumer key and secret to create the basic authorization key
private static String encodeKeys(String consumerKey, String consumerSecret) {
try {
String encodedConsumerKey = URLEncoder.encode(consumerKey, "UTF-8");
String encodedConsumerSecret = URLEncoder.encode(consumerSecret, "UTF-8");
String fullKey = encodedConsumerKey + ":" + encodedConsumerSecret;
byte[] encodedBytes = Base64.encodeBase64(fullKey.getBytes());
return new String(encodedBytes);
}
catch (UnsupportedEncodingException e) {
return new String();
}
}
//Constructs the request for requesting a bearer token and returns that token as a string
private static void requestAccessToken() throws IOException {
HttpsURLConnection connection = null;
String endPointUrl = twitterApiUrl + "/oauth2/token";
String encodedCredentials = encodeKeys(consumerKey,consumerSecret);
String key = "";
try {
URL url = new URL(endPointUrl);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Basic " + encodedCredentials);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
connection.setRequestProperty("Content-Length", "29");
connection.setUseCaches(false);
writeRequest(connection, "grant_type=client_credentials");
// Parse the JSON response into a JSON mapped object to fetch fields from.
JSONObject obj = (JSONObject)JSONValue.parse(readResponse(connection));
if (obj != null) {
String tokenType = (String)obj.get("token_type");
String token = (String)obj.get("access_token");
accessToken = ((tokenType.equals("bearer")) && (token != null)) ? token : "";
}
else {
accessToken = null;
}
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
}
private void requestTwitterUserInfo(String sn) throws IOException {
HttpsURLConnection connection = null;
if (accessToken == null) {
requestAccessToken();
}
String count = "";
try {
URL url = new URL(twitterApiUrl + "/1.1/users/show.json?screen_name=" + sn);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setRequestProperty("Host", "api.twitter.com");
connection.setRequestProperty("User-Agent", "Your Program Name");
connection.setRequestProperty("Authorization", "Bearer " + accessToken);
connection.setRequestProperty("Content-Type", "text/plain");
connection.setUseCaches(false);
}
catch (MalformedURLException e) {
throw new IOException("Invalid endpoint URL specified.", e);
}
finally {
if (connection != null) {
connection.disconnect();
}
}
twitUser = readResponse(connection);
}
//Writes a request to a connection
private static boolean writeRequest(HttpsURLConnection connection, String textBody) {
try {
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
wr.write(textBody);
wr.flush();
wr.close();
return true;
}
catch (IOException e) { return false; }
}
// Reads a response for a given connection and returns it as a string.
private static String readResponse(HttpsURLConnection connection) {
try {
StringBuilder str = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line = "";
while((line = br.readLine()) != null) {
str.append(line + System.getProperty("line.separator"));
}
return str.toString();
}
catch (IOException e) { return new String(); }
}
}
A few pointers:
Domino has the Apache HTTP client classes. They tend to be more robust than raw HTTP connections
Define a new class as a bean that contains all values that you want to see per row. You only need the getters public
add a method to your managed bean Collection getAllData()
bind that to a repeat control
you then can use repeatvar.someProperty in column values in EL
use better names than I just used

Getting a MAC address from the IP's retrieved from a ping sweep

Basically I have 2 bits of code one will do a ping sweep of a network range and then one will retrieve a MAC address from a given IP.
What I would like to do is incorporate these two pieces of code so when the ping sweep is performed it shows the MAC address in the output next to the IP addresses.
The MAC address retrieval code is as follows...
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package test118;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
public class Test118 {
public static String command;
public String ip = "192.168.0.4";
Test118() {
command = "arp -a " + ip;
}
public void viewMac() {
String process = null;
String mac[] = new String[5];
String rmac[] = new String[10];
try {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec(command);
InputStream inputstream = proc.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String line;
int i = 0;
while ((line = bufferedreader.readLine()) != null) {
mac[i] = line;
i++;
}
rmac = mac[3].split(" ");
System.out.println(rmac[2]);
} catch (Exception e) {
System.out.println("mac cant find");
}
}
public static void main(String[] args) throws Exception {
Test118 r = new Test118();
r.viewMac();
}
}
The ping sweep is as follows...
package pingstestnew;
import java.io.IOException;
import java.net.InetAddress;
public class NetworkPing {
public static void main(String[] args) throws IOException {
InetAddress localhost = InetAddress.getLocalHost();
// this code assumes IPv4 is used
byte[] ip = localhost.getAddress();
for (int i = 142; i <= 145; i++)
{
ip[3] = (byte)i;
InetAddress address = InetAddress.getByAddress(ip);
if (address.isReachable(1000))
{
System.out.println(address + " Host is reachable");
}
else if (!address.getHostAddress().equals(address.getHostName()))
{
System.out.println(address + " Hostname Resolved, Host is reachable");
}
else
{
System.out.println(address + " Host Unreachable");
}
}
}
}