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?

Similar Messages

  • 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

  • How to remove padding after RSA decryption??

    Hello,
    I am testing my host apps ability to read public key that was saved in file after being exported from smart card where it was generated.
    I have successfully used the private key on card to encrypt a small piece of data and the cryptogram is returned to the host.
    On host side I retrieve public key from file and decrypt ciphertext
    The on-card alg for Cipher is declared as follows-
    RSAcipher = Cipher.getInstance(Cipher.ALG_RSA_PKCS1, true);and in the host app
    Cipher rsaCipher = Cipher.getInstance("RSA","BC");I can see from what is returned from
    byte[] decrypted = rsaCipher.doFinal(this.encryptedData);that the correct data is being returned, but is is padded by
    01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF
    FFFFFFFFFFFFFFFFFFFFFFFFFFFF00How do I know where the padding ends and the plaintext begins?
    Can anyone help me with this?
    Thanks in advance,
    Ann

    Hi!
    I have the same problem like you.
    But my problem is that i don,t know how to move the key across. I manege to create a pair of keys public and private using RSA Algorithm.
    privateKey = KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PRIVATE,KeyBuilder.LENGTH_RSA_512,false);
            publicKey = KeyBuilder.buildKey(KeyBuilder.TYPE_RSA_PUBLIC,KeyBuilder.LENGTH_RSA_512,true);
                        // KeyPair creation
                        if(keyPair == null){
                            keyPair = new KeyPair(KeyPair.ALG_RSA, (short)publicKey.getSize());
                        // starts key generation process
                        keyPair.genKeyPair();
                      publicKey = keyPair.getPublic();
                        privateKey = keyPair.getPrivate();
                         cipher = Cipher.getInstance(ALG_RSA_NO_PAD, false );then i send the modulus and exponent part of the public key to host
                 byte    keyElement = (byte)(apduBuffer[ISO7816.OFFSET_P2] & 0xFF);
                     // check correct type (modulus or exponent)
                     if((keyElement != 0x00) && (keyElement != 0x01))
                         ISOException.throwIt(ISO7816.SW_INCORRECT_P1P2);
                     // check elements request
                     if(keyElement == 0) {
                         // retrieve modulus
                         apduBuffer[0] = (byte)((RSAPublicKey)publicKey).getModulus(apduBuffer, (short)1);
                     } else
                         // retrieve exponent
                        apduBuffer[0] = (byte)((RSAPublicKey)publicKey).getExponent(apduBuffer, (short)1);
                     // send the key element
                     apdu.setOutgoingAndSend((short)0, (short)((apduBuffer[0] & 0xFF) + 1));I decrypt the data as follow in the card
          byte[] apduBuffer = apdu.getBuffer();
          if(!privateKey.isInitialized())
                            ISOException.throwIt(ISO7816.SW_CONDITIONS_NOT_SATISFIED);
          cipher.init(privateKey,Cipher.MODE_DECRYPT);
          apdu.setIncomingAndReceive();
         cipher.doFinal(apduBuffer, (short)ISO7816.OFFSET_CDATA, (short)(apduBuffer[ISO7816.OFFSET_LC] & 0xFF), apduBuffer, (short)0);
        apdu.setOutgoingAndSend((short)0, (short)(KeyBuilder.LENGTH_RSA_512/8));
       in host i encrypt data as follow
    // Note modulus and exponent are arrays of bytes from the card
        BigInteger modulus = new BigInteger(1,modulus);
        BigInteger exponent =new BigInteger(1,exponent);
        cipher = Cipher.getInstance("RSA");
    RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus,exponent);
    keyFactory = KeyFactory.getInstance("RSA");
    pubKey = keyFactory.generatePublic(pubKeySpec);
    cipher.init(Cipher.ENCRYPT_MODE,pubKey);
    byte[] p = cipher.doFinal(data);

  • 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 encrypt excel file data using triple DES algorithm in oracle

    Hi,
    I would like to know the process or script to encrypt/decrypt the excel file data using triple DES algorithm in oracle.

    I'm not quite sure your requirement.... do you mean when uploading files to be stored in the database ?

  • Cannot decrypt RSA encrypted text : due to : input too large for RSA cipher

    Hi,
    I am in a fix trying to decrypt this RSA encrypted String ... plzz help
    I have the encrypted text as a String.
    This is what I do to decrypt it using the Private key
    - Determine the block size of the Cipher object
    - Get the array of bytes from the String
    - Find out how many block sized partitions I have in the array
    - Encrypt the exact block sized partitions using update() method
    - Ok, now its easy to find out how many bytes remain (using % operator)
    - If the remaining bytes is 0 then simply call the 'doFinal()'
    i.e. the one which returns an array of bytes and takes no args
    - If the remaining bytes is not zero then call the
    'doFinal(byte [] input, int offset, in inputLen)' method for the
    bytes which actually remained
    However, this doesnt work. This is making me go really crazy.
    Can anyone point out whats wrong ? Plzz
    Here is the (childish) code
    Cipher rsaDecipher = null;
    //The initialization stuff for rsaDecipher
    //The rsaDecipher Cipher is using 256 bit keys
    //I havent specified anything regarding padding
    //And, I am using BouncyCastle
    String encryptedString;
    // read in the string from the network
    // this string is encrypted using an RSA public key generated earlier
    // I have to decrypt this string using the corresponding Private key
    byte [] input = encryptedString.getBytes();
    int blockSize = rsaDecipher.getBlockSize();
    int outputSize = rsaDecipher.getOutputSize(blockSize);
    byte [] output = new byte[outputSize];
    int numBlockSizedPartitions = input.length / blockSize;
    int numRemainingBytes = input.length % blockSize;
    boolean hasRemainingBytes = false;
    if (numRemainingBytes > 0)
      hasRemainingBytes = true;
    int offset = 0;
    int inputLen = blockSize;
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < numBlockSizedPartitions; i++) {
      output = rsaDecipher.update(input, offset, blockSize);
      offset += blockSize;
      buf.append(new String(output));
    if (hasRemainingBytes) {
      //This is excatly where I get the "input too large for RSA cipher"
      //Which is suffixed with ArrayIndexOutofBounds
      output = rsaDecipher.doFinal(input,offset,numRemainingBytes);
    } else {
      output = rsaDecipher.doFinal();
    buf.append(new String(output));
    //After having reached till here, will it be wrong if I assumed that I
    //have the properly decrypted string ???

    Hi,
    I am in a fix trying to decrypt this RSA encrypted
    String ... plzz helpYou're already broken at this point.
    Repeat after me: ciphertext CANNOT be safely represented as a String. Strings have internal structure - if you hand ciphertext to the new String(byte[]) constructor, it will eat your ciphertext and leave you with garbage. Said garbage will fail to decrypt in a variety of puzzling fashions.
    If you want to transmit ciphertext as a String, you need to use something like Base64 to encode the raw bytes. Then, on the receiving side, you must Base64-DEcode back into bytes, and then decrypt the resulting byte[].
    Second - using RSA as a general-purpose cipher is a bad idea. Don't do that. It's slow (on the order of 100x slower than the slowest symmetric cipher). It has a HUGE block size (governed by the keysize). And it's subject to attack if used as a stream-cipher (IIRC - I can no longer find the reference for that, so take it with a grain of salt...) Standard practice is to use RSA only to encrypt a generated key for some symmetric algorithm (like, say, AES), and use that key as a session-key.
    At any rate - the code you posted is broken before you get to this line:byte [] input = encryptedString.getBytes();Go back to the encrypting and and make it stop treating your ciphertext as a String.
    Grant

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

  • Triple DES CBC Encryption using an Initial Vector

    How can triple DES encryption in CBC be done using the javacard package and not javax?
    Will this do?
                   cipher3DESCBCDebSesKey1.init( key, Cipher.MODE_ENCRYPT, initVector, (short) 0, (short) 8);
                   cipher3DESCBCDebSesKey1.doFinal( input, (short) 0, (short) 16, SesKey, (short) 0 );
    After all the initialization, will the doFinal already give me the result of triple DES using CBC? or do I have to init* and doFinal* three times?
    Also, I used the no pad setting for this one.
    cipher3DESCBCDebSesKey1 = Cipher.getInstance( Cipher.ALG_DES_CBC_NOPAD, false );

    The fact that only the first block is corrupt is indicative that I you are not using the same IV on both sides. This is confirmed by your PHP code that seems to generate a random IV so your chance of getting the same IV on both sides is just about zero.

  • Can I encrypt a string with RSA encryption using DBMS_CRYPTO?

    We have an web application that does a redirect thru a database package to a 3rd party site. They would like us to encrypt the querystring that is passed using RSA encryption. The example that they've given us (below) uses the RSA cryptographic service available in .NET. Is it possible to do this using DBMS_CRYPTO or some other method in Oracle?
    Below are the steps outlined to use the key to generate the encrypted URL
    2.1 Initialize Service
    The RSA cryptographic service must be initialized with the provided public key. Below is sample code that can be used to initialize the service using the public key
    C#
    private void InitializeRSA( string keyFileName )
    CspParameters cspParams = new CspParameters( );
    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
    m_sp = new RSACryptoServiceProvider( cspParams );
    //Load the public key from the supplied XML file
    StreamReader reader = new StreamReader( keyFileName );
    string data = reader.ReadToEnd( );
    //Initializes the public key
    m_sp.FromXmlString( data );
    2.2 Encryption method
    Create a method that will encrypt a string using the cryptographic service that was initialized in step 2.1. The encryption method should convert the encryption method to Base64 to avoid special characters from being passed in the URL. Below is sample code that uses the method created in step 2.1 that can be used to encrypt a string.
    C#
    private string RSAEncrypt( string plainText )
    ASCIIEncoding enc = new ASCIIEncoding( );
    int numOfChars = enc.GetByteCount( plainText );
    byte[ ] tempArray = enc.GetBytes( plainText );
    byte[ ] result = m_sp.Encrypt( tempArray, false );
    //Use Base64 encoding since the encrypted string will be used in an URL
    return Convert.ToBase64String( result );
    2.3 Generate URL
    The query string must contain the necessary data elements configured for you school in Step 1. This will always include the Client Number and the Student ID of the student clicking on the link.
    1.     Build the query string with Client Number and Student ID
    C#
    string queryString = “schoolId=1234&studentId=1234”;
    The StudentCenter website will validate that the query string was generated within 3 minutes of the request being received on our server. A time stamp in UTC universal time (to prevent time zone inconsistencies) will need to be attached to the query string.
    2.     Get the current UTC timestamp, and add the timestamp to the query string
    C#
    string dateTime = DateTime.UtcNow.ToString(“yyyy-MM-dd HH:mm:ss”);
    queryString += “&currentDT=” + dateTime;
    Now that the query string has all of the necessary parameters, use the RSAEncrypt (Step 2.2) method created early to encrypt the string. The encrypted string must also be url encoded to escape any special characters.
    3.     Encrypt and Url Encode the query string
    C#
    string rsa = RSAEncrypt(querystring);
    string eqs = Server.UrlEncode(rsa);
    The encrypted query string is now appended to the Url (https://studentcenter.uhcsr.com), and is now ready for navigation.
    4.     Build the URL
    C#
    string url = “https://studentcenter.uhcsr.com/custom.aspx?eqs=” + eqs

    The documentation lists all the encyrption types:
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_crypto.htm#ARPLS664

  • RSA Encryption

    Dear colleagues,
    do you have any idea how to nicely implement RSA encryption in PL/SQL? I couldn't find anything interesting (including DBMS_CRYPTO package).
    Many thanks in advance

    And maybe: Cryptography

  • How do i keep my events from tripling on my calendars

    how do i keep my events from tripling on my calendars? I have the date once on mac and once on phone but on i pad it shows up three times and some I have not even figured out how to delete on the i pad

    Open FaceTime preferences>Settings and uncheck iPhone Cellular Calls.

  • Is it enough only use RSA encryption?

    Hi all,
    I want to know is it enough if we develop Java Card application by using only RSA encryption?..
    if on-card application uses RSA, and so off-card application uses RSA, is it mean that we have to use 2 KeyPairs?..
    I mean, the off-card shall generate Pub and Priv Key, Keep Priv-Key secret, and the Pub key is distributed to card..
    and of course on-card do same thing, it will generate Pub and Priv Key, Keep Priv-Key secret, and the Pub key is distributed to Off-card application..
    Please correct me if this wrong..
    if this isn't wrong, do i still have to use X509Certificate?..
    Thanks in advance,,

    Thanks Lexdabear and Shane for your reply..
    Actually, i'm a little bit confused how do i can make sure the data is being sent is confidential and valid (it means that the data received by receiver is same with the data sent by sender)..
    Hm, i read from the PDF document that i downloaded from the internet, says that :
    &#9679; Signing
    Use private key to “sign” data
    &#9679; Verification
    Use public key to verify “signature”
    &#9679; Encryption
    Use public key to encrypt data
    &#9679; Decryption
    Use private key to decrypt data
    Can i mix these features together if i only use single RSA Key-Pair (only on the card side)?, assume that the on-card application hold only Private-Key, can on-card do these features together ((encrypt, decrypt, sign, verify) if it has only Private Key? ..
    based on that, it means that if we use only single RSA KeyPair, assume that the Card holds the Private Key and the Off-card holds the Public-Key, so the application in the card can only do Sign and Encrypt data before data sent to the off-card, and of course, the off-card can only do Verify signature and Decrypt data received..
    So, how the card can decrypt and verify the signature of the data sent by off-card if the card doesn't hold the public key of the off-card ?
    i thought the off-card SHOULD send its Public-Key to the on-card application, so the On-Card application can do Decrypt and Verify the signature of data sent by Off-Card..
    i thought single RSA keypair isn't enough (My point of view as a less of experience programmer)
    Please correct me if i'm wrong..
    Thanks in advance..
    Edited by: Leonardo_Carreira on Jun 22, 2010 2:22 AM

  • How to encode queryString ....help pls

    hi,
    can any tell me how to encode queryString in jsp.
    itz urgent
    thanks

    thanks for reply
    i have a simple registration form which simply take the value from user and pass to another page . But in address bar it shows all the values that the user is passing . I want this to be encrypt or encoded into another form which is secure than this.
    Can You tell how to solve this?

  • 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 to encode URL parameters in pl/sql?

    How to encode url and its paramters in PL/SQL to call a page using html GET method? Is there any equiavlent method of java's URLEncoder.encode() method in pl/sql (in any web packages) ?
    Any help/pointers highly appreciated.
    P.S. : URGENT PLEASE!!!

    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:371959198986

Maybe you are looking for

  • VPN Client and Clientless users not authenticating with AD

    Web clients are receiving login failed messages and VPN clients are getting disconnected by host messages. I am able to ping the server from the ASA5510.  Users authenticate in AD.  I am not sure if the problem is on the server or the ASA. CP

  • We need to create one or more business services to connect to service provider in OSB

    Hi all,     I posted some questions for OSB and received some responses helpful. And today, I have a question about it to clearing about business services in OSB.     Based on oracle's documents, a business service will connect to (I mean it can comm

  • Async Call to BPEL

    I have a basic process, and trying to call it ansynchronously. The process works well when I invoke with the syncronous call, however it cannot get the input I provide ( a single string) with the asyncrounous call. For the error I see that the only d

  • .avi files in prem elements 11

    An error message apears after import" not supported codec is req'd " in prem elements 11. I purchased the software to use with .avi files which were listed as compatible on the web site.

  • Ethernet cable not recognized

    First off, I am not a technical guru, so I need help.  I have a WRT54G wireless router that I have been using for a couple years.  Today, I came home and had no internet signal.  I called my ISP (cable), and we reset the modem/router several times.