Key from a String

Hi to all,
i have a big problem.
I must set an RSA key value (Modulus and Exponent) from a String conteining the encrypted value
( for example :hVqLzLgUeZTxQ95UdJDTpIwbf6F7v.... ).
Is possible to do this ?
I didn't found classes and method to do this from the API.
Somebody can help me?
thank you!

ghstark wrote:
z4c4gn0 wrote:
Hi to all,
i have a big problem.
I must set an RSA key value (Modulus and Exponent) from a String conteining the encrypted value
( for example :hVqLzLgUeZTxQ95UdJDTpIwbf6F7v.... ). Is possible to do this ?
I didn't found classes and method to do this from the API.
Somebody can help me?
I cannot offer much help without more clarifying details, though perhaps others can deduce what you need. Just from the little you have written, I might guess that you have a base64 encoded (*not* encrypted) string or strings containing the RSA modulus and exponent. In that case, I know sabre150 has shown what to do, so search this forum for posts containing keywords "XML " and "RSA". Also, examine the class http://java.sun.com/javase/6/docs/api/java/security/spec/RSAPublicKeySpec.html as well as the base64 decoders from the jakarta commons codex classes.
I must get the keyinfo from an XML Signed file, and use this parameters for sign another one, so
i have my class that return the String value of RSA Module and Exponent parsed.
Now i need to sign using this parameters, and i tried the RSAPublicKeySpec that you said
in this way:
String mod="blablalba"; //the string module parsed
String exp ="blablalba"; //the string exponend parsed
byte [] modbyte=mod.getBytes();
byte [] expbyte=exp.getBytes();
BigInteger modulus = new BigInteger(modbyte);
BigInteger publicExponent =new BigInteger(expbyte);
System.out.println(exp+" = "+publicExponent);
System.exit(0);
RSAPublicKeySpec keySpec = new RSAPublicKeySpec(modulus, publicExponent);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKey pk = (RSAPublicKey)keyFactory.generatePublic(keySpec);
that's work but don't return the right value of parameters, because Transform the strings in BigInteger.
What can i do?
thanks

Similar Messages

  • Finding the key according to string length in java.util.Properties

    Finding the key according to string length in java.util.Properties.
    I know only String length only.

    i need to retrieve the values from the java.util.properties.
    we know that we need to give the key value in order to retrieve the datas.
    but my problem is i will give the length of the key instead of giving the key value but i need to retrieve the datas according to the length of the key.

  • How can I get keys from Hashtable in the same order?

    Hello, everyone.
    I have a Hashtable containing key-value pairs, I need to get the keys in the same order as I use
    method put(key,value) to save the key-value pairs. But I can only find Hashtable.keys() to fetch the keys in form of Enumeration and when retrieve the keys from the Enumeration,they are not in the original order!
    The following is my code:
    Hashtable ht = new Hashtable();
    ht.put("Name","Harry Bott");
    ht.put("Gender","Male");
    ht.put("Age","25");
    String[] Items = new String[ht.size()];
    Enumeration e = ht.keys();
    int i = 0;
    while(e.hasMoreElements()) {
    Items[i++] =(String)(e.nextElement());
    The Items contains the keys but they are not in the original order.
    Does anyone know how to get the keys from a Hashtable in the same order when they're put?
    Thank you!

    yeah, another solution is to stored keys on a Collection at the same time you put them on the HashMap with its values.
    Then when ur going to retrieve objects from the Map u iterate the Collection that has the ordered keys and use them.

  • Constructing an ID from a String

    Hi all,
    I just want to ask for your opinion about a solution:
    Problem:
    I have a random size list of unique strings. Out of these strings I have to generate unique numeric IDs. The IDs can be of the type "long".
    My Solution (not every if and else... written)
    1. Create a char array with size 19 ( a var of type long has 19 characters) and init it with zeros...
    2. Get the hashcode of the unique string (type int) and fill it into the first half of the char array
    3. Because hashcodes are not unique I will now reverse the unique key (From "ABCD" to "DCBA") and make a second hashcode from it.
    4. Put the second hashcode in the second part of the char array.
    5. Construct a new long with the char array.
    Advantage:
    - "More" unique as a simple hashcode (sounds stupid)
    - faster as a encryption algorithm...
    Disadvantage:
    - not really unique
    Any comments or other suggestions?

    Thanks for your replies:
    Of course, the best way to accomplish this is to do a mapping between unique self-made IDs and the unique Strings in a mapping table, but this is not feasible in my case.
    I can't set an numeric ID to the object and make it persistent since the objects come from a legacy system without write back functionality.
    In my application I have to integrate those objects with our current datastructure and much of the logic depends on numeric IDs...
    Why 19 chars: a variable of type long in decimal form has 19 characters max. ( without -)
    I have to store the id in the database, where "bigint" is the required type as well.
    I know, that I will never have a real unique ID with this procedure, but since there are some other unique context parameters to differ the objects...
    The idea was just: if 2 strings have the same hashcodes the chance to have the same hashcodes backwards should be small enough. Are there any
    maths gurus out there ;-)

  • Need help for "From concatenate string insert to mysql table"

    Well, most of this problem is a question about SQL syntax. In the VALUES clause you put a comma delimited list of the values to go into the new record. You insert one record at a time. How are the columns defined? Have you done any study on basic SQL?
    Mike...

    i nid to insert values from concatenate string into mysql with using LabSQL, but the result come out from conatenate string is like " 2015-07-08 00:00:00 38.933235E-3" , a logged data of "Date Time Wind Speed(m/s). i nid to put these 3 values into 3 different column in mysql which is Date Time and Wind Speed. How can i pick Date to put inside Date's column, Time into Time's column and Wind Speed into Wind Speed's column in mysql ?
    What i do is
    INSERT INTO wind_speed_data (Date, Time, Wind_Speed) The space in Wind Speed can i put a _ in between Wind Speed? without _ and just put Wind Speed it shows errors.
    VALUES( i have no idea wat to key in at this part ) <--- nid help !
    The Mysql table. Date Time Wind Speed
    The result from concatenate string. Have to insert into mysql.
    My labview program.
    The error i facing.
     

  • How to read DES key from a file?

    I stored the DES key in the file as follows:
    KeyGenerator keygen = KeyGenerator.getInstance("DES");
    SecretKey Key = keygen.generateKey();
    FileOutputStream ostream = new FileOutputStream("t.tmp");
         ObjectOutputStream p = new ObjectOutputStream(ostream);
         p.writeObject(Key) ;
         p.flush();
         ostream.close();
    I don't know if there is problem with the above code, I am just new to java cryptography.
    I have problem read in the key and store it in the DES key object to be used for decryption.
    Can someone please tell me how to do it and a simple example will be appriciated.
    thanks
    Jeff

    Thank you for your help. after getting the key from the file( the output of the key is com.sun.crypto.provider.DESKey@fffe786d, not sure if it is right), I use this key to decrypt the message sent from the client program.
    here is the code:
    ObjectInputStream ois=new ObjectInputStream(data.getInputStream());
    String c = ois.readLine() ;//should I convert the byte[] data to String?
    ois.close() ;
    jTextField1.setText(c) ;//display the cipher text to the first textfield
    byte[] ciphertext = c.getBytes() ;
    // System.out.write(ciphertext) ;
    // get key from file
    FileInputStream in = new FileInputStream("t.tmp");
    ObjectInputStream oin = new ObjectInputStream(in);
    SecretKey Key = (SecretKey)oin.readObject();
    oin.close();
    in.close();
    System.out.println(Key) ;
    //decrypt
    Cipher C = Cipher.getInstance("DES");
    C.init(Cipher.DECRYPT_MODE, Key);
    // Decrypt the ciphertext
    byte[] cleartext1 =C.doFinal(ciphertext);
    System.out.write(cleartext1) ;//doesn't show anything!!
    System.out.println("this is cleartexxt");//doesn't even show this!!
    String display = new String(cleartext1);
    jTextField2.setText(display);
    why there is no output from System.out.write(cleartext1)? where did I go wrong?
    thank you.
    Jeff

  • CSConfigDotMacCert request to export key from key chain

    I updated Safari and iTunes (8.2.1) this evening and after rebooting a message requesting that CSConfigDotMacCert have access to key chain appeared. I presumed this was something to do with the iTunes update and clicked yes. However another message then appeared which requested the CSConfigDotMacCert wanted to export a key from my key chain. This seemed odd and I denied access. Does any one know whether this program should be allowed to export information from the key chain and if so why.
    Thanks

    Hi René.
    It might be because the fields contains a string value. You could try to use the NODIM function to remove the UOM from the keyfigures. Then they might appear as numbers in Excel. Another approach could be to add the UOM char (in this case "Currency/Unit" technical "1CUDIM") in the columns or rows. This removes the UOM from the key figure values too.
    Hope it helps.
    BR
    Stefan
    Message was edited by:
            Stefan Stefansson

  • Retrieving Key from array

    Hi
    I need a dynamic way of retrieving all the "keys" from a array.
    Found this which is exactly what I need but doesn't work as expected in my case:
    var myObject:Object = {key1:"value1",key2:"value2"}
    for (var s:String in myObject)
    trace("key:",s,"value:",myObject[s]);
    //key: key2 value: value2
    //key: key1 value: value1
    My case:
    var testArray:Array = new Array()
    testArray = DG1.dataProvider.toArray() // create array from dataprovider
    I've tested this array and it performs "correctly" as an array but when I try the above mentioned method it traces as follows:
    key: 0 value: [object Object] (key not being what I need)
    What I need:
    dgArr.push({partNo:event.target.data['partNo'+i],description:event.target.data['descriptio n'+i],cost:event.target.data['cost'+i]});               
    trace (????) //outputs = partNo, description, cost etc...
    Thanks for any help.

    your dataprovider values are also objects.  use:
    function listF(dp:DataProvider):void{
    for(var i:int=0;i<dp.length;i++){
    for(var s:String in dp.getItemAt(i)){
    trace(s,dp.getItemAt(i)[s]);

  • How do I generate a TripleDES key from the user's password?

    Is there any standard way to generate a Key (for TripleDES for example) using a user provided password? I want to store encripted data and I see TripleDes key has to be 24 bytes long, so how do I generate it consistently and safely from the user provided password?
    I know how to actually build a key with the keyfactory, I'm talking about the aproach to generate good keys from a user entered string. It can't be random keys since I have to store those encripted files and restore them later.

    Is there any standard way to generate a Key (for
    TripleDES for example) using a user provided
    password? I want to store encripted data and I see
    TripleDes key has to be 24 bytes long, so how do I
    generate it consistently and safely from the user
    provided password?
    I know how to actually build a key with the
    keyfactory, I'm talking about the aproach to generate
    good keys from a user entered string. It can't be
    random keys since I have to store those encripted
    files and restore them later.Hi , i�m having the same problem, i was wondering if yoy found any solution so far.
    I�ve tried this
    SecretKey symmetricKey = SecretKeyFactory.getInstance("DESede").generateSecret(new PBEKeySpec("mypassword".toCharArray()));But it returns java.security.spec.InvalidKeySpecException: Inappropriate key specification
    I have also tried to this:
    SecretKey symmetricKey = SecretKeyFactory.getInstance("PBEWithMD5AndTripleDES").generateSecret(new PBEKeySpec(password.toCharArray()));But it results on different byte arrays whenever i try to do the encrypting, i mean it allways returns different encryptatios. I suposed it could be becaus it�s using some kind of random, and i need to have always a specific result.

  • Need help with generating keys from xml

    Hello,
    I am just learning about JCE and am haveing some problems with implementing a basic program.
    I have the following information:
    <RSAKeyValue>
    <Modulus>Base64EncodedString</Modulus>
    <Exponent>Base64EncodedString</Exponent>
    <P>Base64EncodedString</P>
    <Q>Base64EncodedString</Q>
    <DP>Base64EncodedString</DP>
    <DQ>Base64EncodedString</DQ>
    <InverseQ>Base64EncodedString</InverseQ>
    <D>Base64EncodedString</D>
    </RSAKeyValue>
    From which I need to construct a public and private key. I am using RSA algorithm for the encrypting and decrypting. I am using the org.bouncycastle.jce.provider.BouncyCastleProvider provider. Any help would be greatly appreciated.
    My questions are:
    1) Is it possible to create the public and private key from this data?
    2) How can I construct a public and private key from this data.
    Thank you in advance.
    Sunit.

    Thanks for your help...I am still having problems.
    I am now creating the public and private keys. I am generating the public exp, modulus, private exp, and the encrypted text from another source.
    so my questions are:
    1) How do I verfiy that the private and public keys that I generate are valid?
    2) How do I get the decrypted text back in a readable form?
    3) the decrypted text should read "ADAM"
    Here is a test I wrote:
    _________________STARTCODE_____________________
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import java.math.BigInteger;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class CryptTester
         protected Cipher encryptCipher = null;
         protected Cipher decryptCipher = null;
         private KeyFactory keyFactory = null;
         protected PublicKey publicKey = null;
         protected PrivateKey privateKey = null;
         private RSAPublicKeySpec publicKeySpec = null;
         private RSAPrivateKeySpec privateKeySpec = null;
         public CryptTester()
              /* Create Cipher for asymmetric encryption (
              * e.g., RSA),
              try
                   encryptCipher = Cipher.getInstance("RSA", "BC");
                   System.out.println("Successfully got encrypt Cipher" );
                   decryptCipher = Cipher.getInstance("RSA", "BC");
                   System.out.println("Successfully got decrypt Cipher" );
                   keyFactory = KeyFactory.getInstance("RSA" , "BC");
                   System.out.println("Successfully got keyFactory" );
              }catch ( NoSuchAlgorithmException nsae)
                   System.out.println("Exception1: " + nsae.toString() );
              catch ( NoSuchPaddingException nspe)
                   System.out.println("Exception2: " + nspe.toString() );
              catch ( java.security.NoSuchProviderException nspe)
                   System.out.println("Exceptiont6: " + nspe.toString() );
              /* Get the private and public keys specs
              BigInteger publicMod = new BigInteger ("86e0ff4b9e95bc6dcbfd6673b33971d4f728218496adcad92021923a9be815ddb7ecf17c06f437634c62fa999a293da90d964172a21d8ce74bd33938994fbd93377f7d83ce93d523782639c75221a3c91b53927a081b2b089a61770c6d112d78d5da8a6abc452d39a276787892080d6cf17dd09537c1ec5551d89567345068ef", 16);
              BigInteger publicExp = new BigInteger ("5");
              BigInteger privateExp = new BigInteger ("50ed65fa2bf3710ead980a456b88dde62de4e0e9", 16);
              publicKeySpec = new java.security.spec.RSAPublicKeySpec( publicMod, publicExp );
              privateKeySpec = new java.security.spec.RSAPrivateKeySpec( publicMod, privateExp);
              try
                   privateKey = keyFactory.generatePrivate(privateKeySpec);
                   publicKey = keyFactory.generatePublic(publicKeySpec);
              }catch ( InvalidKeySpecException ivse)
                   System.out.println("Exception3: " + ivse.toString() );
              try
              * initialize it for encryption with
              * recipient's public key
                   encryptCipher.init(Cipher.ENCRYPT_MODE, publicKey );
                   decryptCipher.init(Cipher.DECRYPT_MODE, privateKey );
         }catch ( InvalidKeyException ivse)
                   System.out.println("Exception4: " + ivse.toString() );
         public String getPublicKey()
              //return new String(publicKey.getEncoded());
              return publicKey.toString();
         public String getPrivateKey()
         //          return new String(privateKey.getEncoded());
              return privateKey.toString();
         public String encryptIt(String toencrypt)
              * Encrypt the message
              try
                   byte [] result = null;
                   try
                        result = encryptCipher.doFinal(toencrypt.getBytes());
                   catch ( IllegalStateException ise )
                        System.out.println("Exception5: " + ise.toString() );
                   return new String(result);
              }catch (Exception e)
                   e.printStackTrace();
              return "did not work";
         public String decryptIt(String todecrypt)
                        * decrypt the message
              try
                   byte [] result = null;
                   try
                        result = decryptCipher.doFinal(todecrypt.getBytes());
                   catch ( IllegalStateException ise )
                        System.out.println("Exception6: " + ise.toString() );
                   return new String(result);
              }catch (Exception e )
                   e.printStackTrace() ;
              return "did not work";
         public static void main(String[] args)
              try
              Security.addProvider(new BouncyCastleProvider());
              CryptTester tester = new CryptTester();
              String encrypted = "307203c3f5827266f5e11af2958271c4";
              System.out.println("Decoding string " + encrypted + "returns : " + tester.decryptIt(encoded) );
              } catch (Exception e)
                   e.printStackTrace();
    _________________ENDPROGRAM_____________________

  • Replacing a set of characters from a string in oracle sql query

    I want to replace a set of characters ( ~    !     @    #     $     %     ^     *     /     \     +    :    ;    |     <     >     ?    _  ,) from a STRING in sql
    select 'TESTING ! ABC 123 #'
    FROM DUAL;
    What is the best way to do it? Please provide examples also.

    What is your expected output... The query I posted just removes them, it never replaces them with spaces..your string already has space.. if you want to remove space as well .. try this...
    SELECT TRANSLATE ('TESTING ! ABC 123 #', '-~!@#$%^*/\+:;|<>?_, ', ' ') FROM DUAL;
    Output:
    --TESTINGABC123
    Else post your expected output..
    Cheers,
    Manik.

  • Problems with Reflection API and intantiating an class from a string value

    I want to instantiate a class with the name from a String. I have used the reflection api so:
    static Object createObject(String className) {
    Object object = null;
    try {
    Class classDefinition = Class.forName(className);
    object = classDefinition.newInstance();
    } catch (InstantiationException e) {
    System.out.println(e);
    } catch (IllegalAccessException e) {
    System.out.println(e);
    } catch (ClassNotFoundException e) {
    System.out.println(e);
    return object;
    Let's say my class name is "Frame1".
    and then if i use:
    Frame1 frm = (Frame1) createObject("Frame1");
    everything is ok but i cannot do this because the name "Frame1" is a String variable called "name" and it doesn't work like:
    name frm = (name) createObject("Frame1");
    where i'm i mistaking?
    Thanks very much!

    i have understood what you have told me but here is a little problem
    here is how my test code looks like
    Class[] parameterTypes = new Class[] {String.class};
    Object frm = createObject("Frame1");
    Class cls = frm.getClass();
    cls.getMethod("pack",parameterTypes);
    cls.getMethod("validate",parameterTypes);
    everything works ok till now.
    usually if i would of had instantiated the "Frame1" class standardly the "cls" (or "frm" in the first question ) object would be an java.awt.Window object so now i can't use the function (proprietary):
    frame_pos_size.frame_pos_size(frm,true);
    this function requires as parameters: frame_pos_size(java.awt.Window, boolean)
    because my cls or frm objects are not java.awt.Window i really don't find any solution for my problem. I hope you have understood my problem. Please help. Thanks a lot in advance.

  • How can i store values from my String into Array

    Hi guys
    i wants to store all the values from my string into an array,,,, after converting them into intergers,,,, how i can do this becs i have a peice of code which just give me a value of a character at time,,,,charat(2)...BUT i want to the values from String to store in an Array
    here is my peice of code which i m using for 1 char at time
    int[] ExampleArray2 = new int[24];
    String tempci = "Battle of Midway";
    for(int i=0;i>=tempci.length();i++)
    int ascii = tempci.charAt(i); //Get ascii value for the first character.

    public class d1
         public static final void main( String args[] )
              int[] ExampleArray2 = new int[24];
              String tempci = "Battle of Midway";
              for(int i=0;i<tempci.length();i++)
                   int ascii = tempci.charAt(i);
                   ExampleArray2=ascii;
              for(int i=0;i<ExampleArray2.length;i++)
                   System.out.println(ExampleArray2[i]);

  • Get all keys from Cache

    Hi,
    I have a scenario where I have a backing store attached to the cache and running the server in a fault tolerant mode. Because of fault tolerance when a new node joins the cluster it is required to recover the data from the cache. When using NamedCache.keySet() I get only the keys which are in the cache and not the ones persisted in the Backing store.
    How do I go about getting the whole set of keys from the cache and backing store using the Tangosol API ?

    Here is my cache-config file. The CacheStore implementation is quite big and I need to check with my manager to share it on the forum. Maybe this will continue through the regular support channel.
    Message was edited by: pkdhar<br><br> <b> Attachment: </b><br>coherence-cache-config.xml <br> (*To use this attachment you will need to rename 465.bin to coherence-cache-config.xml after the download is complete.)

  • Getting char values from a string problem

    Hi,
    Here's an example of what I'm trying to do:
    boolean loopSwitch = true;
    while (loopSwitch)
         String orderDecider = JOptionPane.showInputDialog (null, "Would you like your numbers to be ordered in   ascending or descending order(A/D)",      "Order decision", JOptionPane.QUESTION_MESSAGE);
         if (orderDecider == A)
         loopSwitch = false;
         }I basically want the user to input either a/A/d/D and to get the char values from the string so I can use them in an if statement.
    Basically, I wanna parse the string into a char.
    Is this possible?
    Thanks.
    Edited by: xcd on Oct 16, 2009 8:38 AM

    Why not just use the String.equals() method to compare a String to a String?
    But if you must, you can use the String.charAt() method to return a char at a particular location in the String.
    Note: char literals need to be surrounded by single quotes ('A') and String literals need to be surrounded by double quotes ("A").

Maybe you are looking for

  • Pls help...How to pass a executed value to a variable?

    hi everyone im new here.. ok im having prob in passing the executed value of a string into a variable for me to manupulate the value. sample codes as below : declare @Str varchar(500) declare @Str1 varchar(50) declare @Int varchar(50) declare @Str2 v

  • " STEPS TO  CREATE SELECTION CRITERIA IN WEBI-REPORTS ! "

    Hai friends ,                             Let me know the procedure  to create a Selection Criteria on the webi-reports . Based on the Selection criteria, I should execute the report.

  • Conected ipod to pc all songs gone please help

    **Hi ALL,** **Need help please, my hard drive died on the computer so i replaced it went to sign in on the itunes store and went to sync and all of my songs,photos,games have gone from my ipod is there any way i can get them all back????** **Please h

  • LR3 Won't Open Images in CS5!

    Hello! I've been running both LR3 and CS5 for months and months, and now suddenly, when I go to "Edit in Photoshop CS5..." an image, it won't open in CS5! It always worked great before. Now, instead, CS5 does nothing, or throws up an open dialogue bo

  • Sound files from Keynote (or Powerpoint 2004) do not work in Windows

    I have spent many hours designing slide shows in both Keynote & Powerpoint 2004 on my MAC that include sound and they work great. HOWEVER, all slide shows I send to Windows users NEVER get the SOUND files. HELP>>>>>>