Hoe to convert a String to Triple DES Key

Hi
can Someone help me how to convert a string to TRipleDES key, some times the string can be less than
24 bytes ( but DESedeKeySpec needs at least 24 bytes).
thanks
chintha

I would take a slightly different approach than that offered by previous posts. This is from looking at what OpenSSL does for generating keys.
1) Do a String.getBytes() from your password (or String.getBytes("UTF-8") if you are using other than ASCII).
2) Generate a SHA-1 hash from the bytes. This gives you a 20 byte value.
3) Compute a SHA-1 hash of the original hash and the password. This will give you another 20 byte value.
4) Take the first 20 bytes from hash #1 and the first 4 bytes of hash #2 to get a 24 byte value.
5) Give the 24 byte value odd parity (this means that each byte has an odd number of 1 bytes). You'll need to write a bit of your own code to do this.
6) Finally, use this 24 byte, odd parity value to generate your DES key.
--Kevin

Similar Messages

  • Exception 6A80 while setting Triple DES key inside the applet constructor

    In the applet definition part, I am having these definition:
    public static final byte DEFAULT_PERSO_KEY_SET_REFERENCE = (byte) 0x81;
         public static final byte[] DEFAULT_PERSO_KEY_SET_ENC = {
              (byte) 0x52, (byte) 0x57, (byte) 0x4d, (byte) 0x41,
              (byte) 0x43, (byte) 0x45, (byte) 0x43, (byte) 0x48,
              (byte) 0x41, (byte) 0x4e, (byte) 0x54, (byte) 0x49,
              (byte) 0x4c, (byte) 0x4c, (byte) 0x4f, (byte) 0x4e
         public static final byte[] DEFAULT_PERSO_KEY_SET_MAC = {
              (byte) 0x52, (byte) 0x57, (byte) 0x45, (byte) 0x4e,
              (byte) 0x43, (byte) 0x45, (byte) 0x43, (byte) 0x48,
              (byte) 0x41, (byte) 0x4e, (byte) 0x54, (byte) 0x49,
              (byte) 0x4c, (byte) 0x4c, (byte) 0x4f, (byte) 0x4e
    public Key keyEnc;
         public Key keyMac;In the applet constructor I am having these lines of code:
    keyEnc = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY,
                             false);
                   keyMac = (DESKey) KeyBuilder.buildKey(KeyBuilder.TYPE_DES, KeyBuilder.LENGTH_DES3_2KEY,
                             false);
              ((DESKey) keyMac).setKey(DEFAULT_PERSO_KEY_SET_MAC, (short) 0);
              ((DESKey) keyEnc).setKey(DEFAULT_PERSO_KEY_SET_ENC, (short) 0);On line when the MAC is setting, the next exception is thrown: 
    Status: Wrong data
    jcshell: Error code: 6a80 (Wrong data)
    jcshell: Wrong response APDU: 6A80
    Unexpected error; aborting execution

    >
    Status: Wrong data
    jcshell: Error code: 6a80 (Wrong data)
    jcshell: Wrong response APDU: 6A80
    Unexpected error; aborting execution
    >
    usually unhandled exceptions do not look like this. If you catch the exception you can try to specify the reason. May be the problem in parity bits of des keys, though this error is not listed in possible exceptions of setKey method.

  • How to encode/pad an RSA-Encrypted Triple-DES Key

    Similar to this guy's problem: http://forum.java.sun.com/thread.jspa?messageID=3332692&#3332692
    I am having an issue along the same lines... I'm writing a java client that is dealing with a C++ agent, which is expecting an encrypted TripleDES key. However when I create a DesEDE key, then encrypt it using a public RSA key, I am only sending 24 bytes, where the C++ code is expecting 32.
    Luckily, I DO have a C++ client that is doing what I need to do, so I'm investigating exactly how they're doing with the padding/encoding in order to fix my problem. But it's using the crypto 5.1 library (crypto++ maybe) and its not the most readable code.
    If anyone's done anything similar, I'd appreciate any tips/advice for how you dealt with it.
    tOm

    32/24 == 4/3 == the expansion ration converting bytes to Base64.
    Is this a possibility?

  • 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

  • Read PKCS8 encrypted key with Triple DES

    Hi, I have a RSA private key in a PKCS8 file, encrypted with Triple DES. I can obtain the RSA private key with the command:
    openssl pkcs8 -inform der -v2 des3 -passin pass:mypass -in private.key > rsakey.key
    Then I can read it in Java using bouncycastle classes:
                    Security.addProvider(new BouncyCastleProvider());
              String file = "rsakey.key";
              PEMReader pr = new PEMReader(new FileReader(file));
              Object obj = pr.readObject();
              KeyPair kp = (KeyPair) obj;
              PrivateKey privateKey = kp.getPrivate();My question is:
    How can I use the bouncycastle classes to replace the openssl command, So all the process stays in java.
    Thanks in advance
    Rich

    The class for this is javax.crypto.EncryptedPrivateKeyInfo but I seem to be having trouble getting it to work (I've posted about my problem in the Cryptography forum).

  • Decrypting PEM file using Triple DES

    Hi all,
    I am trying to decrypt a Triple DES encrypted RSAPrivateKey stored in PEM format in a file. How do I get the DES key to initialize the Cipher. I am using the following code to get the IV from the file and get the DES key using pass phrase. But I get the message
    java.lang.SecurityException: Unsupported keysize or algorithm parameters
    Can someone help me.
    Thanks in advance,
    Trilok.
    // Gets the IV params from the RSAPrivate key PEM file.
    // Uses the last 16 digits in this line to get the IV.
    // DEK-Info: DES-EDE3-CBC,4A90C209D3A81791
    private IvParameterSpec getIV(String s) { // here s = 4A90C209D3A81791
    byte[] ivBytes = new byte[8];
    for (int j=0; j<8; j++) {
    ivBytes[j] = (byte)Integer.parseInt(s.substring(j*2, j*2 + 2), 16);
    return new IvParameterSpec(ivBytes);
    private SecretKeySpec getSecretKey(byte [] pwd, byte [] iv)
    throws NoSuchAlgorithmException {
         byte[] keyMat = new byte[24];
         MessageDigest md = MessageDigest.getInstance("MD5");
         md.update(pwd);
         md.update(iv);
         byte[] data = md.digest();
         System.arraycopy(data, 0, keyMat, 0, 16);
         md.update(data);
         md.update(pwd);
         md.update(iv);
         data = md.digest();
         System.arraycopy(data, 0, keyMat, 16, 8);
         return new SecretKeySpec(keyMat, encAlg);
    }

    Hi trilok,
    Please let me know what JCE provider you are using for decrypting the Key.
    Please make sure that you have made the static or dynamic registration properly.
    For Static registration:
    Please go to JAVA_HOME/jre/lib/security/java.security
    Please edit
    security.provider.1=sun.security.provider.Sun
    For Dynamic Registration
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    Also please refer this URL, which is the third party provider which supports RSA.
    http://www.bouncycastle.org/latest_releases.html
    I hope this will help you.
    Thanks
    Bakrudeen
    Technical Support Engineer
    Sun MicroSystems Inc, India

  • "Property value is not valid" when PropertyGridView tries to convert a string to a custom object type.

    Hi,
    I have a problem with an PropertyGrid enum property that uses a type converter.
    In general it works, but when I double clicking or using the scoll wheel,  an error message appears:
    "Property value is not valid"
    Details: "Object of type 'System.String' cannot be converted to type 'myCompany.myProject.CC_myCustomProperty."
    I noticed that the CommitValue method (in PropertyGridView.cs) tries to convert a string value to a CC_myCustomProperty object.
    Here is the code that causes the error (see line 33):
    (Using the .net symbols from the PropertyGridView.cs file)
    1
            internal bool CommitValue(GridEntry ipeCur, object value) {   
    2
    3
                Debug.WriteLineIf(CompModSwitches.DebugGridView.TraceVerbose,  "PropertyGridView:CommitValue(" + (value==null ? "null" :value.ToString()) + ")");   
    4
    5
                int propCount = ipeCur.ChildCount;  
    6
                bool capture = Edit.HookMouseDown;  
    7
                object originalValue = null;   
    8
    9
                try {   
    10
                    originalValue = ipeCur.PropertyValue;   
    11
    12
                catch {   
    13
                    // if the getter is failing, we still want to let  
    14
                    // the set happen.  
    15
    16
    17
                try {  
    18
                    try {   
    19
                        SetFlag(FlagInPropertySet, true);   
    20
    21
                        //if this propentry is enumerable, then once a value is selected from the editor,   
    22
                        //we'll want to close the drop down (like true/false).  Otherwise, if we're  
    23
                        //working with Anchor for ex., then we should be able to select different values  
    24
                        //from the editor, without having it close every time.  
    25
                        if (ipeCur != null &&   
    26
                            ipeCur.Enumerable) {  
    27
                               CloseDropDown();   
    28
    29
    30
                        try {   
    31
                            Edit.DisableMouseHook = true;  
    32
    /*** This Step fails because the commit method is trying to convert a string to myCustom objet ***/ 
    33
                            ipeCur.PropertyValue = value;   
    34
    35
                        finally {   
    36
                            Edit.DisableMouseHook = false;  
    37
                            Edit.HookMouseDown = capture;   
    38
    39
    40
                    catch (Exception ex) {   
    41
                        SetCommitError(ERROR_THROWN);  
    42
                        ShowInvalidMessage(ipeCur.PropertyLabel, value, ex);  
    43
                        return false;  
    44
    I'm stuck.
    I was wondering is there a way to work around this? Maybe extend the string converter class to accept this?
    Thanks in advance,
    Eric

     
    Hi,
    Thank you for your post!  I would suggest posting your question in one of the MS Forums,
     MSDN Forums » Windows Forms » Windows Forms General
     located here:http://forums.microsoft.com/MSDN/ShowForum.aspx?ForumID=8&SiteID=1.
    Have a great day!

  • Utility to generate the triple des (3DES) encrypted password in wl 6.1?

    To take advantage of the encrypted passwords in config.xml, as of wl 6.1, is
    there a weblogic utiltiy or api tha could be used to encrypt plaintext into
    the triple-des symmetric key PRIOR to having an SA or DBA type it into the
    console? This would help me greatly in the deployment and security of
    passwords.
    Thanks in Advance,
    Steve Rogers

    Hi,
    Thank you for your question.
    I am trying to involve someone familiar with this topic to further look at this issue. There might be some time delay. Appreciate your patience.
    Thank you for your understanding and support.
    Best Regards,
    Aiden
    Aiden Cao
    TechNet Community Support

  • How do I know if I can convert a String value to an int value or not?

    Hi,
    I want to know how to make the judgment that if I can convert a String value to an int value or not? Assume that I don't know the String is number or letters
    Thank you

    Encephalopathic wrote
    Again, why?One of the problems (have been dued) in my codelab asks us to write a class as follow
    Write a class definition of a class named 'Value' with the following:
    a constructor accepting a single integer paramter
    a constructor with no parameters
    a method 'setVal' that accepts a single parameter,
    a boolean method, 'wasModified' that returns true if setVal was ever called for the object.
    a method 'getVal' that returns an integer value as follows: if setVal has ever been called, it getVal returns the last value passed to setVal. Otherwise if the "single int parameter" constructor was used to create the object, getVal returns the value passed to that constructor. Otherwise getVal returns 0.
    The setVal(int y) returns nothing, so how do I know whether it has been called or not?
    Thank you

  • Looking for a simple way to convert a string to title case

    New to LiveCycle and Javascript.  Looking for a simple way to convert a string to title case, except acronyms.  Currently using the the following, it converts acronyms to lower case:
    var str  =  this.rawValue;
    var upCase = str.split(" ");
    for(i=0; i < upCase.length; i++) {
    upCase[i] = upCase[i].substr(0,1).toUpperCase() + upCase[i].substr(1).toLowerCase();
    this.rawValue = upCase.join(' ');

    Thanks for the reply.
    Found the following script in a forum, which works fine as a "custom validation script" in the.pdf version of my form.  However, it will not work in LiveCycle?  The problem seems to be with
    "return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g"
    function toTitleCase(str) {
    var smallWords = /^(a|an|and|as|at|but|by|en|for|if|in|nor|of|on|or|per|the|to|vs?\.?|via)$/i;
        return str.replace(/[A-Za-z0-9\u00C0-\u00FF]+[^\s-]*/g, function(match, index, title){
    if (index > 0 && index + match.length !== title.length &&
      match.search(smallWords) > -1 && title.charAt(index - 2) !== ":" &&
    (title.charAt(index + match.length) !== '-' || title.charAt(index - 1) === '-') &&
    title.charAt(index - 1).search(/[^\s-]/) < 0) {
    return match.toLowerCase();
    if (match.substr(1).search(/[A-Z]|\../) > -1) {
      return match;
      return match.charAt(0).toUpperCase() + match.substr(1);
    event.value = toTitleCase(event.value);

  • Convert a String to Decimal Format in European format

    Hi Experts,
    I am having a string as a context type for a input field, where the user can enter the Price, I need to convert the same into European format "###.###,00", I am using this below code to convert the string to decimal format
    User will enter the input as 10 as it needs to be converted into 10,00. Also, 1000 which has to be converted as 1.000,00
    String Str1 = wdContext.currentvn_temptable.getVa_TempUnitPrice();
    Locale mylocale  = Locale.GERMAN;
    String pattern="###.###,00";                    
    NumberFormat nf = NumberFormat.getNumberInstance(mylocale);
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern(pattern);
    String output = df.format(Str1);
    wdComponentAPI.getMessageManager().reportSuccess("Unit Price" + " " + pattern + " " + output);
    When I execute the above code, i am getting an error called "Malformed Pattern ###.###,00"
    Please let me know, how to convert a String to Quantity in European format
    Thanks & Regards,
    Palani

    Hello!
    Try to change your pattern to this one 
    Locale mylocale  = Locale.GERMAN;
    String pattern = "#,#00.00";                    
    NumberFormat nf = NumberFormat.getNumberInstance(mylocale);
    DecimalFormat df = (DecimalFormat)nf;
    df.applyPattern(pattern);
    String output = df.format(1111111.222);
    Pattern has an influence on number of digits between separators, but you have to use ',' for grouping and '.' for decimal. Character values for separators correspond to your Locale object.
    Thanks, Mikhail

  • How to convert a string value to date

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)

    Dear All,
    I am new to powershell script, i was trying to store a Ad user password set date to a variable add, add a number of days to get the expire date.
    but when i try to convert the variable to date value, I am getting the error as below.
    Please help me......
    PS C:\script> $passwordSetDate = (get-aduser user1 -properties * | select PasswordLastSet)
    PS C:\script> $passwordSetDate
    PasswordLastSet
    7/15/2014 8:17:24 PM
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    Cannot find an overload for "ParseExact" and the argument count: "3".
    At line:1 char:1
    + $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodException
        + FullyQualifiedErrorId : MethodCountCouldNotFindBest
    PS C:\script> $a = [datetime]::ParseExact($passwordSetDate,"MM/dd/yyyy HH:MM:SS", $null)
    In your post you ask how to convert a string value to a date.  The value returned from the Get-AdUser is already a date.  It does not need to be converted.
    Bill has sshown one way to convert a date to a string and there are other methods.  You need to clarify your question.
    If you are really trying ot convert strings to dates then you can start with this:
    [datetime]'01/21/1965 13:33:23'
    Most date strings aer autodetected by the class.
    ¯\_(ツ)_/¯

  • Error synchroniz​ing with Windows 7 Contacts: "CRADSData​base ERROR (5211): There is an error converting Unicode string to or from code page string"

    CRADSDatabase ERROR (5211): There is an error converting Unicode string to or from code page string
    Device          Blackberry Z10
    Sw release  10.2.1.2977
    OS Version  10.2.1.3247
    The problem is known by Blackberry but they didn't make a little effort to solve this problem and they wonder why nobody buy Blackberry. I come from Android platform and I regret buying Blackberry: call problems(I sent it to service because the people that I was talking with couldn't hear me), jack problems (the headphones does not work; I will send it again to service). This synchronisation problem is "the drop that fills the glass". Please don't buy Blackberry any more.
    http://btsc.webapps.blackberry.com/btsc/viewdocume​nt.do?noCount=true&externalId=KB33098&sliceId=2&di​...

    This is a Windows registry issue, if you search the Web using these keywords:
    "how to fix craddatabase error 5211"       you will find a registry editor that syas it can fix this issue.

  • How to convert a String("yyyy-mm-dd") to the same but in Date format ?

    Hi,
    can anyone plz tell me how to convert a String to a date format.I'm using MSACCESS database.I want to store this string in the database.So i need to convert it to a date format since the table is designed such a way with date/time type for date field.I used SimpleDateFormat ,but i can't able to convert.The code is given below:
    coding:
    public String dateconvertion(String strDate)
    try
    SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd");
    Date date = sdfSource.parse(strDate);
    SimpleDateFormat sdfDestination = new SimpleDateFormat("yyyy-MM-dd ");
    strDate = sdfDestination.format(date);
    catch(ParseException pe)
    System.out.println("Parse Exception : " + pe);
    return(strDate);
    }

    i used prepared statement even now i am getting error like this.....
    i have included the prepared statement package also...
    my coding:
    ResultSet rsdatetemp = null;
    PreparedStatement ps = null;
    String query ="select distinct itemcode from sales where bill date between ? and ?";
    ps = precon.prepareStatement(query);
    ps.setDate(1,d1);//d1 and d2 are in date format
    ps.setDate(2,d2);
    rsdatetemp = ps.executeQuery();
    error :
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(1,d1);
    symbol : method setDate(int,java.util.Date)
    location: interface java.sql.PreparedStatement
    ps.setDate(2,d2);

  • How do I convert a string into a decimal

    I've been tryin to convert a string into decimal but I can't get it to work at all. I keep getting an exception.
    I've tried all of these:
    double myDouble = Double.valueOf(string).doubleValue();
    int myint = Interger.parseInt(string);
    float myfloat = Float.parseFloat(string);
    I can't get anything to work.
    That string i'm reading in is an array containing values with decimals. ex: -45.09348
    All the above work fine if there is no decimal, but fails when it comes to one.
    How do I go about doing this?
    Thanks!

    This works for me:String s = "-45.6789";
    double d = Double.parseDouble(s);
    System.out.println(d);Mark

Maybe you are looking for

  • Firefox 4 crashing display driver

    I am using acer aspire4741G with an NVIDIA GEFORCE GT330M' driver version 8.16.11.8886'(ForceWare 188.86). when i browse using firefox the display driver crash and show me one message like (the display driver has stopped working and recover successfu

  • My ipod is stuck on low battery!!!!! and wont charge

    this might be a lil long but please bare with me! my ipod wont charge. i whiped out my computer last weekend and had to put all my songs back onto my ipod. it was fully charged and worked fine for me.. now my battery is dead and ive plugged it into m

  • Pages cannot create Sub- folders!

    Boy! Ami disappointed! Apple's Pages software cannot support Sub-folders! I wanted to use ipa for everything and now I realize I cannot. I wanted to create a folder for Recipes with sub folders for desserts entrees etc. but since Pages does not suppo

  • VAT Rounding off during MIRO

    Dear SAP Guru's, I would like to know what has to be done to round off the VAT amount during MIRO. We have configured the rounding off rule 17 in our Tax pricing procedure and it works for PO. I could the amount gets rounded off in PO pricing procedu

  • DYLD Library Problem

    A couple of days ago, I tried to install libgd and obviously made some horrible mistakes. I installed a .pkg (seemed to be libgd) and a couple of source files (e.g. libpng, libjpeg). Since then I cannot execute any terminal commands any more. I keep