Converting a byte[] back to key problem

I CAN create a key and convert the key to a byte array, then convert the array to a string(base 64):
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key = generator.generateKey();
byte[] keyBytes = key.getEncoded;
BASE64Encoder encoder = new BASE64Encoder();
String randomKey = encoder.encode(keyBytes);
and I CAN save that string to a database, forget about it, then sometime later reload it and convert it to a byte array again:
String loadedKey = "WhAt3Ver-It-I5" //from DB
BASE64Decoder decoder = new BASE64Decoder();
byte[] loadedKeyBytes = decoder.decodeBuffer(loadedKey);
what I CAN'T do is convert the loadedKeyBytes back into the key of the same type as it was originally, enabling me to decrypt whatever that key originally encrypted.
Does anyone know.
I know I need to convert it to a KeySpec, I presume as:
DESKeySpec keySpec = new DESKeySpec(loadedKeyBytes);
this compiles correctly.... but how do i then recreate the key so i can use it for decryption.
Once i've finished this test program I should be able to port it to my application.
Many thanks in advance guys!
Cheers!
Relisys
================ CODE FOLLOWS ======================
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import com.sun.crypto.provider.SunJCE;
import sun.misc.*;
public class SecPrescrip {
public static void main(String[] args) throws Exception {
// Create Key.
Key key;
KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key = generator.generateKey();
// Get a cipher object
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
// Encrypt the input string:
cipher.init(Cipher.ENCRYPT_MODE, key);
String input = "Medicare Secure Prescription: 30 Tamazopan 200mg tablets. Dosage: 1 to be taken every 4 hours";
System.out.println("Stage 1: ENCRYPT PRESCRIPTION WITH A RANDOM DES KEY");
System.out.println("===================================================");
System.out.println(" - Input Plain Text: "+input);
System.out.println("");
byte[] stringBytes = input.getBytes("UTF8");
byte[] raw = cipher.doFinal(stringBytes);
BASE64Encoder encoder = new BASE64Encoder();
String ciphertext1 = encoder.encode(raw);
System.out.println(" - Cipher Text: "+ciphertext1);
System.out.println("");
byte[] keybytes = key.getEncoded();
String randomkey = encoder.encode(keybytes);
System.out.println(" - Random Prescription Key: "+randomkey);
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 2: ENCRYPT RANDOM KEY WITH PATIENT MEDICARE KEY");
System.out.println("=====================================================");
BASE64Decoder decoder = new BASE64Decoder();
String passphrase = "ABCD1234efghIJ56"; //Patient Medicare Key
System.out.println(" - Patient Medicare Key: "+passphrase);
System.out.println("");
System.out.println(" - Input Plain Text: "+randomkey);
String algorithm = "PBEWithMD5AndDES";
byte[] salt = new byte[8];
int iteration = 20;
KeySpec ks = new PBEKeySpec(passphrase.toCharArray());
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
SecretKey key2 = skf.generateSecret(ks);
byte[] input2 = decoder.decodeBuffer(randomkey);
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(passphrase.getBytes());
md.update(input2);
byte[] digest = md.digest();
System.arraycopy(digest, 0, salt, 0, 8);
AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iteration);
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key2, aps);
byte[] outputFinalKey = cipher.doFinal(input2);
String ciphertext2 = encoder.encode(outputFinalKey);
String saltString = encoder.encode(salt);
String encryptedCiphertext = saltString+ciphertext2;
System.out.println("");
System.out.println(" - Cipher Text (Final Prescription Key): "+ciphertext2);
System.out.println("");
System.out.println(" - Salt: "+saltString);
System.out.println("");
System.out.println(" - Full Encrypted Output: "+encryptedCiphertext);
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 3: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
System.out.println("============================================================");
//NOT CHANGED String passphrase = "ABCD1234efghIJ56";
System.out.println(" - Patient Medicare Key: "+passphrase);
System.out.println("");
System.out.println(" - Input Plain Text: "+ciphertext2);
algorithm = "PBEWithMD5AndDES";
salt = new byte[8];
iteration = 20;
ks = new PBEKeySpec(passphrase.toCharArray());
skf = SecretKeyFactory.getInstance(algorithm);
SecretKey key3 = skf.generateSecret(ks);
//Load in the input bytes as if they had been loaded from an sql database or the like
String saltIn = encryptedCiphertext.substring(0,12);
String ciphertext3 = encryptedCiphertext.substring(12,encryptedCiphertext.length());
byte[] saltArray = decoder.decodeBuffer(saltIn);
byte[] ciphertextarray = decoder.decodeBuffer(ciphertext3);
aps = new PBEParameterSpec(saltArray, iteration);
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, key3, aps);
byte[] outputKey2 = cipher.doFinal(ciphertextarray);
String plaintext2 = encoder.encode(outputKey2);
System.out.println(" - Plain Text (Random Generated Key): "+plaintext2);
System.out.println("");
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 4: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
System.out.println("============================================================");
// The decrypter string plaintext should be the same as the BASE64 Encoded representation of the random DES string
byte[] randomKeyFetched = decoder.decodeBuffer(plaintext2);
generator = KeyGenerator.getInstance("DES");
DESKeySpec keyspec = new DESKeySpec(randomKeyFetched);
* Stuck here! Once the key is reformed it will be complete!
}

You need to use a SecretKeyFactory to convert the byte array back to a SecretKey to use in decryption. Continuing your example:
SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
DESKeySpec desKeySpec = new DESKeySpec(loadedKeyBytes);
SecretKey sk = skf.generateSecret(desKeySpec);
Use sk in the call to the Cipher init() function. (Note that you don't call KeyGenerator to restore a key from its bytes.)
Incidently, if you're using ECB mode for encryption I don't think you need to worry about the Initialization Vector. However, if you're using CBC mode (which is the default DES mode for the default SunJCE provider), I believe you also have to make sure that the decryption system starts from the same Initialization Vector that was used for encryption. To deal with this, if 'cipher' is your encryption Cipher object, then you call
byte bytIV[] = cipher.getIV();
to get the 8-byte IV array. To decrypt, you need to call:
IvParameterSpec iv = new IvParameterSpec(bytIV);
This is an AlgorithmParameterSpec, and can be used as the third argument to the init() function for Cipher to set up decryption, e.g.
Cipher cd = Cipher.getInstance("DES/ECB/PKCS5Padding");
cd.init(Cipher.DECRYPT_MODE, sk, iv);
I believe that CBC mode is more secure than ECB mode when you have more than 8 bytes of material to encode (e.g. use "DES/CBC/PKCS5Padding"
when you create the Cipher objects).
To simplify things a bit, you might just want to use a fixed 8-byte Initialization Vector by constructing a IvParameterSpec and using it for all DES encryption and decryption.
The documentation on all of this is extraodinarily obscure.

Similar Messages

  • Converting bytes to character array problem

    I am trying to convert a byte array into a character array, however no matter which Character Set i choose i am always getting the '?' character for some of the bytes which means that it was unable to convert the byte to a character.
    What i want is very simple. i.e. map the byte array to its Extended ASCII format which actually is no change in the bit represtation of the actual byte. But i cannot seem to do this in java.
    Does anyone have any idea how to get around this problem?

    Thanks for responding.
    I have however arrived at a solution. A little un-elegant but it seems to do the job.
    I am converting each byte into char manually by this algorithm:
              for (int i=0;i<compressedDataLength;i++)
                   if (((int) output)<0)
                        k=(127-((int) output[i]));
                        outputChr[i]=((char) k);
                   else
                        k=((int) output[i]);
                        outputChr[i]=((char) k);
                   System.out.println(k);
    where output is the byte array and outputChr is the character array

  • Converting a byte array or hex string  into DES key

    i required to covert a hex represented of DES key into key object for cryptography operation to performed ...
    can you help me to find out how to convert a hex representaion of key int DES key object

    hi friend,
    I think the key size is more than the required size. For DES algorithm, the key size is 64 bit long.But the code u have given has more than 64 bit, because of which this exception has been raised.
    Reduce the key value to 64bit and try. If it doesnt work,try the code given below .I think it might be helpful for u
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Cryption
         public byte[] encrypt(byte[] keyData,byte[] clearMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.ENCRYPT_MODE,sks);
                   byte[] encryptedMessage = c.doFinal(clearMessage);
                   return encryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public byte[] decrypt(byte[] keyData,byte[] cipherMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.DECRYPT_MODE,sks);
                   byte[] decryptedMessage = c.doFinal(cipherMessage);
                   return decryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public static void main(String[] args)
              String keyString = "ABCDEF12";
              byte keyValue[] = keyString.getBytes();
              Cryption encryption = new Cryption();
              String Message = "Hello Welcome to world of Cryptography";
              System.out.println("Key Value (represented in HEX form): "+keyString);
              System.out.println("Key Value (represented in byte array form): "+keyValue);
              System.out.println("Original Message : "+Message);
              byte[] encryptedMessage = encryption.encrypt(keyValue,Message.getBytes());
              System.out.println("Encrypted Message : "+new String(encryptedMessage));
              Cryption decryption = new Cryption();
              byte[] decryptedMessage = decryption.decrypt(keyValue,encryptedMessage);
              System.out.println("Decrypted Message : "+new String(decryptedMessage));
    output :
    Key Value (represented in HEX form): ABCDEF12
    Key Value (represented in byte array form): [B@43c749
    Original Message : Hello Welcome to world of Cryptography
    Encrypted Message : "O3�?�M�,����������,�]�3�����R�?>C$
    Decrypted Message : Hello Welcome to world of Cryptography
    whenever u use any algorithm, first findout the key size or range that algorithm supports. It is very important
    regards,
    Deepa Raghuraman

  • Private key problem

    hey folks,
    i would like to store a certificate's private key in a mysql db.
    my problem is that i don't know how to convert it back to a PrivateKey when i extract it from the db.
    i use the function Base64.encode(userPrivKey.getEncoded()); (org.bouncycastle.util.encoders.Base64; to store the private key base64 encoded in the db.
    when i extract the key from the db i can decode it with Base64.decode(). the problem is that the decode function only returns a byte array.
    so does anybody know how i can convert that byte array back to a private key?
    or is there any other (better) solution to store and retrieve private keys from a mysql db?
    many thanks
    toto

    I've been looking to do the same thing, and your code is helpful.
    If you do not want to pull in the BouncyCastle library, you can extract the RSA private key from the PKCS8 key format by parsing the DER directly. Here is some code that does it. All you need to add is the Base64 encode, and RSA begin and end flags.
    import java.util.*;
    import java.io.*;
    public class Pkcs8ToRsa {
        // rsaEncrytion is { pkcs-1 1 }
        // pkcs-1 is { iso(1) member-body(2) usa(840) rsadsi(113549) pkcs(1) 1 }
        private static final byte[] OID_rsaEncryption = {
            (byte)0x2a, (byte)0x86, (byte)0x48, (byte)0x86,
            (byte)0xf7, (byte)0x0d, (byte)0x01, (byte)0x01,
            (byte)0x01 };
        private static final byte[] INTEGER_v1 = { (byte)0x00 };
        private static final int TAG_INTEGER      = 0x02;
        private static final int TAG_OCTET_STRING = 0x04;
        private static final int TAG_OID          = 0x06;
        private static final int TAG_SEQUENCE     = 0x30;
        private byte[] buffer;
        private int offset;
        protected Pkcs8ToRsa(byte[] pkcs8key) {
            this.buffer = pkcs8key;
            this.offset = 0;
        public static byte[] convert(byte[] pkcs8key) {
            return (new Pkcs8ToRsa(pkcs8key)).extractPrivateKey();
        private int extractTag() {
            // Assume single octet tag
            return ((int)buffer[offset++]) & 0xff;
        private void matchTag(int tag) {
            if (extractTag() != tag) {
                throw new IllegalArgumentException("Bad input");
        private int extractLength() {
            int lengthOfLength = ((int)buffer[offset++]) & 0xff;
            if ((lengthOfLength & 0x80) == 0) {
                // Single octet
                return lengthOfLength;
            } else {
                // Multiple-octet
                lengthOfLength = lengthOfLength & 0x7f;
                int length = 0;
                for (int i = 0; i < lengthOfLength; i++) {
                    length = (length << 8) | (((int)buffer[offset++]) & 0xff);
                return length;
        private void matchLength(int length) {
            if (extractLength() != length) {
                throw new IllegalArgumentException("Bad input");
        private byte[] extractValue(int length) {
            byte[] value = new byte[length];
            System.arraycopy(buffer, offset, value, 0, length);
            offset += length;
            return value;
        private void matchValue(byte[] value) {
            for (int i = 0; i < value.length; i++) {
                if (buffer[offset+i] != value) {
    throw new IllegalArgumentException("Bad input");
    offset += value.length;
    public byte[] extractPrivateKey() {
    // Encoding should be
    // SEQUENCE {
    // version INTEGER,
    // privateKeyAlgorithm SEQUENCE {
    // id OBJECT IDENTIFIER,
    // Type OPTIONAL
    // privateKey OCTET STRING
    // attributes [0] Attributes OPTIONAL
    // We are after the contents of privateKey
    // Outer sequence
    matchTag(TAG_SEQUENCE);
    int totalLength = extractLength();
    if ((offset + totalLength) > buffer.length) {
    throw new IllegalArgumentException("Bad input");
    // Check version == v1
    matchTag(TAG_INTEGER);
    matchLength(INTEGER_v1.length);
    matchValue(INTEGER_v1);
    // Check algorithm
    matchTag(TAG_SEQUENCE);
    int algorithmLength = extractLength();
    int keyOffset = offset + algorithmLength;
    matchTag(TAG_OID);
    matchLength(OID_rsaEncryption.length);
    matchValue(OID_rsaEncryption);
    // Skip to privateKey
    offset = keyOffset;
    // Get it.
    matchTag(TAG_OCTET_STRING);
    int keyLength = extractLength();
    if ((offset + keyLength) > buffer.length) {
    throw new IllegalArgumentException("Bad input");
    return extractValue(keyLength);

  • Byte array to base64encoder problem, cannot encode a 7.7 MB file

    hey guys, so ive been trying to use the base64encoder to encode a bytearray which is then sent thru a webservice to the server to be decoded.
    and as the subject of this post suggests, i have been having problems encoding a big file,
    forexample i tried to upload/convert a 84KB image and it worked just fine... the trace of the string ended with a "==" which i believe means that the conversion is complete...
    but when i try to upload a 7.7MB image, it is, i guess, crashing... i dont see any "==" in the string... so i guess its not working... i was wondering if there is any any type of file size limit or soemthign for the encoding...
    the code i have is
    import flash.events.Event;
    import flash.net.FileFilter;
    import flash.net.FileReference;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Encoder;
    import services.images.ImageData;
    import services.images.Images;
    import services.images.ReturnMessage;
    // ActionScript file
        public var fileRef:FileReference = new FileReference();
        public var imgCollection:ArrayCollection = new ArrayCollection();
        public var imgService:Images = new Images();
        public var imageData:ImageData = new ImageData();
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public function onBrowseButtonClicked(event:MouseEvent):void{
            var arr:Array = [];
            arr.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.browse(arr);
            fileRef.addEventListener(Event.SELECT, fileRef_select);
            fileRef.addEventListener(Event.COMPLETE, fileRef_complete);
        public function fileRef_select(event:Event):void{
            fileRef.load();
        public function fileRef_complete(event:Event):void{
            img.source = fileRef.data;
            var fileByteArr:ByteArray = fileRef.data;
            var b64En:Base64Encoder = new Base64Encoder();
            b64En.encodeBytes(fileByteArr);                                                  //<----------------------------------------------------------
            var str:String = b64En.flush();                                                        //<----------------------------------------------------------
            trace(str.length);
            b64En.reset();
            trace("------------------------------------      " + str + "     -----------------------------");
            imageData.Base64EncodedImage = str;
            imageData.FileName = "nameofstring";
            imgService.UploadImage(imageData);
           imgService.addEventListener(FaultEvent.FAULT, servFault);
           imgService.addEventListener(ResultEvent.RESULT, imgServSuccess);
        public function imgServSuccess(event:ResultEvent):void{
            Alert.show("i am in the result");
            returnMsg = event.result as ReturnMessage;
            var resultStr:String = event.result as String;
            Alert.show(resultStr);
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
        public function servFault(event:FaultEvent):void{
            Alert.show("2 " + event.fault.message);
            Alert.show("3 " + event.fault.faultCode);
    any help will be greatly appretiated!! thanks in advace!

    yeah i did actually... except i think i changed a LOT of code since i last posted this article...
    so i dont remember where this code is exactly... lol
    i have the following code now...
    hope this helps
    i use a a lot of webservices... so there is some of that code included in there aswell...
    * This file will do the file upload. It has been suggested to me multiple times, that using a queueing system for
    * file upload is not a good idea. Instead I declared a counter and used the final function to fire the next item
    * in the array. this also makes canceling a routine easier.
    import flash.events.Event;
    import flash.events.ProgressEvent;
    import flash.net.FileReference;
    import flash.net.FileReferenceList;
    import flash.utils.ByteArray;
    import mx.collections.ArrayCollection;
    import mx.controls.*;
    import mx.managers.*;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.utils.Base64Decoder;
    import mx.utils.Base64Encoder;
    import services.images.Images;
    import valueObjects.*;
        public var t:Number = 0;
        public var fileRef:FileReferenceList = new FileReferenceList();
        public var listCacheFiles:Array = new Array();
        [Bindable] public var fileListArr:Array = new Array();
        [Bindable] public var fileNames:ArrayCollection = new ArrayCollection();
        [Bindable] public var arrUploadFiles:Array = new Array();
        public var file:FileReference;
        public var _numCurrentUpload:Number = 0;
        public var imageData:valueObjects.ImageData;
        public var imageService:Images = new Images();
        public var saveImages:Images;
        public var returnMsg:ReturnMessage = new ReturnMessage();
        public var dataToSave:ImageData;
        public var myCounter:int = 0;
        public var numPerc:Number;
        /*vars to possible delete*/
        public var fileListx:ArrayCollection;
         * Initiates the browse, when files are selected the selectionHandler function is called
        public function initiateBrowse():void{
            var filter:Array = [];
            filter.push(new FileFilter("Images", ".gif;*.jepg;*.jpg;*.png"));
            fileRef.addEventListener(Event.SELECT, selectionHandler);
            fileRef.browse(filter);
         * selection handler takes the selected files and puts them in 2 different arrays
         * fileListArr contains all the file information like the image itself and the name and everything
         * fileNames contains the information essential to populate the datagrid in the cropper.mxml
        public function selectionHandler(event:Event):void{
            //trace("selection Handler ->>");
            fileRef.removeEventListener(Event.SELECT, selectionHandler);
            var numSelected:int = event.target.fileList.length;
            var fileList:Array = event.target.fileList;
            fileListx = new ArrayCollection();
            fileListx = event.target.fileList as ArrayCollection;
            //var oldListLength:Number = fileListArr.length;
            for each(var item:Object in fileList){
                fileListArr.push(item);
                fileNames.addItem({
                    num: fileNames.length + 1,
                    name: item.name,
                    size: formatFileSize(item.size),
                    status: "",
                    itemDetails: item
            var newListLength:Number = fileListArr.length;
            if(myCounter > 0)
                loopList(myCounter);
            else
                loopList(0);
         * this function starts one, new filereference for each files in the array
        public function loopList(value:int):void{
            //trace("looplist -->");
            if(value < fileListArr.length){
                _numCurrentUpload = value;       
                file = new FileReference();
                file = FileReference(fileListArr[value]);;
                file.addEventListener(Event.COMPLETE, loadImage);
                file.addEventListener(ProgressEvent.PROGRESS, fileProgress);
                file.load();
         * This function will convert the byte array into a string, and then it sends it to the server.
        public function loadImage(event:Event):void{
            trace("loadImage -->");
            file.removeEventListener(Event.COMPLETE, loadImage);
                myCounter += 1;
                var fileByteArr:ByteArray = event.target.data;
                var b64En:Base64Encoder = new Base64Encoder();
                b64En.encodeBytes(fileByteArr);
                var str:String = b64En.flush();
                imageData = new ImageData();
                imageData.Base64EncodedImage = str;
                imageData.FileName = event.target.name;
                trace("sending -->>  " + imageData.FileName);
                updateStatus("Sending to server");
                imageService.addEventListener(ResultEvent.RESULT, imgServSuccess);
                imageService.UploadImage(imageData);
                b64En.reset();
         * This function will decode the information recieved back from the server.
        public function imgServSuccess(event:ResultEvent):void{
            trace("imgServSuccess -->");
            imageService.removeEventListener(ResultEvent.RESULT, imgServSuccess);
            var returnedImageId:ArrayCollection = new ArrayCollection();
            returnMsg = event.result as ReturnMessage;
            var returnedData:Object = event.result.Images;
            var imgD:ImageData = new ImageData();
            if(returnMsg.ThereWasAnError){
                trace(returnMsg.ErrorMessages.getItemAt(0).toString());
            else{
                for each(var imgData:ImageData in returnedData){
                    var decoded:Base64Decoder = new Base64Decoder();
                    decoded.decode(imgData.Base64EncodedImage);
                    var byteArr:ByteArray = decoded.toByteArray();
                    //img.source = byteArr;
                dataToSave = new ImageData();
                dataToSave = returnedData[0];
                listCacheFiles.push(dataToSave);
                updateStatus("Item in Cache");
                //uploadDetails.visible = true;
                loopList(myCounter);
        public var win:itemDetails;
        public function itemClicking(event:Event):void{
            var fileName:String = event.currentTarget.dataProvider[0].name;
            for(var i:Number = 0; i < listCacheFiles.length; i++){
            //var temp:ImageData = event.target as ImageData;
            win = null;
            win = itemDetails(PopUpManager.createPopUp(this, itemDetails, true));
            win.title = "Enter Details";
            PopUpManager.centerPopUp(win);
            win["save"].addEventListener("click", popupClosed);
        public function popupClosed(event:Event):void{
            var returnedData:ImageData = new ImageData;
            returnedData = win.dataToSave;
            saveImgAndData(returnedData);
        public function saveImgAndData(data:ImageData):void{
            saveImages = new Images;
            saveImages.showBusyCursor = true;
            saveImages.addEventListener(ResultEvent.RESULT, savedSuccess);
            saveImages.addEventListener(FaultEvent.FAULT, faultFunc);
            saveImages.SaveUploadedImageInformation(data);
        public function faultFunc(event:FaultEvent):void{
            Alert.show(event.fault.message);
            Alert.show(event.fault.faultString);
        public function savedSuccess(event:ResultEvent):void{
            //trace("savedSuccess -->");
            var retMsg:Object = event.result.Images;
            //trace("saving -->> " + retMsg[0].FileName);
            updateStatus("Completed");
            //loopList(myCounter);
        private function formatFileSize(numSize:Number):String {
            var strReturn:String;
            numSize = Number(numSize / 1024);
            strReturn = String(numSize.toFixed(1) + " KB");
            if (numSize > 1024) {
                numSize = numSize / 1024;
                strReturn = String(numSize.toFixed(1) + " MB");
                if (numSize > 1024) {
                    numSize = numSize / 1024;
                    strReturn = String(numSize.toFixed(1) + " GB");
            return strReturn;
        public function removeFiles():void{
            var arrSelected:Array = displayFilesList.selectedIndices;
            if(arrSelected.length >= 1){
                for(var i:Number = 0; i < arrSelected.length; i++){
                    fileNames[Number(arrSelected[i])] = null;
                var idx:int = 1;
                for(var j:Number = 0; j < fileNames.length; j++){
                    if(fileNames[j] == null){
                        fileNames.removeItemAt(j);
                        j--;
                    }else{
                        fileNames[j].num = idx++;
                if(fileNames.length > 0)
                    displayFilesList.selectedIndex = 0;
                else
                    displayFilesList.selectedIndex = -1;
                _numCurrentUpload--;
                updateProgBar();
        private function updateStatus(status:String, index:Number = -1):void{
            index = _numCurrentUpload;
            fileNames[index].status = status;
            displayFilesList.invalidateList();
        public function fileProgress(event:ProgressEvent):void{
            //trace("fileProgress -->");
            var numPerc:Number = Math.round((Number(event.bytesLoaded) / Number(event.bytesTotal)) * 100);
            updateStatus("Uploading: " + numPerc.toString() + "%");
            updateProgBar(numPerc);
            var evt:ProgressEvent = new ProgressEvent("uploadProgress", false, false, event.bytesLoaded, event.bytesTotal);
            dispatchEvent(evt);
        public function updateProgBar(numPerc:Number = 0):void{
            //trace("updateProgBar -->");
            var strLabel:String = (_numCurrentUpload + 1) + "/" + fileNames.length;
            progBar.label = strLabel;
            progBar.setProgress(_numCurrentUpload + numPerc / 100, fileNames.length);
            progBar.validateNow();

  • Key encoded back to key

    I have to save in file the keys I have generated or received. To do this if I have well understood I have to use the .getencoded() mothod. One I have save and reload the result. How can I transform this byte[] back in SecretKey or PublicKey???
    Thank you very n�mutch guys :)
    Turpo

    Hi,
    To get your key just read the file and convert it into bytes and use java.security.spec.* to generate key specification .
    Use this Spec to get your acctual keys.

  • How to repair "No bootable device insert disk and press any key" problem?

    I was browsing sites using Google Chrome when all of a sudden, my laptop completely turned off. I turned the power back on only to find the error message "Intel UNDI, PXE-2.1 (build 082)" appear in white letters, followed by a bunch of other error messages, ending with, "No bootable device insert disk and press any key". Whenever I try restarting my laptop, the same error messages show up.
    I've been reading about Toshiba laptops, to try to remedy this issue, and I've learned that as of 2007, Toshiba discontinued the recovery disks that had always accompanied the laptops, and instead, allow you to totally restore your computer without the help of a disk. (The model of my laptop is Satellite L300D - 01P).
    Now, apparently to restore a Toshiba laptop, you're supposed to press the '0' key while also pressing the power button, but when I do this, there is a beeping noise (which is apparently supposed to happen), but the error messages (ending with "No bootable device insert disk and press any key") still show up. Other than the affirmative beeping noise, no changes occur.
    Anyone had this problem or have any suggestions of how to fix it?
    Thanks so much.

    >...and I've learned that as of 2007, Toshiba discontinued the recovery disks that had always accompanied the laptops, and instead, allow you to totally restore your computer without the help of a disk. (The model of my laptop is Satellite L300D - 01P).
    Have you also learned that you SHOULD create recovery DVD using preinstalled Toshiba recovery disc creator tool? When something goes wrong with HDD you can use this disc for operating system installation. This is clearly described in Users manuals document.
    Back to your problem:
    I don't know for sure but Im afraid you have some problem with HDD controller or HDD itself.
    Is HDD recognized in BIOS settings (F2 at start up)?

  • Enter key not functioning pls i need to resume backing,enter key not function another option pls.

    Enter key not functioning pls i need to resume back,enter key not function another option pls hp mini laptop.

    Hello Damyanology,
    If your enter key is not working but you have to use it, you can bring up the on screen keyboard, and that will allow you to use enter.
    Here is a link to open the on screen keyboard.
    Go into device manager and uninstall the keyboard and restart the computer. This should reinstall the driver to correct the problem.
    Here is a link to uninstall in device manager.
    Let me know if this helps.

  • Prioryly generated key problem.

    public String encrypt(String password){
    String algo = "DESede";
    Cipher cipher = Cipher.getInstance(algo);
    String s = null;
    Key key = (Key)com.sun.crypto.provider.DESedeKey@4f9655f1;
    cipher.init(Cipher.ENCRYPT_MODE, key);
         byte[] inputBytes = password.getBytes();
         s = cipher.doFinal(inputBytes);
    return s;
    public String decrypt(String password){
    String algo = "DESede";
    Cipher cipher = Cipher.getInstance(algo);
    String s = null;
    Key key = (Key)com.sun.crypto.provider.DESedeKey@4f9655f1;
    cipher.init(Cipher.DECRYPT_MODE, key);
         byte[] vas = cipher.doFinal(password);
         String s = new String(vas);
         return s;
    I got a problem with the above code the character @ in the object com.sun.crypto.provider.DESedeKey@4f9655f1 does not compile in java, but I need to use it because its my pre generated key that i wish to use in encryption and decryption function.
    Thanks for the help in advance.

    Wow. This one is...surreal. Let's see:
    As silk.m noted, what you're trying to do doesn't make any sense. You need to have the bytes of the Key in order to recreate it. Use generatedKey.getEncoded() to get the byte[] that describes the Key, and then look at how to use DESedeKeySpec and SecretKeyFactory to recreate the Key object.
    On top of that, you have other problems.
    You can't just use byte[] plaintext = s.getBytes(). The default String encoding is different on different platforms. You need to tell getBytes() which encoding you really want.
    You're attempting to return the output of doFinal() as a String. You can't - it's a byte[]. You can't just return "new String(doFinalBytes)", either - ciphertext IS NOT "String-able". You'll need to Base64 it first.
    It's also possible you'll be bitten by having a plaintext that isn't an integral number of blocks. I don't recall if the default DESede uses padding, or assumes NoPadding.
    You've got some fixing to do...
    Good luck,
    Grant

  • 'Keys' problem when trying to re install 10.2 on Power Mac G4

    Have had my Power Mac G4 wiped clean prior to selling and am now trying to reinstall 10.2.
    Install disc one reached the end of its loading process and then froze.
    Install disc two did not respond when loaded.
    Put install disc one back in while holding down 'C' key. Started to install but soon stopped.
    Went to Disc First Aid > verify disc > 'keys out of order HD need repairing'.
    Clicked 'repair disc' and indicated 'repair complete'.
    Returned to 'verify disc' > HD needs repairing, key length too short.
    Repaired once more, keys still out of order.
    Removed Install disc one and loaded Disc Warrior.
    Speed inhibited by malfunction stage 5 when rebuilding directory.
    So with no full operating system loaded, how do we progress?

    John:
    "Keys problems" are directory issues which, if not repairable by Disk Utility need a third party package like Tech Tool Pro, DriveGenius, or Disk Warrior. However, in some cases the disk hardware may be damaged or the HDD may have failed and unable to hold the format. When in DU check the SMART status. Even if the SMART Status is Verified and the HDD is more than 3 years old you should consider replacement.
    cornelius

  • Converting a byte[] to a int or a Point

    I have sent a DatagramPacket containing a Point object converted to a byte[]. Now I want to convert the byte[] object back to a Point object. How do I do it?
    In my application I want to draw a number of dots in a window, send to a copy of the application in some other location on the Net and the two applications must view the same dots in real time. So I thought I would draw the dots, send the cordinats in a Datagram and then draw the dots using this cordinats. Is that a good idea?
    Best regards
    Jonas

    To create a Point from a byte[], assuming the byte[] has two elements:
    Point p = new Point((int)byte[0], (int)byte[1]);Is that what you need?

  • Converting PDF file back to word need assistance please, have adobe reader 11.0.10

    Need assistance converting PDF documents back to Word format, have adobe Reader 11.0.10 will this work and directions please

    Sadly no. And strange thing is that only this pdf file have problem with saving sigh...even if I told him to send again still can't save this file...my classmate doesn't have this problem  :I for this pdf...but only me specifically on this pdf...it go cray cray (crazy)

  • Escape key problems.

    My escape key has been freaking out on me lately. It seems to randomly decide to press itself down very rapidly, and it continues to do so until I press the key myself, fairly hard. The key isn't jammed or anything. Is there anything I can do to fix this, short of paying a rediculous price to get a new keyboard. This escape key problem makes even the most simple action a chore.
    By the way, I'm using a Lenovo 3000 n100.
    Message Edited by PSOCecil on 05-23-2008 06:12 PM

    Yes, they told me they didn't do any laptop work. And I sent it in when it was still under warenty, asking them to look at both my non-working USB drives (that were causing a odd power problem and causin the computer to not start), and my weird escape key. They seemed to of forgotten the escape key, and just looked at the USB drives. It's not under warenty any more, and I don't want to send it back to them again, after the ordeal I had to go through last time.

  • 7373 key problems

    Hi - my 3-month old 7373 has suddenly developed key problems - for example, the "back" key doesn't work at all, and the * key brings up the volume control! This started without me doing anything unpleasant to the phone - any suggestions?
    -Caro

    It's developed a hardware fault.
    You need to visit a nokia care point to get it fixed under warranty.
    Care points:
    UK
    http://www.nokia.co.uk/A4228006
    Europe:
    http://europe.nokia.com/A4388379
    Elsewhere:
    http://www.nokia.com and select your country.

  • Convert a byte/Byte - HEX STRING ?

    Hi ,
    My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
    please help me.

    Integer.toHexString(byteValue);
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

Maybe you are looking for

  • Can not view update rules on production BW server

    This can be quite a time-consuming problem as I can't always tell if the latest update rules are successfully transported to production.  Most every where else in production I can choose to DISPLAY however this is not the case with update rules only.

  • Link in each item of a listbox control

    Hello, I have a "select one listbox" in my form. Inside this I have a "selectItems" object, pointing to a bean. This way, my listbox will be populated. My question is: how can I have each item in the list has a URL, to open a window that will navigat

  • Installing Mavericks Failed

    Hello to everyone. I need all your help, i`m trying to install Mavericks on my Macbook Pro late 2008. But my problem is this: Once I download Mavericks  the computer started installing it but then it`s and got message saying installation failed.  any

  • ITunes can't find my songs after transfer

    I recently transfered my entire iTunes library to my Mac G4 (Tiger) via my iPod classic. After the transfer I held 'Option' down when opening iTunes and chose my new .itl folder. When iTunes opened up, all my music/videos were there, but when I went

  • Make Shared Folder into External Hard Drive

    For backup purposes I would like to disguise a shared folder as an external drive. The best way I can explain it is move a folder in the Finder window from 'Places' to 'Devices'. Let me know if you need more of an explanation...my Google-Fu is failin