Converting a SecretKey

Hi! can anyone help on how to convert a SecretKey format to an int then to String and back to int and String and lastly back to a SecretKey format?
And, how to encrypt and decrypt a string instead of a file?

A Key isn't an integer - it's a sequence of bytes, and it's often too big to fit into an int. Even if it does fit into one of the primitive types, in order to do things like encode it as a String and rebuild Key objects from it, you're going to want to treat it as a byte[].
You could use BigInteger to do your operations on the Key. Try something like this:Key myKey = .....;
byte[] myKeyBytes = myKey.getEncoded();
BigInteger myKeyAsInt = new BigInteger( myKeybytes );
// Do arithmetic on your key here
String myKeyBase64 = Base64.encode( myKeyAsInt.toByteArray() );
// send key elsewhere; upon receipt, do:
byte[] newBigIntBytes = Base64.decode(myKeyBase64);
BigInteger newKeyAsBigInt = new BigInteger(newBigIntBytes);
// undo your arithmetic here
byte[] newKeyBytes = newKeyAsBigInt.toByteArray();
EncodedKeySpec newKeySpec = new EncodedKeySpec(newKeyBytes);
Key myKey = KeyFactory.getInstance(myAlgorithm).generateSecret(newKeySpec);You need to fill in some blanks here, obviously - but this shows the approach. Note that "Base64" isn't a standard part of Java - do a web-search and you'l find a bunch of available implementations, tho.
Note that you need to be REALLY CAREFUL doing math on keys. If you do something that isn't reversible, there's no way to get your original key back.
Regarding this:
i got the key from the DES algorithm, so it's in HEX form right?No - it's a stream of bytes. You can print it in hex, if you like. In Java, it's an Object (a SecretKey), and you need to use getEncoded() to get it in byte[] form.
Good luck,
Grant

Similar Messages

  • Newbie mistake

    Hello,
    I am new to the cryptography stuff, so please excuse me if I have made any stupid mistakes. I have this simple program that does encryption and decryption. It is supposed to print out the encrypted string as well as the key used. These values will then go into the XML configuration file. When the other application reads this config file, it is supposed to decrypt the stuff. I have a few problems actually.
    1. If I run this program, it works sometimes and sometimes it gives me an exception. The strange part is that the input is the same. I run the program 2 times within 3 mins and I get this unexpected behavior.
    2. When it does work, the decrypted value displayed is not the same as the input.
    Please can someone help and tell me what my stupid mistake is.
    You can run it as
    java -cp .;<PATH_TO_BASE64_ENCODER>.jar SecurityService <VALUE_TO_ENCRYPT_AND_DECRYPT>
    Here is my complete program
    import java.io.UnsupportedEncodingException;
    import java.security.*;
    import javax.crypto.spec.*;
    import javax.crypto.*;
    import com.Ostermiller.util.Base64;
    public class SecurityService {
    protected final String DEFAULT_ALGORITHM = "DESede";
    protected final String DEFAULT_MODE = "NONE";
    protected final String DEFAULT_PADDING = "NoPadding";
    public SecurityService() {
    * This method will encrypt the value passed to it using the algorithm provided by the user.
    * The default algorightm is DESede with no mode or padding. Only if the encoding algorithm is
    * specified will the mode and padding be read. Since these two values make most sense with a
    * particular algorithm only, there is no reason to read these values if no algorithm is specified.
    * @param anEncodingAlgorithm The algorithm to use to encrypt the value. eg. DES, DESede, RSA
    * @param aMode The mode to use along with the encryption algorithm. eg. CBC, CFB
    * @param aPadding The type of padding to use.
    * @param aValueToEncode The value to encode.
    * @return The encrypted value and the key separated using ...
    public String encrypt(String anEncodingAlgorithm,
    String aMode,
    String aPadding,
    String aValueToEncode)
    throws NoSuchAlgorithmException, Exception
    String currentAlgorithm = this.DEFAULT_ALGORITHM;
    try
    StringBuffer transformationBuffer = new StringBuffer();
    if ((null != anEncodingAlgorithm) && (0 != anEncodingAlgorithm.trim().length()))
    transformationBuffer.append(anEncodingAlgorithm);
    currentAlgorithm = anEncodingAlgorithm;
    if ((null != aMode) && (0 != aMode.trim().length()))
    transformationBuffer.append("/" + aMode);
    else
    transformationBuffer.append("/" + DEFAULT_MODE);
    if ((null != aPadding) && (0 != aPadding.trim().length()))
    transformationBuffer.append("/" + aPadding);
    else
    transformationBuffer.append("/" + DEFAULT_PADDING);
    else
    transformationBuffer.append(DEFAULT_ALGORITHM);
    System.out.println("The transformation to use is : " + transformationBuffer.toString());
    //STEP 1: Create the Cipher object that will be used to encrypt the value
    Cipher cipherObject = Cipher.getInstance(transformationBuffer.toString());
    //STEP 2: Obtain an instance of the KeyGenerator to generate a Key.
    KeyGenerator keyGenerator = KeyGenerator.getInstance(currentAlgorithm);
    keyGenerator.init(112);
    //STEP 3: Generate the secret key
    SecretKey keyToUse = keyGenerator.generateKey();
    System.out.println("During encryption, the encoded secret key is : " + keyToUse.getEncoded());
    System.out.println("During encryption, the secret key format is : " + keyToUse.getFormat());
    //STEP 4: Initialize the Cipher object so that it is in the Encryption mode.
    cipherObject.init(Cipher.ENCRYPT_MODE, keyToUse);
    //STEP 5: Encrypt the value
    byte[] encryptedData = cipherObject.doFinal(aValueToEncode.getBytes());
    //STEP 6: The encrypted data is in the form of bytes and has no structure. In order to
    //convert it to a String, it must be base64 encoded first.
    String base64EncryptedString = new String(Base64.encode(encryptedData));
    System.out.println("During encryption, the base64 encrypted value is : " + base64EncryptedString);
    //STEP 7: Create the buffer to hold the delimited encrypted value and key
    StringBuffer resultBuffer = new StringBuffer(base64EncryptedString);
    resultBuffer.append("...");
    //STEP 8: Convert the SecretKey to a DESede key
    SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede");
    DESedeKeySpec desEdeSpec = (DESedeKeySpec)desEdeFactory.getKeySpec(keyToUse, javax.crypto.spec.DESedeKeySpec.class);
    byte[] rawDesEdeKey = desEdeSpec.getKey();
    byte[] rawDesEdeKey = keyToUse.getEncoded();
    String keyInBase64Format = new String(Base64.encode(rawDesEdeKey));
    resultBuffer.append(keyInBase64Format);
    System.out.println("During encryption, the secret key is : " + keyInBase64Format);
    return resultBuffer.toString();
    catch(NoSuchAlgorithmException noSuchAlgorithm)
    throw noSuchAlgorithm;
    catch(NoSuchPaddingException noSuchPadding)
    throw noSuchPadding;
    catch(Exception e)
    throw e;
    public String decrypt(String aDecodingAlgorithm,
    String aMode,
    String aPadding,
    String akeyToUseToDecode,
    String aValueToDecode)
    throws NoSuchAlgorithmException, Exception
    String currentAlgorithm = this.DEFAULT_ALGORITHM;
    try
    StringBuffer transformationBuffer = new StringBuffer();
    if ((null != aDecodingAlgorithm) && (0 != aDecodingAlgorithm.trim().length()))
    transformationBuffer.append(aDecodingAlgorithm);
    currentAlgorithm = aDecodingAlgorithm;
    if ((null != aMode) && (0 != aMode.trim().length()))
    transformationBuffer.append("/" + aMode);
    else
    transformationBuffer.append("/" + DEFAULT_MODE);
    if ((null != aPadding) && (0 != aPadding.trim().length()))
    transformationBuffer.append("/" + aPadding);
    else
    transformationBuffer.append("/" + DEFAULT_PADDING);
    else
    transformationBuffer.append(DEFAULT_ALGORITHM);
    System.out.println("Decrypting : The transformation to use is : " + transformationBuffer.toString());
    System.out.println("Decrypting : The algorithm to use is : " + currentAlgorithm);
    //STEP 1: Create an instance of the Cipher object using the transformation.
    Cipher cipherObject = Cipher.getInstance(transformationBuffer.toString());
    //STEP 2: Convert the DESede key to a secret key
    SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede");
    //Decode the base64 encoded key to it's raw format first
    byte[] rawKey = Base64.decodeToBytes(akeyToUseToDecode);
    DESedeKeySpec keyspec = new DESedeKeySpec(rawKey);
    // SecretKeySpec keyspec = new SecretKeySpec(rawKey, currentAlgorithm);
    System.out.println("Decrypting : Key Spec created...");
    SecretKey keyToUse = desEdeFactory.generateSecret(keyspec);
    cipherObject.init(Cipher.DECRYPT_MODE, keyToUse);
    byte[] decryptedData = cipherObject.doFinal(Base64.decodeToBytes(aValueToDecode));
    StringBuffer resultBuffer = new StringBuffer(Base64.encode(decryptedData).toString());
    System.out.println("Decrypting: The decrypted value is : " + Base64.decode(resultBuffer.toString()));
    resultBuffer.append("...");
    // resultBuffer.append(Base64.encode(keyspec.getEncoded()).toString());
    resultBuffer.append(Base64.encode(keyspec.getKey()).toString());
    return resultBuffer.toString();
    catch(NoSuchAlgorithmException noSuchAlgorithm)
    throw noSuchAlgorithm;
    catch(NoSuchPaddingException noSuchPadding)
    throw noSuchPadding;
    catch(Exception e)
    throw e;
    public static void main(String args[])
    SecurityService testSecurityService = new SecurityService();
    if (args.length <= 0 )
    args[0] = "Amitabh";
    if (args.length <= 0 )
    System.out.println("USAGE: java com.petris.security.SecurityService valueToEncrypt");
    System.exit(1);
    try
    String encryptedValueAndKey = testSecurityService.encrypt(null, null, null,
    args[0]);
    int indexOfDelimiter = encryptedValueAndKey.indexOf("...");
    String encryptedValue = encryptedValueAndKey.substring(0, indexOfDelimiter);
    String key = encryptedValueAndKey.substring(indexOfDelimiter + 3);
    System.out.println("The value to encrypt is : " + args[0]);
    System.out.println("The encrypted value is : " + encryptedValue);
    System.out.println("The key used is : " + key);
    String decryptedValueAndKey = testSecurityService.decrypt(null, null, null,
    key, encryptedValue);
    indexOfDelimiter = decryptedValueAndKey.indexOf("...");
    String decryptedValue = decryptedValueAndKey.substring(0, indexOfDelimiter);
    key = decryptedValueAndKey.substring(indexOfDelimiter + 3);
    System.out.println("The complete decrypted string is : " + decryptedValueAndKey);
    System.out.println("The decrypted value is : " + Base64.decode(decryptedValue));
    System.out.println("The key used is : " + key);
    catch(Exception e)
    System.out.println(e.getMessage());
    e.printStackTrace();
    }

    1. If I run this program, it works sometimes and
    sometimes it gives me an exception. The strange part
    is that the input is the same. I run the program 2
    times within 3 mins and I get this unexpected
    behavior.
    Exceptions are your friends so listen to what they say! What exception and which line?

  • Converting String into SecretKey

    Hi there,,
    I'm having probs with decrypting my encrytped data.In fact I have encrypted the data on the client side and have sent the encrypted data and the key to the server database.On the server side I wanna retrieve the key and decrypt the encrypted data with the help of it but I'm finding no way to retrieve it as a key,,moreover while trying to cast the retreived string (having converted it to an Object),,I get the ClassCastException,,
    SecretKey key=(SecretKey) myRetrievedKeyObject;
    Hope somebody can help me out with this,,,sample code highly welcomed....
    thanks...

    Here's the class I'm using for encryption and decryption..
    import java.security.*;
    import java.io.*;
    import java.util.StringTokenizer;
    import javax.crypto.*;
    import sun.misc.*;
    import java.sql.*;
    public class DesEncrypter {
    Cipher ecipher;
    Cipher dcipher;
    DesEncrypter(SecretKey key) {
    try {
    ecipher = Cipher.getInstance("DES");
    dcipher = Cipher.getInstance("DES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch (javax.crypto.NoSuchPaddingException e) {
    } catch (java.security.NoSuchAlgorithmException e) {
    } catch (java.security.InvalidKeyException e) {
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e) {
    } catch (IllegalBlockSizeException e) {
    } catch (UnsupportedEncodingException e) {
    } catch (java.io.IOException e) {
    return null;
    hope you can guide me...

  • Converting a SecretKeySpec to a blowfish SecretKey

    Hello,
    I am having trouble converting a [blowfish] SecretKeySpec to a SecretKeys.
    I would like to:
    javax.crypto.SecretKeyFactory. bff = javax.crypto.SecretKeyFactory.getInstance("Blowfish");
    java.crypto.SecretKey myKey = bff.generatSecretKey(aSecretKeySpec);
    However the first line generates a noSuchAlgorythmException.
    For now I simply cast the SecretKeySpec to a SecretKey, but I am wondering if this is a proper way to do it, and even if this is the case, why doesn't the above work.
    JCE (1.2) is properly installed, and other crypto operations (including blowfish ones) work fine...
    Any help would be greatly appreciated.
    Please email me directly if you wish...
    [email protected]

    Hi,
    There is no generatSecretKey(aSecretKeySpec) method for KeyGenerator, just a generatSecretKey() method. Conceptually, I think that KeyGenerators are used to generate random keys, and KeyFactories are used to create Keys from Keyspecs. If I'm wrong about this I hope someone will correct me.
    Anyway I have no problem creating blowfish keys with KeyGenerators, just creating keys (from Keyspecs) with KeyFactory.
    Help!
    I think you want to use KeyGenerator to generate the
    Blowfish key. Like
    KeyGenerator bff =
    KeyGenerator.getInstance("Blowfish");
    java.crypto.SecretKey myKey =
    bff.generatSecretKey(aSecretKeySpec);

  • Converting a password to a SecretKey

    Hi,
    I am using a lightweight Kerberos style of secret key server. I communicate with the key server using RMI and pass javax.crypto.SealedObject from the key server with a ticket like
    KeyGenerator keyGen =
         KeyGenerator.getInstance("Blowfish");
    // key for client-server communications
    SecretKey sessionKey = KeyGen.generateKey();
    // the key server keeps ciphers
    Cipher serverCipher =
         (Cipher)ciphers.get(serverName)
    // this is the servers part of the ticket
    SealedObject serverTicket =
    new SealedObject(sessionKey,serverCipher);
    Object[] contents = new Object[] {
    sessionKey, serverTicket};
    // the final ticket returned
    return new SealedObject(contents,
         (Cipher)ciphets.get(clientName));
    However I am having trouble creating a SecretKey object from a password. If for instance someone creates an account with the secret key server like
    login: jim
    password: secret123
    I have implemented this so that the client always knows its password. However I cannot generate a SecretKey such that the secret key server can generate the SAME key as the client when they both share the information "secret123".
    I have tried to do the following but it did not work
    public class StringKey implements SecretKey {
    private String key;
    StringKey(String key){
    this.key = key;
    public String getFormat(){
    return "RAW"
    public String getAlgorithim(){
    return "Blowfish"
    public byte[] getEncoded(){
    return key.getBytes();
    This implementation allowed a Cipher object to be created however when I created a SealedObject on the secret key server using the Cipher and returned it as part of an RMI call the client produced null when the SealedObject.getObject(Cipher) method was invoked.
    If you have any information on how to create a Blowfish/DES/IDEA/etc.. SecretKey or any tips on how to achive a secure communication using a similar model I would greatly appriciate it.
    Thanks

    first make the byte array of the keys
    i.e. String key = "jljlSecretKey";
    byte [] k=key.getBytes();
    SecretKey desKey = new SecretKeySpec(k, "DES");
    then use the desKey in your cipher operation.
    i hope i have given the clear answer
    u can use any other algo name if you dont want to use des.

  • 3DES - Php crypto codes 2 Java codes convertion problem

    I give all php and java codes I convert one by one but I didnt get same result where is my mistake and what shall I do. Thanks for all.
    Php Code
    $key = "db9ca45ee012dcabaff193ca";
    $input = sha1("MehmetKaraman");
    $td = mcrypt_module_open('tripledes', '', 'ecb', '');
    $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
    mcrypt_generic_init($td, $key, $iv);
    $encrypted_data = mcrypt_generic($td, $input);
    mcrypt_generic_deinit($td);
    mcrypt_module_close($td);
    echo sha1(bin2hex($encrypted_data));
    Output : d7eaa53ab43683a1323cfae877a24efb4a918411
    Java Code :
    String message= “MehmetKaraman”;
    byte[] input = MessageDigest.getInstance("SHA1").digest(message.getBytes("utf-8"));
         final Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
         final SecretKey key = new SecretKeySpec("db9ca45ee012dcabaff193ca".getBytes("utf-8"), "DESede");
    cipher.init(Cipher.ENCRYPT_MODE, key );
    if( input.length % 8 != 0){
         byte [] in2 = new byte[input.length+ 8- input.length%8];
         for(int i = 0;i<input.length;i++){
         in2=input[i];
         input = in2;
         final byte[] encrypted_data = cipher.doFinal(input);
         System.out.println(bin2hex(MessageDigest.getInstance("SHA1").digest(bin2hex(encrypted_data).getBytes())));
    Output : 626b61642ec4ba8f7467933832619d492a6fdde1

    Either you need$input = sha1("MehmetKaraman", true);or in your Java you need to hex encode your sha1 digest before encrypting. When I do either of these and emulate your Java bin2hex() method I get a match.
    I don't understand why people seem unable to do simple debugging. If you had read the PHP documentation for the sha1() function and had printed out the results at each stage it would have been obvious.
    P.S. The zero padding implemented by your codeif( input.length % 8 != 0){
    byte [] in2 = new byte[input.length+ 8- input.length%8];
    for(int i = 0;i<input.length;i++){
    in2=input[i];
    input = in2;
    }can be replaced by 1 line using one of the methods in class java.util.Arrays.
    Edited by: sabre150 on Sep 15, 2010 3:10 PM                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can i convert my encrypting file to a applet form to use it in IE?

    Hi, i m a little new in JAVA.
    I searched about encryting methods. And i decide to built a encrypter that reads a string from a textbox and writes the encrypted form to another textbox.. this code is working in eclipse. but i cannot convert this to applet form to use it in internet explorer .. i dont know why this not work. It says : "Applet password notinited" -> How can i solve this problem ???
    Please HELP ME ! Thanks alot..
    package yeni;
    import java.applet.*;
    import java.awt.*;
    import java.lang.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class password extends java.applet.Applet
         SecretKeySpec keyS;
         SecretKey key;
         SecretKey key_s;
         String encrypted;
         String decrypted;
         KeyGenerator keyGen;
         Mac mac;
         byte[] utf8;
         byte[] digest;
         private Button b_open;
         private Button b_next;
         private TextField t_userID;
         private TextField t_password;
         private TextField re_userID;
         private TextField re_password;
         private Label l_title;
         private String root;
         private int col;
         private String title;
         private String buttontxt;
         private int bgcolor;
         private int fsize;
         private String fface;
         private String errorURL;
         /* Init */
         public void init()
              String att = getParameter("root");
              root = (att == null) ? this.getDocumentBase().toString() : att;
              att = getParameter("textfield");
              col = (att == null) ? 20 : (Integer.valueOf(att).intValue());
              att = getParameter("font_size");
              fsize = (att == null) ? 11 : (Integer.valueOf(att).intValue());
              att = getParameter("font_face");
              fface = (att == null) ? "Arial" : att;
              att = getParameter("color");
              bgcolor = (att == null) ? Color.white.getRGB() : (Integer.parseInt(att, 16));
              att = getParameter("title");
              title = (att == null) ? "" : att;
              att = getParameter("button");
              buttontxt = (att == null) ? "OPEN" : att;
              att = getParameter("wrong");
              errorURL = (att == null) ? "" : att;
              setFont(new Font(fface, Font.PLAIN, fsize));
              setBackground(new Color(bgcolor));
              b_open = new Button(buttontxt);
              b_next = new Button("NEXT");
              t_userID = new TextField(col);
              t_password = new TextField(col);
              re_userID = new TextField(col);
              re_password = new TextField(col);
              l_title = new Label(title);
              t_userID.setBackground(Color.white);
              t_password.setBackground(Color.white);
              t_password.setEchoCharacter('*');
              re_userID.setBackground(Color.YELLOW);
              re_password.setBackground(Color.YELLOW);
    //          re_password.setEchoCharacter('-');
              setLayout(new FlowLayout(FlowLayout.CENTER,3,3));
              if(title.length()>0)
                   add(l_title);
              add(t_userID);
              add(t_password);
              add(b_next);          
              add(b_open);
              add(re_userID);
              add(re_password);
              t_userID.setText("User ID");
              t_password.setText("Password");
              //re_password.hide();
              //re_password.hide();
              show();
         /* Transfer - �ifreleleme */
         void transfer()
              if(t_userID.getText().length()>0)
                   re_userID.setText(t_userID.getText());
              else t_userID.setText("Enter Your USER ID!");
              if(t_password.getText().length()>0)
                   //Calling HMAC Function
                   re_password.setText(HMAC(t_password.getText()));
         /* HMAC Fonksiyonu - �ifreleme */
         public String HMAC(String values){
             String output = "";
             try {
                 //Generate a key for the HMAC-MD5 keyed-hashing algorithm;
                 key =  new SecretKeySpec( "istenen anahtar".getBytes("ASCII"), "HmacMD5");
                 // Create a MAC object using HMAC-MD5 and initialize with key
                 mac = Mac.getInstance("HmacMD5");
                 mac.init(key);
                 // Encode the string into bytes using utf-8 and digest it
                 utf8 = values.getBytes("UTF8");
                 digest = mac.doFinal(utf8);
                 //If desired, convert the digest into a string
                 String digestB64 = new sun.misc.BASE64Encoder().encode(digest);
                 output += digestB64;
             catch(Exception e){}
             return output;
         /* surfto_error Fonksiyonu - Hata durumu */
         void surfto_error()
              if(errorURL.length()>0)
                   try
                        getAppletContext().showDocument(new URL(errorURL),"_self");
                   catch (MalformedURLException e) {}
              else
                   re_password.setText("");
                   showStatus("Invalid password!");
         /* surfto Fonksiyonu - Bilgi Aktar�m� */
         void surfto()
              if(t_password.getText().length()>0)
                   try
                        URL surftoURL = new URL(root+t_password.getText()+".html");
                        InputStream in = surftoURL.openStream();
                        in.close();
                        getAppletContext().showDocument(surftoURL,"_self");
                   catch (MalformedURLException e) { surfto_error(); }
                   catch (SecurityException e) { surfto_error(); }
                   catch (IOException e) { surfto_error(); }
         /* Durum ��leme */
         public boolean handleEvent(Event evt)
              if(evt.id == Event.KEY_PRESS && evt.target == t_password && evt.key==10)
                   surfto();
                   return(true);
              return super.handleEvent(evt);
         /* Eylem ��leme  */
         public boolean action(Event evt, Object arg)
              if (evt.target == b_open)
                   surfto();
                   return true;
              if (evt.target == b_next)
                   transfer();
                   return true;
              return(super.action(evt,arg));
    }

    In method HMAC, you have towards the bottom
    catch(Exception e) {}please change this to
    catch(Exception e)
                e.printStackTrace();
            }Note that using the sun.* classes, including the sun.misc.BASE64Encoder class, requires elevated privileges (see http://forum.java.sun.com/thread.jspa?threadID=483223&messageID=2255882).
    It is not difficult to write your own encoder/decoder class, or borrow one from someone else. Just google on "java base64 encoder".

  • Saving SecretKey to database

    I need to encrypt user password with a key and store that key in the database along with the encrypted password. Every once in a while I need to generate a new encryption key. So far it works fine with the encryption/decryption routine for 3-4 tests, but every once in a while I get the BadPadding exception and when i look at the key stored in the database I see that the value is a bit different from what was generated. Can anyone please tell me why this might be happening?
    I can post my code for new key generation and storing and retrieving it from the database.
    Here is my method to get the new key that I will use for encryption and then store this key in the database column of varchar2(100) . What should I do different?
    public String genEncryptionKey() {
    try {
    // Step 1.
    // Get an instance of a key generator for DES
    KeyGenerator kgen = KeyGenerator.getInstance("DES" );
    kgen.init(56, new SecureRandom() );
    // Step 2.
    // Generate the key
    SecretKey sKey = kgen.generateKey();
    return new String( sKey.getEncoded());
    catch( Exception e ) {
    e.printStackTrace();
    return null;
    I am then storing this key in the database
    when i do a printlln after this method to see the value of the key and compare it with what i get from the database they are slighlty different
    Thanks

    the problem is that sKey.getEncoded() return an array of bytes and the ascii characters corresponding to this bytes are not "printable" characters.
    If there is a '0' in the array the string will be truncated because '0' mean end of string.
    Convert your byte array in a string using a base 64 encoder (sun.misc.BASE64Encoder)

  • Convert Below Java code equivalent to c# windows store app.

    Hi
    please help me " To convert Below Java code equivalent to c# windows store app."
    private String SecretKey = "enctsbqrm6hxyjfa";
        public byte[] encrypt(String text) throws Exception
            if(text == null || text.length() == 0)
                throw new Exception("Empty string");
            // convert key to bytes
            byte[] keyBytes = SecretKey.getBytes("UTF-8");
            // Use the first 16 bytes (or even less if key is shorter)
            byte[] keyBytes16 = new byte[16];
            System.arraycopy(keyBytes, 0, keyBytes16, 0, Math.min(keyBytes.length, 16));
            // convert plain text to bytes
            byte[] plainBytes = text.getBytes("UTF-8");
            // setup cipher
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes16, "AES");
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            //byte[] iv = new byte[16]; // initialization vector with all 0
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // encrypt
            byte[] encrypted = cipher.doFinal(plainBytes);
            return encrypted;
      Thanks            
      Nitin

    Hello Nitin,
    Your current requirement is beyond the scope of our support for this fourm which is used to Discuss and ask questions about .NET Framework Base Classes (BCL) such as Collections, I/O, Regigistry, Globalization, Reflection.
    If you want to know how to encrypt/decrypt in windows store app, I suggest that you could post a it to:
    https://social.msdn.microsoft.com/Forums/windowsapps/en-US/home?forum=winappswithcsharp
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • 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.

  • Convert des to desede

    how could i convert the following des encryption program into triple des?
    import java.io.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Encrypter {
        Cipher ecipher;
        Cipher dcipher;
        // 8-byte Salt
        byte[] salt = {
            (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
            (byte)0x56, (byte)0x35, (byte)0xE3, (byte)0x03
        // Iteration count
        int iterationCount = 19;
        Encrypter(String passPhrase) {
            try {
                // Create the key
                KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
                SecretKey key = SecretKeyFactory.getInstance(
                    "PBEWithMD5AndDES").generateSecret(keySpec);
                ecipher = Cipher.getInstance(key.getAlgorithm());
                dcipher = Cipher.getInstance(key.getAlgorithm());
                // Prepare the parameter to the ciphers
                AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
                // Create the ciphers
                ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
                dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
            } catch (java.security.InvalidAlgorithmParameterException e) {
            } catch (java.security.spec.InvalidKeySpecException e) {
            } catch (javax.crypto.NoSuchPaddingException e) {
            } catch (java.security.NoSuchAlgorithmException e) {
            } catch (java.security.InvalidKeyException e) {
        public String encrypt(String str) {
            try {
                // Encode the string into bytes using utf-8
                byte[] utf8 = str.getBytes("UTF8");
                // Encrypt
                byte[] enc = ecipher.doFinal(utf8);
                // Encode bytes to base64 to get a string
                return new sun.misc.BASE64Encoder().encode(enc);
            } catch (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (UnsupportedEncodingException e) {
            } catch (java.io.IOException e) {
            return null;
        public String decrypt(String str) {
            try {
                // Decode base64 to get bytes
                byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
                // Decrypt
                byte[] utf8 = dcipher.doFinal(dec);
                // Decode using utf-8
                return new String(utf8, "UTF8");
            } catch (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (UnsupportedEncodingException e) {
            } catch (java.io.IOException e) {
            return null;
         public static void main(String[] args) {
             // Here is an example that uses the class
             try {
                 // Create encrypter/decrypter class
                 Encrypter encrypter = new Encrypter("My Pasdfgqerft t2t43563456346thyerthyewh!");
                 // Encrypt
                 String encrypted = encrypter.encrypt("Don't tell anybody!");
                  System.out.println(encrypted);
                 // Decrypt
                 String decrypted = encrypter.decrypt(encrypted);
                 System.out.println(decrypted);
             } catch (Exception e) {
    }Is this going to have to be a total rewrite?
    Thankyou.

    I think you should be aware that you exception handling is classed a criminal by most Java programmers. Just swallowing exceptions can rarely be justified.Oh - and there's me thinking it was good - i usually just stick a 'throws Exception' after the function delceration.
    ..and it wasn't my code..

  • String representation of SecretKey

    I want to convert SecretKey to String and send it to server.
    I do this:
    SecretKey key = generateKey();
            SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
            DESedeKeySpec keyspec =
                    (DESedeKeySpec) keyfactory.getKeySpec(key, DESedeKeySpec.class);
            byte[] raw = keyspec.getKey();
            String skey = new String(raw);And send skey to server.
    Server must recover this info in order to decode properly.
    So server do this:
    byte[] rawDesEdeKey=skey.getBytes();
    SecretKeyFactory desEdeFactory = SecretKeyFactory.getInstance("DESede");
                // Convert the raw bytes of a key back to a SecretKey object
                DESedeKeySpec keyspec = new DESedeKeySpec(rawDesEdeKey);
                k = desEdeFactory.generateSecret(keyspec);And k is my SecretKey I use to decode info on server.
    But something here is not right. Because Server cannot parse xml using this key.

    Thanks.
    Anyway I decided that sending a key is security leak and now share one key among server and client.

  • Need to a voltage converter to run US-bought 110v HP Printers in 220v Pakistan any recommendations?

    I Purchased Three Printers 
    1. 
    HP LaserJet Enterprise 500 MFP M525dn(CF116A)
    2.
    HP Color LaserJet Enterprise CP4025n Printer(CC489A)
    3.
    HP LaserJet P2055d Printer (CE457A) -
     All of them three operates on 110v USA.  but i need them to use in 220V . Can anyone recommend me any good Voltage converter ?
    This question was solved.
    View Solution.

    Hi,
    Before go out to buy a converter/transformer  (you need over 2KW for all 3 of them), please check the switches at the back, they may have switches to switch from 110V to 220V. I don't know your market, my suggestion: talk with an electrician who knows the real world much better.
    Regards.
    BH
    **Click the KUDOS thumb up on the left to say 'Thanks'**
    Make it easier for other people to find solutions by marking a Reply 'Accept as Solution' if it solves your problem.

  • ALL MY DESKTOP APPS CONVERTED TO PDF FILES.

    After sending an urgent email attachment in Adobe PDF to Government Offcom, all my Desktop applications in windows 7 64 bit have been converted to PDF files and cannot be opened.   The attachment used was sent to me by my Secretary remotely using an old MAC.
    I can return my laptop to normal operation by un installing my Adobe Reader 11 app, but the problem returns when I re Download Adobe Reader
    11 again.     After discussing this with Adobe Technical in London they advised me to raise this issue with your Adjudicators in this Forum. 
    Please assist asap as this is very urgent right now for several genuine reasons.
    Many thanks.   Derek Horder.

    See if anything in here helps: https://helpx.adobe.com/acrobat/kb/application-file-icons-change-acrobat.html

  • Which is best app to convert voice memos to text?

    There must be a way to import iPhone 5s voice memos, some 20 minutes long into editable text. Recommendations would be appreciated.

    SORRY! WHAT I MEANT TO ASK WAS "I WANT TO EXPORT  YOUTUBE & FACEBOOK VIDEOS TO ITUNES. WHAT IS THE BEST APP. TO USE TO CONVERT THESE VIDEOS INTO A FORMAT THAT IS ACCEPTABLE TO ITUNES. WHAT IS THE BEST FORMAT TO USE. THANK YOU

Maybe you are looking for

  • Email is not being sent to the vendor

    Dear All, I am facing a concern where the Purchase order output email is not triggering to the vendor. When I have checked in the SPPFP transaction code, I am having the below error. I have checked the below and all are seems to be fine. 1.) In the B

  • GT70 Dominator Pro 2PE Freezing on Alt tab

    Hi there, first post just wondering if anyone can think of any fixes I haven't. Basically for about a little over a week now my laptop freezes whenever I alt tab out of a game. I can play fine, games will run great but as soon as I alt tab out and th

  • OAS 4.0.8.1 on Linux error

    I installed OAS 4.0.8.1 on RH Linux 6.0 successfully but when I try to start the services this message appears: OWS-08820: Unable to start wrksf process '/home/oracle/admin/ows/ows/4.0/bin/wrksf' Initialization Failure - Exiting OAS... Any ideas ?

  • Help with the enlarged display after install an old PC program!!

    I've installed "hooks on phonics" program on my think pad T7700.  The program is 4-5 years old. The program functions on the thinkpad computer but the rest of the display on the computer is all enlarged.  I've deinstalled the program but still con't

  • Send a pages document as a email

    hello i use to send my newsletter in publisher as a email so people would not need to open an atachment, i dont know how to do it in pages, ? i would like to send it just like the mac news