I've already tried the another solutions from SO, such as:
String password ="pwd";
WinCrypt.DATA_BLOB pDataIn = new WinCrypt.DATA_BLOB(password.getBytes(Charset.forName("UTF-16LE")));
WinCrypt.DATA_BLOB pDataEncrypted = new WinCrypt.DATA_BLOB();
System.out.println(Crypt32.INSTANCE.CryptProtectData(pDataIn, "psw",
null, null, null, WinCrypt.CRYPTPROTECT_UI_FORBIDDEN, pDataEncrypted));
StringBuffer epwsb = new StringBuffer();
byte[] pwdBytes= new byte [pDataEncrypted.cbData];
pwdBytes=pDataEncrypted.getData();
Formatter formatter = new Formatter(epwsb);
for ( final byte b : pwdBytes ) {
formatter.format("%02X", b);
}
System.out.println("password 51:b:"+ epwsb.toString());
or
Crypt32Util.cryptProtectData("12345".getBytes("UTF-16LE"), null, 0, "psw", null);
But all of them give different results for every time I run them, and they do not match the real password, that was saved by MSTSC or generated by RDP Password Hasher utility.
Does anyone know the solution, or CLI-utility that can encrypt password?
Here's my working solution (you need JNA platform, to get this working):
private static String ToHexString(byte[] bytes) {
StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
for (byte b : bytes) {
formatter.format("%02x", b);
}
formatter.close();
return sb.toString();
}
private String cryptRdpPassword(String pass) {
try {
return ToHexString(Crypt32Util.cryptProtectData(pass.getBytes("UTF-16LE"), null, 0, "psw", null));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "ERROR";
}
}
Related
in my current android app I need a key which is special to my App and hackers can't reach it , and I can verify that in each API call , is there any app specific key or way of creating one that is safe for using?
You cannot prevent hackers completely as there's always a way they exploit your but you can use this prevent calls this way so authorized user action will be more secure
Create hash with each login of user, and save that in database and in shared preference in the application, for every further call send hash to API and check against the database to check if user is authorized to call the API
Here's an example how you can create hash
Put this into your "Utils" class.
public static String getSha256Hash(String password) {
try {
MessageDigest digest = null;
try {
digest = MessageDigest.getInstance("SHA-256");
} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}
digest.reset();
return bin2hex(digest.digest(password.getBytes()));
} catch (Exception ignored) {
return null;
}
}
private static String bin2hex(byte[] data) {
StringBuilder hex = new StringBuilder(data.length * 2);
for (byte b : data)
hex.append(String.format("%02x", b & 0xFF));
return hex.toString();
}
public static String getCurrentTimeStamp(){
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()); // Find todays date
return currentDateTime;
} catch (Exception e) {
e.printStackTrace();
return null;
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(MAX_LENGTH);
char tempChar;
for (int i = 0; i < randomLength; i++){
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
Example of use:
String token = Utils.getSha256Hash(getCurrentTimeStamp()+username+random())
I try to send valid request to REST API which uses oAuth. I keep receiving respond : "Invalid signature"
Here's steps I do to generate request:
Build Request:
public String buildRequest() {
ArrayList<String> params = new ArrayList<>(generateParams());
params.add("oauth_signature=" + sign(buildSignatureBaseString()));
Collections.sort(params);
return join(params.toArray(template), "&");
}
Creating Signature Base String:
public String buildSignatureBaseString(){
StringBuilder builder = new StringBuilder();
builder.append(METHOD);
builder.append("&");
builder.append(percentEncoding(URL));
builder.append("&");
builder.append(percentEncoding(join(generateParams().toArray(template), "&")));
return builder.toString();
}
Generating parameters sorted in natural order:
private ArrayList<String> generateParams() {
ArrayList<String> params = new ArrayList<>();
params.add("oauth_consumer_key=" + "...");
params.add("oauth_signature_method=HMAC-SHA1");
params.add("oauth_timestamp=" + Long.valueOf(System.currentTimeMillis() / 1000).toString());
params.add("oauth_nonce=" + getNonce());
params.add("oauth_version=1.0");
params.add("format=json");
params.add("method=foods.search");
params.add("search_expression=pasta");
Collections.sort(params);
return params;
}
Creating Signature Base String:
public String buildSignatureBaseString(){
StringBuilder builder = new StringBuilder();
builder.append(METHOD);
builder.append("&");
builder.append(percentEncoding(URL));
builder.append("&");
builder.append(percentEncoding(join(generateParams().toArray(template), "&")));
return builder.toString();
}
Generating signature with HMAC-SHA1:
public String sign(String sbs) {
String key = <SharedSecret> + "&";
SecretKeySpec sk = new SecretKeySpec(key.getBytes(Charset.forName("UTF-8")), ALGORITHM);
try {
Mac m = Mac.getInstance(ALGORITHM);
m.init(sk);
byte[] hmacEncoded = m.doFinal(sbs.getBytes(Charset.forName("UTF-8")));
byte[] base64Encoded = Base64.encode(hmacEncoded, Base64.DEFAULT);
return Uri.encode(new String(base64Encoded, Charset.forName("UTF-8")));
} catch (java.security.NoSuchAlgorithmException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
} catch (java.security.InvalidKeyException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
}
}
Could someone more experienced in this matter help?
Regards
The param entries from generateParams all are in the form tag=value. Your sign method seems only to return a value.
And: Are you sure the sign method does not throw? I this case you would return null, which you should check in the caller method and only add it to the params if it is not null
I have simply code in PHP like that
$hash = md5("testtesttest", TRUE);
echo $hash.'<br>';
$hash = md5($hash . "test", TRUE);
echo $hash.'<br>';
With 2 line fisrt in java, it's working good with my code
public static void main(String[] args) {
// String str = new String(md5x16("test"));
byte[] input = md5x16("testtesttest");
String t = new String(input);
System.out.println(t);
}
public static byte[] md5x16(String text) {
try {
MessageDigest digester = MessageDigest.getInstance("MD5");
digester.update(text.getBytes());
byte[] md5Bytes = digester.digest();
return md5Bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
But in line 3 and 4 in PHP, I can't do the same in Java
If I parse to String and add a "test" to it, I will get another result with PHP
Iraklis should be right. md5() gives you a hex-encoded output string by default. You only get the unencoded bytes like in Java by passing in TRUE for the optional $raw_output argument.
the lengths range from 29 to 32
hexString.append( Integer.toHexString(0xFF & message[ i ] ) );
function makeBrokenMD5($s) {
$hash= md5($s, TRUE);
$bytes= preg_split('//', $hash, -1, PREG_SPLIT_NO_EMPTY);
$broken= '';
foreach ($bytes as $byte)
$broken.= dechex(ord($byte));
return $broken;
}`
I have a text file which contains the "Captured Network Packets' Headers" as hexadecimal values like this...
FC-C8-97-62-88-5F-74-DE-2B-C8-C7-E5-08-00-45-00-00-28-4E-C4-40-00-80-06-BD-65-C0-A8-01-03-AD-C2-7F-38-C9-96-01-BB-F8-01-7F-5F-B6-8A-15-22-50-10-40-42-72-8C-00-00.
I need to convert them to decimal values... I did little as here..
InputStream input = new FileInputStream("data.txt");
OutputStream output = new FileOutputStream ("converteddata.txt");
int data = input.read();
while (data != -1)
{
char ch = (char) data;
output.write(ch);
data=input.read();
}
input.close();
output.close();
Now, my problem is... how to get each hexadecimal string which would have '2' characters..? (such as "AD" or 5F etc. in order to convert them in to decimal values).
I know that C++ has a function "fgetc()" No..? I need similar solution. Anybody can suggest a good way..? (Sorry, I'm a beginner for Java but know c++ much better)
Thanks in advance.
Try Long.parseLong("<hex string>", 16); to convert a hexadecimal string to a long value.
Try this:
String strHex = "FC-C8-97-62-88-5F-74-DE-2B-C8-C7-E5-08-00-45-00-00-28-4E-C4-40-00-80-06-BD-65-C0-A8-01-03-AD-C2-7F-38-C9-96-01-BB-F8-01-7F-5F-B6-8A-15-22-50-10-40-42-72-8C-00-00";
String[] hexParts = strHex.split("-");
for (String myStr : hexParts) {
// System.out.println(toHex(myStr));
System.out.println(toDecimal(myStr));
}
// getting For Decimal values from Hex string
public int toDecimal(String str){
return Integer.parseInt(str.trim(), 16 );
}
// getting For Hex values
public String toHex(String arg) {
return String.format("%x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
}
Here is a sample code. Please optimize for real time uses.
public static void main(String[] args) throws IOException {
OutputStream output = new FileOutputStream ("converteddata.txt");
BufferedReader br = new BufferedReader(new FileReader(new File("data.txt")));
String r = null;
while((r=br.readLine())!=null) {
String [] str = r.split("-");
for (String string : str) {
Long l = Long.parseLong(string.trim(), 16);
output.write(String.valueOf(l).getBytes());
output.write("\n".getBytes());
}
}
br.close();
output.close();
}
My question is, I guess, quite simple :
How to convert a Byte to alpha-numeric char array (String) in java ?
I tried this but it gives me back an error on netbeans :
byte[] b = "test".getBytes("ASCII");
String test = new String(b,"ASCII");
UPDATE :
I am actually using this code :
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
String bla = new String(md.digest(b), "ASCII");
But once I try to use for other stuff which requires String with ASCII, I receive the following errors like "This is not ASCII".
I don't really understand, actually.
When I try to print it I got something weird like "2Q�h/�k�����"
Thank you in advance for your help.
You're close :
public static void main(String[] args) throws java.io.UnsupportedEncodingException { //you should throw or catch this exception
byte[] b = "test".getBytes("ASCII"); // And you must declare a byte array
String test = new String(b,"ASCII");
System.out.println(test); // Will output "test"
}
After your edits I think you want to generate a SHA-256 hash of a given String.
try {
byte[] b = "test".getBytes("ASCII");
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashBytes = md.digest(b);
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hashBytes.length; i++) {
hexString.append(Integer.toHexString(0xFF & hashBytes[i]));
}
System.out.println(hexString);
} catch (Exception e) {
e.printStackTrace();
}