CryptoJS Progressive Ciphering - cryptojs

Is there any other tutorial or documentation on how to do Progressive Ciphering with CryptoJS?
Their own Documentation about it is kinda lacking of Information's
These are the Information's I found:
https://cryptojs.gitbook.io/docs/#progressive-ciphering
https://github.com/brix/crypto-js/blob/develop/docs/QuickStartGuide.wiki

Here's my solution:
export function calcSha1 (file: File): Promise<string> {
const reader = new FileReader()
const promise = new Promise<string>(
(resolve) => {
reader.onloadend = (evt: ProgressEvent<FileReader>) => {
const sha1Hash = CryptoJS.algo.SHA1.create()
let currentPosition = 0
const chunkSize = 10 * 1024 * 1024 // 10MB
while (currentPosition < file.size) {
let endPosition = currentPosition + chunkSize
if (endPosition > file.size) {
endPosition = file.size
}
const blob = evt.target?.result?.slice(currentPosition, endPosition)
const wordArray = CryptoJS.lib.WordArray.create(blob)
sha1Hash.update(wordArray)
currentPosition += chunkSize
}
const result = sha1Hash.finalize()
resolve(result.toString())
}
}
)
reader.readAsArrayBuffer(file)
return promise
}

Related

open62541 client fails when calling method with custom datatype input argument

I'm using open62541 to connect to an OPC/UA server and I'm trying to call methods that a certain object on that server provides. Those methods have custom types as input arguments; for example, the following method takes a structure of three booleans:
<opc:Method SymbolicName="SetStatusMethodType" ModellingRule="Mandatory">
<opc:InputArguments>
<opc:Argument Name="Status" DataType="VisionStatusDataType" ValueRank="Scalar"/>
</opc:InputArguments>
<opc:OutputArguments />
</opc:Method>
Here, VisionStatusDataType is the following structure:
<opc:DataType SymbolicName="VisionStatusDataType" BaseType="ua:Structure">
<opc:ClassName>VisionStatus</opc:ClassName>
<opc:Fields>
<opc:Field Name="Camera" DataType="ua:Boolean" ValueRank="Scalar"/>
<opc:Field Name="StrobeController" DataType="ua:Boolean" ValueRank="Scalar"/>
<opc:Field Name="Server" DataType="ua:Boolean" ValueRank="Scalar"/>
</opc:Fields>
</opc:DataType>
Now, when calling the method, I'm encoding the data into an UA_ExtensionObject, and wrap that one as an UA_Variant to provide it to UA_Client_call. The encoding looks like this:
void encode(const QVariantList& vecqVar, size_t& nIdx, const DataType& dt, std::back_insert_iterator<std::vector<UAptr<UA_ByteString>>> itOut)
{
if (dt.isSimple())
{
auto&& qVar = vecqVar.at(nIdx++);
auto&& uaVar = convertToUaVar(qVar, dt.uaType());
auto pOutBuf = create<UA_ByteString>();
auto nStatus = UA_encodeBinary(uaVar.data, dt.uaType(), pOutBuf.get());
statusCheck(nStatus);
itOut = std::move(pOutBuf);
}
else
{
for (auto&& dtMember : dt.members())
encode(vecqVar, nIdx, dtMember, itOut);
}
}
UA_Variant ToUAVariant(const QVariant& qVar, const DataType& dt)
{
if (dt.isSimple())
return convertToUaVar(qVar, dt.uaType());
else
{
std::vector<UAptr<UA_ByteString>> vecByteStr;
auto&& qVarList = qVar.toList();
size_t nIdx = 0UL;
encode(qVarList, nIdx, dt, std::back_inserter(vecByteStr));
auto pExtObj = UA_ExtensionObject_new();
pExtObj->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
auto nSizeAll = std::accumulate(vecByteStr.cbegin(), vecByteStr.cend(), 0ULL, [](size_t nSize, const UAptr<UA_ByteString>& pByteStr) {
return nSize + pByteStr->length;
});
auto&& uaEncoded = pExtObj->content.encoded;
uaEncoded.typeId = dt.uaType()->typeId;
uaEncoded.body.length = nSizeAll;
auto pData = uaEncoded.body.data = new UA_Byte[nSizeAll];
nIdx = 0UL;
for (auto&& pByteStr : vecByteStr)
{
memcpy_s(pData + nIdx, nSizeAll - nIdx, pByteStr->data, pByteStr->length);
nIdx += pByteStr->length;
}
UA_Variant uaVar;
UA_Variant_init(&uaVar);
UA_Variant_setScalar(&uaVar, pExtObj, &UA_TYPES[UA_TYPES_EXTENSIONOBJECT]);
return uaVar;
}
}
The DataType class is a wrapper for the UA_DataType structure; the original open62541 type can be accessed via DataType::uaType().
Now, once a have the variant (containing the extension object), the method call looks like this:
auto uavarInput = ToUAVariant(qvarArg, dtInput);
UA_Variant* pvarOut;
size_t nOutSize = 0UL;
auto nStatus = UA_Client_call(m_pClient, objNode.nodeId(), m_uaNodeId, 1UL, &uavarInput, &nOutSize, &pvarOut);
The status is 2158690304, i.e. BadInvalidArgument according to UA_StatusCode_name.
Is there really something wrong with the method argument? Are we supposed to send ExtensionObjects, or what data type should the variant contain?
Is it possible that the server itself (created using the .NET OPC/UA stack) is not configured correctly?
N.B., the types here are custom types; that is, the encoding is done manually (see above) by storing the byte representation of all members next to each other in an UA_ByteString - just the opposite of what I'm doing when reading variables or output arguments, which works just fine.
The problem is the typeId of the encoded object. For the server in order to understand the received data, it needs to know the NodeId of the encoding, not the actual NodeId of the type itself. That encoding can be found by following the HasEncoding reference (named "Default Binary") of the type:
auto pRequest = create<UA_BrowseRequest>();
auto pDescr = pRequest->nodesToBrowse = UA_BrowseDescription_new();
pRequest->nodesToBrowseSize = 1UL;
pDescr->nodeId = m_uaNodeId;
pDescr->resultMask = UA_BROWSERESULTMASK_ALL;
pDescr->browseDirection = UA_BROWSEDIRECTION_BOTH;
pDescr->referenceTypeId = UA_NODEID_NUMERIC(0, UA_NS0ID_HASENCODING);
auto response = UA_Client_Service_browse(m_pClient, *pRequest);
for (auto k = 0UL; k < response.resultsSize; ++k)
{
auto browseRes = response.results[k];
for (auto n = 0UL; n < browseRes.referencesSize; ++n)
{
auto browseRef = browseRes.references[n];
if (ToQString(browseRef.browseName.name).contains("Binary"))
{
m_nodeBinaryEnc = browseRef.nodeId.nodeId;
break;
}
}
}
Once you have that NodeId, you pass it to UA_ExtensionObject::content::encoded::typeId:
auto pExtObj = UA_ExtensionObject_new();
pExtObj->encoding = UA_EXTENSIONOBJECT_ENCODED_BYTESTRING;
auto nSizeAll = std::accumulate(vecByteStr.cbegin(), vecByteStr.cend(), 0ULL, [](size_t nSize, const UAptr<UA_ByteString>& pByteStr) {
return nSize + pByteStr->length;
});
auto&& uaEncoded = pExtObj->content.encoded;
uaEncoded.typeId = dt.encoding();
uaEncoded.body.length = nSizeAll;
auto pData = uaEncoded.body.data = new UA_Byte[nSizeAll];
nIdx = 0UL;
for (auto&& pByteStr : vecByteStr)
{
memcpy_s(pData + nIdx, nSizeAll - nIdx, pByteStr->data, pByteStr->length);
nIdx += pByteStr->length;
}

How to convert TRON address to different format

I have an issue while deploying contract in TRON network, where I am required to specify address in format that starts with 4.. or when I receive transactions history (here the api respond with 4.. addresses as well).
Therefore I have a question:
How to convert TRON address started with TLAXtqju7GKyqoP... to 419b6e043089843624c36f1e3b1e8572d189cbe170 and vice versa?
How to convert TRON address started with TLAXtqju7GKyqoP... to 419b6e043089843624c36f1e3b1e8572d189cbe170 and vice versa?
const TronWeb = require('tronweb');
const tronWeb = new TronWeb(
'http://127.0.0.1:9090',
'http://127.0.0.1:9090',
'http://127.0.0.1:9090',
'd6fbbf6eecffdb32172e391363a401f89617acb9dd01897b9fa180830a8a46b2',
);
Once you have the tronWeb object, then you can convert the addresses vice-versa by using tronWeb's address utility
For Example:
const addressInHexFormat = '414450cf8c8b6a8229b7f628e36b3a658e84441b6f';
const addressInBase58 = tronWeb.address.fromHex(addressInHexFormat);
> addressInBase58 = 'TGCRkw1Vq759FBCrwxkZGgqZbRX1WkBHSu'
const addressInHex = tronWeb.address.toHex(addressInBase58);
> addressInHex = '414450cf8c8b6a8229b7f628e36b3a658e84441b6f'
Note
The above tronWeb object is created by using Tron's Quickstart Docker container. In this way the addresses can be converted vice-versa.
You just should decode your base58Address from Base58. In result you will obtain addresschecksum, so you should remove last 4 bytes from result and obtain desired address.
address = 41||sha3[12,32): 415a523b449890854c8fc460ab602df9f31fe4293f
sha256_0 = sha256(address): 06672d677b33045c16d53dbfb1abda1902125cb3a7519dc2a6c202e3d38d3322
sha256_1 = sha256(sha256_0): 9b07d5619882ac91dbe59910499b6948eb3019fafc4f5d05d9ed589bb932a1b4
checkSum = sha256_1[0, 4): 9b07d561
addchecksum = address || checkSum: 415a523b449890854c8fc460ab602df9f31fe4293f9b07d561
base58Address = Base58(addchecksum): TJCnKsPa7y5okkXvQAidZBzqx3QyQ6sxMW
The address format is well explained in the relevant TRON documentation.
In Java code (based on wallet-cli):
public String tronHex(String base58) {
byte[] decoded = decode58(base58);
String hexString = decoded == null ? "" : org.spongycastle.util.encoders.Hex.toHexString(decoded);
return hexString;
}
private byte[] decode58(String input) {
byte[] decodeCheck = Base58.decode(input);
if (decodeCheck.length <= 4) {
return null;
}
byte[] decodeData = new byte[decodeCheck.length - 4];
System.arraycopy(decodeCheck, 0, decodeData, 0, decodeData.length);
byte[] hash0 = Sha256Hash.hash(decodeData);
byte[] hash1 = Sha256Hash.hash(hash0);
if (hash1[0] == decodeCheck[decodeData.length] &&
hash1[1] == decodeCheck[decodeData.length + 1] &&
hash1[2] == decodeCheck[decodeData.length + 2] &&
hash1[3] == decodeCheck[decodeData.length + 3]) {
return decodeData;
}
return null;
}
And the other way around:
public String hexStringTobBase58(String hexString) {
hexString = adjustHex(hexString);
byte[] decodedHex = hexString == null? new byte[0] : org.spongycastle.util.encoders.Hex.decode(hexString);
String base58 = encode58(decodedHex);
return base58;
}
private String adjustHex(String hexString) {
if (hexString.startsWith("0x")) {
hexString = "41" + hexString.substring(2);
}
if (hexString.length() % 2 == 1) {
hexString = "0" + hexString;
}
return hexString;
}
private String encode58(byte[] input) {
byte[] hash0 = Sha256Hash.hash(input);
byte[] hash1 = Sha256Hash.hash(hash0);
byte[] inputCheck = new byte[input.length + 4];
System.arraycopy(input, 0, inputCheck, 0, input.length);
System.arraycopy(hash1, 0, inputCheck, input.length, 4);
return Base58.encode(inputCheck);
}
Find class Base58 here, class Sha256Hash here and the required dependency to Spongy Castle here.
C# example:
public static string GetHex(this String str)
{
var sb = new StringBuilder();
var bytes = Base58.Bitcoin.Decode(str); // nuget https://www.nuget.org/packages/SimpleBase/
for (int i = 0; i < bytes.Length - 4; i++)
{
var t = bytes[i];
sb.Append(t.ToString("X2"));
}
return sb.ToString();
}

UnsafeMutablePointer in AURenderCallback

I can't understand, how I should use UnsafeMutablePointer in Swift 3. Especially in AURenderCallback.
I try below code:
import Foundation
import AudioToolbox
let sineFrequency = 880.0
// MARK: User data struct
struct SineWavePlayer {
var outputUnit: AudioUnit? = nil
var startingFrameCount: Double = 0
}
// MARK: Callback function
let SineWaveRenderProc: AURenderCallback = {(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData) -> OSStatus in
var player = UnsafeMutablePointer<SineWavePlayer>(inRefCon)
var j = player.pointee.startingFrameCount
let cycleLength = 44100 / sineFrequency
for frame in 0..<inNumberFrames {
var buffers = UnsafeMutableAudioBufferListPointer(ioData)
UnsafeMutablePointer<Float32>(buffers[0].mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
UnsafeMutablePointer<Float32>(buffers[1].mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
// Or iterate through array:
// for buffer in buffers {
// UnsafeMutablePointer<Float32>(buffer.mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
// }
j++
if j > cycleLength {
j -= cycleLength
}
}
player.pointee.startingFrameCount = j
return noErr
}
// MARK: Utility function
func CheckError(_ error: OSStatus, operation: String) {
guard error != noErr else {
return
}
var result: String = ""
var char = Int(error.bigEndian)
for _ in 0..<4 {
guard isprint(Int32(char&255)) == 1 else {
result = "\(error)"
break
}
result.append(String(describing: UnicodeScalar(char&255)))
char = char/256
}
print("Error: \(operation) (\(result))")
exit(1)
}
func CreateAndConnectOutputUnit(_ player: inout SineWavePlayer) {
// Generate a description that matches the output device (speakers)
var outputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)
let comp = AudioComponentFindNext(nil, &outputcd)
if comp == nil {
print("Can't get output unit")
exit(-1)
}
CheckError(AudioComponentInstanceNew(comp!, &player.outputUnit),
operation: "Couldn't open component for outputUnit")
// Register the render callback
var input = AURenderCallbackStruct(inputProc: SineWaveRenderProc, inputProcRefCon: &player)
CheckError(AudioUnitSetProperty(player.outputUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, UInt32(MemoryLayout<AURenderCallbackStruct>.size)),
operation: "AudioUnitSetProperty failed")
// Initialize the unit
CheckError(AudioUnitInitialize(player.outputUnit!),
operation: "Couldn't initialize output unit")
}
func main() {
var player = SineWavePlayer()
// Set up output unit and callback
CreateAndConnectOutputUnit(&player)
// Start playing
CheckError(AudioOutputUnitStart(player.outputUnit!),
operation: "Couldn't start output unit")
// Play for 5 seconds
sleep(5)
// Clean up
AudioOutputUnitStop(player.outputUnit!)
AudioUnitUninitialize(player.outputUnit!)
AudioComponentInstanceDispose(player.outputUnit!)
}
main()
But this line of code
var player = UnsafeMutablePointer<SineWavePlayer>(inRefCon)
is not working. How to translate this line to Swift 3?
Please, help me.
In Swift 3, initializers cannot be used to convert pointer types. In your case, the type of inRefCon is UnsafeMutableRawPointer, so you need to use assumingMemoryBound(to:) method.
And one more, the address of player passed to the callback needs to be stable all while the sound is playing, addresses taken from inout arguments (specified by & prefix) does not fulfil this requirement.
The two things above fixed, your code would be something like this:
import Foundation
import AudioToolbox
let sineFrequency = 880.0
// MARK: User data struct
struct SineWavePlayer {
var outputUnit: AudioUnit? = nil
var startingFrameCount: Double = 0
}
// MARK: Callback function
let SineWaveRenderProc: AURenderCallback = {(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData) -> OSStatus in
var player = inRefCon.assumingMemoryBound(to: SineWavePlayer.self)
var j = player.pointee.startingFrameCount
let cycleLength = 44100 / sineFrequency
for frame in 0..<inNumberFrames {
var buffers = UnsafeMutableAudioBufferListPointer(ioData)
buffers?[0].mData?.assumingMemoryBound(to: Float32.self)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
buffers?[1].mData?.assumingMemoryBound(to: Float32.self)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
j += 1
if j > cycleLength {
j -= cycleLength
}
}
player.pointee.startingFrameCount = j
return noErr
}
// MARK: Utility function
func CheckError(_ error: OSStatus, operation: String) {
guard error != noErr else {
return
}
var result: String = ""
var char = Int(error.bigEndian)
for _ in 0..<4 {
guard isprint(Int32(char&255)) == 1 else {
result = "\(error)"
break
}
result.append(String(describing: UnicodeScalar(char&255)))
char = char/256
}
print("Error: \(operation) (\(result))")
exit(1)
}
func CreateAndConnectOutputUnit(_ playerPtr: UnsafeMutablePointer<SineWavePlayer>) {
// Generate a description that matches the output device (speakers)
var outputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)
let comp = AudioComponentFindNext(nil, &outputcd)
if comp == nil {
print("Can't get output unit")
exit(-1)
}
CheckError(AudioComponentInstanceNew(comp!, &playerPtr.pointee.outputUnit),
operation: "Couldn't open component for outputUnit")
// Register the render callback
var input = AURenderCallbackStruct(inputProc: SineWaveRenderProc, inputProcRefCon: playerPtr)
CheckError(AudioUnitSetProperty(playerPtr.pointee.outputUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, UInt32(MemoryLayout<AURenderCallbackStruct>.size)),
operation: "AudioUnitSetProperty failed")
// Initialize the unit
CheckError(AudioUnitInitialize(playerPtr.pointee.outputUnit!),
operation: "Couldn't initialize output unit")
}
func main() {
let playerPtr = UnsafeMutablePointer<SineWavePlayer>.allocate(capacity: 1)
defer {playerPtr.deallocate(capacity: 1)}
playerPtr.initialize(to: SineWavePlayer())
defer {playerPtr.deinitialize()}
// Set up output unit and callback
CreateAndConnectOutputUnit(playerPtr)
// Start playing
CheckError(AudioOutputUnitStart(playerPtr.pointee.outputUnit!),
operation: "Couldn't start output unit")
// Play for 5 seconds
sleep(5)
// Clean up
AudioOutputUnitStop(playerPtr.pointee.outputUnit!)
AudioUnitUninitialize(playerPtr.pointee.outputUnit!)
AudioComponentInstanceDispose(playerPtr.pointee.outputUnit!)
}

What arguments needed to exec MSIscsiInitiator_TargetClass:Login?

I trying to connect to iSCSI target via WMI (class WMI\MSIscsiInitiator_TargetClass, which is distributed with Microsoft software initiator), but always get a generic failure (80041001). Here is my code:
var mgmts = GetObject("winmgmts:\\\\.\\root\\WMI");
function login (path, login, passwd) {
var portal = mgmts.Get("MSIscsiInitiator_Portal").SpawnInstance_(),
target = mgmts.Get("MSIscsiInitiator_TargetClass"
).SpawnInstance_(),
args = target.Methods_("Login").InParameters.SpawnInstance_(),
options = mgmts.Get("MSIscsiInitiator_TargetLoginOptions"
).SpawnInstance_();
target.TargetName = path;
target.Put_();
with ( portal ) {
Address = '10.0.0.100';
Port = 3260;
Index = 1;
SymbolicName = 'default';
Put_();
};
args.TargetPortal = portal;
args.IsPersistent = false;
with ( options ) {
HeaderDigest = 1; // CRC32C
DataDigest = 1; // CRC32C
AuthType = 1; // CHAP
Username = login.split('');
Password = passwd.split('');
InformationSpecified = 0xE3; // 227 = 11100011 !! 0x67 = 1100111
if ( ! ( login && passwd ) ) {
AuthType = 0;
// 0000011;
InformationSpecified = InformationSpecified ^ 0x03;
};
DefaultTime2Retain = 0;
DefaultTime2Wait = 0;
LoginFlags = 10; // 1010
MaximumConnections = 0;
Version = 0;
};
args.LoginOptions = options;
return target.ExecMethod_("Login", args); // <- this line fails
}
using like this:
login('iqn.2004-04.com.qnap:ts-859proplus:iscsi.test.c620aa',
'test', 'verylongpassword');
What's wrong?
P.S: the same task with iscsicli.exe
var portal_parameter = '10.0.0.100 3260';
function login (path, login, passwd) {
shell.run('iscsicli AddTargetPortal' +
portal_parameter +
' * * * * * * * * * * * *',
0, true);
var auth = '1'; // CHAP
if ( ! ( login && passwd ) ) {
auth = '0'; // NO
login = '*';
passwd = '*';
};
shell.run('iscsicli LoginTarget ' +
path + ' T ' + // PNP
portal_parameter +
' * * * * 1 1 * * * ' +
login + ' ' + passwd + ' ' + auth + ' * 0',
0, true);
}
works (without result check), but I need WMI.

Silverlight 4 image upload problem

I am using Silverlight4 with java webervices in jsp page. I want to save an image to the server so trying to do this with java webservice. I am using below lines of code but output is damaged. I dont understand why. Please help me. This is really important for me. When i try to open 3mb jpeg file contains "Windows Photo Viewer cant open this picture because file appears to be damaged, corrupted or is too large."
Client Side COde
WriteableBitmap wb = new WriteableBitmap(bitmapImage);
byte[] bb = ToByteArray(wb);
public byte[] ToByteArray(WriteableBitmap bmp)
{
int[] p = bmp.Pixels;
int len = p.Length * 4;
byte[] result = new byte[len]; // ARGB
Buffer.BlockCopy(p, 0, result, 0, len);
return result;
}
WebService Code
#WebMethod(operationName = "saveImage")
public Boolean saveImage(#WebParam(name = "img")
byte[] img, #WebParam(name = "path")
String path) {
try{
FileOutputStream fos = new FileOutputStream("C:\\Users\\TheIntersect\\Desktop\\sharp_serializer_dll\\saved.jpg");
fos.write(img);
fos.close();
return true;
}
catch(Exception e){
return false;
}
}
I found my answer on forums.silverlight.net
It is very interesting when i try to call ReadFully(Stream) just after the Stream definition it works but when i call 10 lines of code later it returns all 0.
FUnction
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
Fail Code
using (Stream str = opd.File.OpenRead())
{
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(str);
image.Tag = bitmapImage.UriSource.ToString();
image.Source = bitmapImage;
image.Width = width;
image.Height = height;
image.Stretch = Stretch.Uniform;
container.Child = image;
rtb.Selection.Insert(container);
ServiceReference1.webWordWebServiceClient s = new ServiceReference1.webWordWebServiceClient();
byte[] bb = ReadFully(str);
s.saveImageCompleted += new EventHandler<ServiceReference1.saveImageCompletedEventArgs>(s_saveImageCompleted);
s.saveImageAsync(bb, "gungorrrr");
}
Successfull Code
using (Stream str = opd.File.OpenRead())
{
byte[] bb = ReadFully(str);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(str);
image.Tag = bitmapImage.UriSource.ToString();
image.Source = bitmapImage;
image.Width = width;
image.Height = height;
image.Stretch = Stretch.Uniform;
container.Child = image;
rtb.Selection.Insert(container);
ServiceReference1.webWordWebServiceClient s = new ServiceReference1.webWordWebServiceClient();
(bitmapImage);
s.saveImageCompleted += new EventHandler<ServiceReference1.saveImageCompletedEventArgs>(s_saveImageCompleted);
s.saveImageAsync(bb, "gungorrrr");
}
Link: http://forums.silverlight.net/forums/p/234126/576070.aspx#576070