In ColdFusion 9, I am hashing a string like so: hash("bob", "SHA1"), I need it to return binary instead of a hex string.
Since you know the hashed string is in hex, simply decode it with the aptly named binaryDecode() function.
hashedString = hash("bob", "SHA1");
binaryData = binaryDecode(hashedString , "Hex");
Is this the sort of thing yer after?
<cfscript>
s = "G'day World";
hash1 = hash(s, "SHA-1");
bin = binaryDecode(hash1, "hex");
hash2 = binaryEncode(bin, "hex");
writeDump(variables);
</cfscript>
Docs:
BinaryDecode()
BinaryEncode()
Related
using rapidjson, how can i encode a number to json format? i have 123.321, i want to convert it to "123.321", then save it in a file. later using json convert it back to 123.321.
i don't want to use Document which saves as like "{"tag":"value"}", i want it to be saved as just a "value", then be converted back.
i have the following code to convert number to "number":
Value v(123);
StringBuffer mybuffer;
Writer<StringBuffer> mywriter(mybuffer);
v.Accept(mywriter);
const char* myjson = mybuffer.GetString();
how to convert it back? is the following a solution? i don't want to use handler!
Reader reader;
StringStream ss(myjson);
reader.Parse(ss, handler);
thanks for the upcoming helps.
I just found the answer after digging into google:
to encode a number to json using rapidjson:
Value v(123.321);
StringBuffer mybuffer;
Writer<StringBuffer> mywriter(mybuffer);
v.Accept(mywriter);
const char* myjson = mybuffer.GetString();
now myjson has "123.321" as its value.
then to decode myjson to a number:
Document d;
d.Parse(myjson); // myjson is "123.321"
assert(d.IsNumber());
value = d.GetDouble(); // now the value is 123.321
as simple as it gets.
SerializeJSON(cfquery)
creates a JSON that looks like this:
"COLUMNS":["POINT","LOCATION"],"DATA":[["41.322365,-71.679251","Ashaway...
How do I output the JSON Data only?
ie...
[["41.322365,-71.679251","Ashaway...
I don't think there is a convenient way to do this unless you can modify the code that is serializing the query; otherwise you are going to need to use some string manipulation. However, assuming you have access to the CF code that is serializing the query, this is a little unorthodox but does work:
<!---Serialize and Deserialize the cfquery to shortcut obtaining a Structure--->
<cfset queryAsStruct = DeSerializeJSON(SerializeJSON(cfquery))>
<!---Now serialize the data key of the struct--->
<cfset dataJSON = SerializeJSON(queryAsStruct.data)>
As I said, not the the prettiest maybe...but seems to get it done. There may be a more convenient/better practice way to convert cfquery to a struct, but this one resulted in fewest lines of code for me.
edit: Just thought to explain why this works. The JSON string when being deserialized by ColdFusion is not detected as a query object anymore, just a plain struct so the "DATA" key is created and populated. THis way you can access it as a key of the structure. When cfquery is a query object, while still a "struct" type of object it has special considerations that prevent you from accessing the data key directly (to my knowledge).
Sample Query
q = QueryNew( '' );
point = [ "41.322365,-71.679251" ];
location = [ "Ashaway" ];
QueryAddColumn( q,"point",point );
QueryAddColumn( q,"location",location );
CF10+ (Using "for row in query" syntax)
data = [];
for( row in q ) {
// append array of two values
ArrayAppend( data, [ row.point, row.location ] );
}
data = SerializeJSON( data );
CF9.01
data = [];
for( row=1; row <= q.recordcount; row++ ) {
rowdata = [];
ArrayAppend( rowdata,q.point[ row ] );
ArrayAppend( rowdata,q.location[ row ] );
ArrayAppend( data,rowdata );
}
data = SerializeJSON( data );
Result:
[["41.322365,-71.679251","Ashaway"]]
I came across this same problem, I think. I'm sending a query to a browser through an ajax call and need to loop through the JSON string in order to display the info. ColdFusion's serializeJSON method outputs a 1-D array called COLUMNS and a 2-D array called DATA.
Let's assume your JSON string has come back through and ajax call into the "response" variable. So we have response.COLUMNS and response.DATA.
By using the column name and finding its index, you can pinpoint its data for a given row. From there you do whatever you need.
var point;
var location;
for(i=0; i<response.COLUMNS.length; i++){
point=response.DATA[i][response.COLUMNS.indexOf('POINT')];
location=response.DATA[i][response.COLUMNS.indexOf('LOCATION')];
}
I have a list that I'd like to convert to a Blob. I first tried converting the list to a long string, like so:
List<Contact_Deals__c> result = ...SOQL Query...
String strSobjects = null;
for(integer i=0;i<result.size();i++){
If(strSobjects == null){
strSobjects = String.valueOf(result2[i]);
}
Else{
strSobjects = strSobjects + ','+String.valueOf(result[i]);
}
}
and then converted the string into a blob, like so:
Document resultD = new Document();
resultD.Name = 'ResultCSV';
Blob myBlob = Blob.valueof(strSobjects);
resultD.body = myBlob;
This worked fine for a 2 dimensional List, but now my list has gotten deep. Real deep. Should I try writing a recursive call to convert it all into one large string (it's JSON format, so it can be parsed later) or is there a better way to convert this list to a blob?
EDIT: This will have to work in SF apex, which is a bit more limited. It seems that the only way to write to a blob is via a string (is this obvious? Blobs are new to me): https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_methods_system_blob.htm
Thanks all!
Zac
I'm trying to encrypt a string, save it in a file and then later read the string from the file and decrypt it. But when I run the code I just get "length of the data to decrypt is invalid" error :/ By debugging I manged to find out that the byte array (array^ bytes) for some reason has a length of 12 when I try to decrypt the string, and it has a length of 8 when I encrypt the string.
Here is the code to encrypt the string:
String^ EncryptS(){
String^ DecryptedS;
MD5CryptoServiceProvider^ md5Crypt = gcnew MD5CryptoServiceProvider();
UTF8Encoding^ utf8Crypt = gcnew UTF8Encoding();
TripleDESCryptoServiceProvider^ crypt = gcnew TripleDESCryptoServiceProvider();
crypt->Key = md5Crypt->ComputeHash(utf8Crypt->GetBytes("123"));
crypt->Mode = CipherMode::ECB;
crypt->Padding = PaddingMode::PKCS7;
ICryptoTransform^ transCrypt = crypt->CreateEncryptor();
DecryptedS = utf8Crypt->GetString(transCrypt->TransformFinalBlock(utf8Crypt->GetBytes(form1::passwordTextBox->Text), 0, utf8Crypt->GetBytes(form1::passwordTextBox->Text)->Length));
return DecryptedS; }
And here is the code to decrypt the string
String^ decryptS(String^ encryptedS){
String^ decryptedS;
array<Byte>^ bytes;
MD5CryptoServiceProvider^ md5Crypt = gcnew MD5CryptoServiceProvider();
UTF8Encoding^ utf8Crypt = gcnew UTF8Encoding();
UTF8Encoding^ utf8ToByte = gcnew UTF8Encoding();
TripleDESCryptoServiceProvider^ crypt = gcnew TripleDESCryptoServiceProvider();
crypt->Key = md5Crypt->ComputeHash(utf8Crypt->GetBytes("123"));
crypt->Mode = CipherMode::ECB;
crypt->Padding = PaddingMode::PKCS7;
ICryptoTransform^ transCrypt = crypt->CreateDecryptor();
bytes = utf8ToByte->GetBytes(encryptedS);
return decryptedS = utf8Crypt->GetString(transCrypt->TransformFinalBlock(bytes, 0, bytes->Length)); }
I've been trying to fix this in hours now, but with no success, help would be much appreciated :)
Sorry for my bad English.
You're trying to convert an arbitrary byte array into a string using UTF-8. That's like trying to load some random text file as if it were a JPEG, and expecting it to be a valid image.
You should only use Encoding.GetString(byte[]) when the byte array really is text encoded with that encoding.
If you want to represent "arbitrary" binary data (which compressed or encrypted data typically is) you should use base64 or perhaps hex, depending on your requirements. (Convert.ToBase64String and Convert.FromBase64String are your friends.)
How can I send an SMS in hebrew through Clickatell?
It arrives on the device as gibberish.
I couldn't find any working example so, i wrote my own:
Try this:
UnicodeEncoding unicode = new UnicodeEncoding(true, false);
return string.Concat(unicode.GetBytes(val).Select(c => string.Format("{0:x2}", c)));
Is it in unicode ? If I remember correctly they require unicode to be escaped into hexadecimal representation. This should be in their docs.
However, I found out when I did this that this is not the only issue, many phones do not support displaying unicode characters properly.
Also, sending unicode may incur a higher cost since it may be split up.
Encode your message as unicode, see this FAQ page for details.
Ran into the same issue... you need to encode to unicode and then convert to hex. The strange thing is that you need to take the last value and append it to the front in order to get it to work. I found this out by comparing the results of my code against the output of their online tool.
private string ToUnicode(string val)
{
Encoding utf8 = Encoding.UTF8;
Encoding unicode = Encoding.Unicode;
byte[] utf8Bytes = utf8.GetBytes(val);
byte[] unicodeBytes = Encoding.Convert(utf8, unicode, utf8Bytes);
var result = ByteArrayToString(unicodeBytes);
result = result.Substring(result.Length - 2, 2) + result.Substring(0, result.Length - 2);
return result;
}
public static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
I used following logic for arabic .. IT needs more testing . Language is VB.Net
If txtArabic.Text.Trim.Length > 0 Then
Dim unicodeString As String = txtArabic.Text
Dim unicode As Encoding = Encoding.Unicode
' Convert the string into a byte array.
Dim unicodeBytes As Byte() = unicode.GetBytes(unicodeString)
Dim sb As String = ToUnicode(txtArabic.Text)
End If
Here is the conversion part
Private Function ToUnicode(ByVal strVal As String)
Dim unicode As Encoding = New UnicodeEncoding(True, False)
' Encoding.Unicode
Dim utf8 As Encoding = Encoding.UTF8
Dim utf8Bytes() As Byte = unicode.GetBytes(strVal)
Dim unicodeBytes() As Byte = Encoding.Convert(utf8, unicode, utf8Bytes)
Dim result As String = ByteArrayToString(unicodeBytes)
Return result
End Function
Private Function ByteArrayToString(ByVal ba() As Byte)
Dim hex As StringBuilder = New StringBuilder(ba.Length)
For i As Integer = 0 To ba.Length - 1
If (((i - 2) Mod 4.0) = 0) Then
Else
hex.AppendFormat("{0:x00}", ba(i))
' hex.Append(ba(i))
End If
' hex.Append("-")
Next
Return hex.ToString
End Function