Can't generate random KeyPair

Hi all,
i tried with the following code to generate a random RSA KeyPair.
But it is always the same keypair generated. What i'm doing wrong?
SecureRandom random = new SecureRandom();
random.setSeed(System.currentTimeMillis());
KeyPairGenerator pairGen = KeyPairGenerator.getInstance("RSA", "BC");
pairGen.initialize(1024, random);
KeyPair keyPair = pairGen.generateKeyPair();
I tried also this way to create a SecureRandom, but with same result:
SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
Thanks for Help!
Regards turjalei

To check RSA keys for equality, you need to see if their modulus and exponent are the same. Comparing keyPair.toString() will NOT do that - and I'm not sure that keyPair.equals() will do it either.
Here's a quick-and-dirty way to eyeball generated keys and see that they are, in fact, different:import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import org.bouncycastle.util.encoders.Base64;
public class CipherHandler {
    public static void main(String[] args) {
        try {
            SecureRandom random = new SecureRandom();
            random.setSeed(System.currentTimeMillis());
            KeyPairGenerator pairGen =
                KeyPairGenerator.getInstance("RSA", "BC");
            pairGen.initialize(1024, random);
            KeyPair keyPair = pairGen.generateKeyPair();
            byte[] pubEnc = keyPair.getPublic().getEncoded();
            String b64Str = new String(Base64.encode(pubEnc), "ASCII");
            System.out.println("pub one = " + b64Str);
            keyPair = pairGen.generateKeyPair();
            pubEnc = keyPair.getPublic().getEncoded();
            b64Str = new String(Base64.encode(pubEnc), "ASCII");
            System.out.println("pub two = " + b64Str);
        } catch (Exception e) {
            e.printStackTrace();
}When you compare the resulting Base64'd strings, you'll note that they are in fact different...
Good luck!
Grant

Similar Messages

  • How can I generate random password

    Hello...
    I use oracle 10g for windows,,,I have an employee table , there are a lot of colunms , their names are employee_name , employee_id ,employee_pass .....
    employee_pass colunm is empty
    I want to generate random password for employee_pass colunm
    How can I generate random password for employee_pass colunm
    thanks
    omer faruk akyuzlu
    in Turkey

    SQL>  exec dbms_random.seed(to_char(sysdate, 'sssss'))
    PL/SQL procedure successfully completed.
    SQL> select dbms_random.string('X', 8) from dual
      2  /
    DBMS_RANDOM.STRING('X',8)
    4YT1H150
    SQL> select dbms_random.string('X', 8) from dual
      2  /
    DBMS_RANDOM.STRING('X',8)
    WIA3QCIP
    SQL> Please be aware that storing the actual passwords in a the EMPLOYEES table is a very bad idea. Oracle has a pretty good password implementation. It's not perfect but it's a darn site better than hand-rolling our own.
    Cheers, APC

  • Generate random Doubles in a range

    how can i generate random numbers (type double) in an interval [a,b] ?

    VafCat wrote:
    ex: i want to generate numbers in this range: [a,b] = [1.648,7.389]
    and i think i solved with:
    double r = (b-a)*generator.nextDouble() + a;If it's three digits of precision you want, then you should generate an integer between 1648 and 7389 and divide it by 1000

  • Generating random text for placeholders in Pages

    In the templates that come with Pages the text placeholders are all in Latin, which I think looks quite professional. My question is: how can I generate random Latin text, like in the templates?
    Thanks
      Mac OS X (10.4.7)  

    You can also use the nifty freeware MacLorem, which will generate random Latin text with various specifiable qualities (and can produce mock text for various other "languages").

  • Does anyone can create a random guest account more than 10 ?

    Hi, Experts
    I'm currently using ISE 1.1.1 to demonstration with my customer. In the sponsor page, does anyone can create the random guest to be more than 10 accounts at a time ?
    I have try to create with 20 accounts then get the error as below,
    Internal error encountered.  Please contact administrator or help desk.
    However the random accounts are created only 10 accounts.
    Since the system said that it can create from 1 up to 10,000 accounts.
    Thanks,
    Pongsatorn Maneesud

    Hi,
    I just tested this and I was able to generate 20 accounts successfully. Do you have patch 1 installed on your ISE node? Also what group is your sponsor account mapped to? I used an account that is mapped to the SponsorAllAccount group.

  • Generating random questions without duplication

    I have 10 questions in my java program,
    I can get them randomly generated but how can I do without duplication ?
    Any help much appreciated

    My approach would be, when you first generate the questions put them in a List. Then use java.util.Collections.shuffle(List) to randomize the List.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html#shuffle(java.util.List)
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/List.html

  • Generate random User Alias - Entity adapter

    Hi,
    I am a newbie. Can anyone please help me in telling steps for creating an Entity Adapter which generate a random User Alias.
    TIA.
    Got few threads that tell about pre-populate adapter, none for entity adapter.

    Hi,
    Follow the below steps to create new entity adapter in OIM
    To add the new created event handler to OIM server, perform the following steps:
    1. Write a java code to perform the needed operation ("Generate random user alias" in your case).
    2. Copy the file to OIM_HOME\xellerate\EventHandlers
    3. Open Design Console and navigate to: Development Tools -> Business Rule Definition -> Event Handler Manager
    4. Create a new Event Handler and specify:
    Event Handler Name: +<give the class name of your code>+
    Package: +<give the package name of your code>+
    Pre-Insert: Checked (for this scenario)
    5. Save the event handler
    6. Navigate to Development Tools -> Business Rule Definition -> Data Object Manager
    7. Search for "Users" and add the event handler to the Pre-Insert list.
    8. Save.
    Regards,
    NS

  • How to create a javabean that generate random password?

    May i know how to create a javabean that can generate random password?
    that include character and string
    and length of 10.

    i created a class file for my java bean
    package autogenerate;
    import java.util.*;
    public class GeneratePwId
    private int MemId;
    private String Passwd;
    public GeneratePwId(){}
    public String getPasswd()
    return this.Passwd;
    public void setPasswd()
    char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
    'J', 'K', 'L', 'M', 'N', 'P', 'R', 'T',
    'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
    'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
    'm', 'n', 'p', 'q', 'r', 's', 't', 'u',
    'v', 'w', 'x', 'y', 'z', '0', '1', '2',
    '3', '4', '5', '6', '7', '8', '9' } ;
    String pwd = "" ;
    while( pwd.length() < 10 )
    pwd += letters[ (int)( Math.random() * letters.length ) ] ;
    this.Passwd = pwd;
    i successfully compile my java file. and try to test it by writing a jsp file.
    here is my jsp code
    <html>
    <head>
    <title>
    Try retrieving password
    </title>
    </head>
    <body>
    <jsp:useBean class"autogenerate.GeneratePwId" id="bean0" scope="page"/>
    <%=bean0.getPasswd()%>
    </body>
    </html>
    but i encounter this error
    org.apache.jasper.compiler.ParseException: /jsp/GetPasswd.jsp(7,18) Attribute class has no value
    anyone can teach me how to solve this problem?
    thanks a alot!

  • Could not generate DH keypair error

    hi,
    My coding was running fine with JDK 1.41.3 but when i am trying to use jdk 1.5 its giving me an error
    "RuntimeException : Cound not generate DH keypair: in the method call sslSock.startHandshake();
    what could cause this ?

    Did you get any replies to this? If so, can you pass it along?
    We are having the same issue. Everything was fine with 1.4. With 1.5, on the server side, we get the following error:
    javax.net.ssl.SSLException: Received fatal alert: internal_error
    The server code is:
    SSLServerSocket ss = null;
    try {
    KeyManagerFactory kmf;
    KeyManager[] km;
    KeyStore ks;
    TrustManagerFactory tmf;
    TrustManager[] tm;
    SSLContext sslc;
    // Create a keystore that will read the JKS (Java KeyStore)
    // file format which was created by the keytool utility.
    ks = KeyStore.getInstance("JKS");
    // Load the keystore object with the binary keystore file and
    // a byte array representing its password.
    ks.load(url.openStream(), keystorepass);
    // Gives us a factory for key managers that will let
    // us handle the asymetric keys we created earlier.
    kmf = KeyManagerFactory.getInstance("sunx509");
    // Initialize the key manager factory with the keystore object,
    // again using the same password for security since it is going to
    // access the private key.
    kmf.init(ks, keystorepass);
    // Now we can get the key managers from the factory, since it knows
    // what type we are using now.
    km = kmf.getKeyManagers();
    // Next, create a trust manager factory using the same algorithm.
    // This is to avoid using the certificates in cacerts that
    // represent an authentication security risk.
    tmf = TrustManagerFactory.getInstance("sunx509");
    // ...then initialize it with the keystore object. This time we don't
    // need the keystore password. This is because trusted certificates
    // are not a sensitive element in the keystore, unlike the
    // private keys.
    tmf.init(ks);
    // Once that's initialized, get the trust managers from the factory.
    tm = tmf.getTrustManagers();
    // Almost done, we need a context object that will get our
    // server socket factory. We specify TLS to indicate that we will
    // need a server socket factory that supports SSL.
    sslc = SSLContext.getInstance("TLS");
    // Initialize the context object with the key managers and trust
    // managers we got earlier. The third parameter is an optional
    // SecureRandom object. By passing in null, we are letting the
    // context object create its own.
    sslc.init(km, tm, null);
    // Finally, we get the ordinary-looking server socket factory
    // from the context object.
    ServerSocketFactory ssf = sslc.getServerSocketFactory();
    SSLServerSocket serversocket = (SSLServerSocket)
    ssf.createServerSocket(port);
    serversocket.setNeedClientAuth(true);
    ss = serversocket;
    } catch (Exception e) {
    SeedServer._logger.error("Unable to create server socket:" + e.getMessage());
    System.exit(-1);
    while(true) {
    SSLSocket socket = null;
    try {
    socket = (SSLSocket) ss.accept();
    System.out.println("Accepted connection from " +
    socket.getInetAddress().getHostAddress() +
    ":" + socket.getPort());
    handleConnection(socket.getInputStream(), socket.getOutputStream());
    } catch (SocketTimeoutException ste) {
    // Error message
    } catch (SocketException se) {
    // Error message
    } catch (Exception e) {
    // Error message -- This is the one thats triggered
    } catch (Throwable t) {
    // Error message
    } finally {
    try {
    if (socket != null)
    socket.close();
    catch (Exception e) {
    The client code is:
    SSLSocketFactory ssf = null;
    try {
    KeyManagerFactory kmf;
    KeyStore ks;
    TrustManagerFactory tmf;
    SSLContext sslc;
    kmf = KeyManagerFactory.getInstance("sunx509");
    ks = KeyStore.getInstance( "JKS" );
    ks.load(url.openStream(), keystorepass);
    kmf.init(ks, keystorepass);
    tmf = TrustManagerFactory.getInstance("sunx509");
    tmf.init(ks);
    sslc = SSLContext.getInstance("TLS");
    sslc.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    // The process is different from here on the client. Instead of
    // getting a ServerSocketFactory, we ask for a SocketFactory from
    // the SSL context.
    ssf = sslc.getSocketFactory();
    } catch (Exception e) {
    System.out.println("Unable to initialize SSL parameters");
    System.exit(-1);
    }

  • Generate Random Number By sequence

    How to generate random 4 digit random number using sequence or any other method. Please suggest

    4 digit random numbers can be obtained by:
    SQL> SELECT TRUNC(DBMS_RANDOM.VALUE(1000,9999)) FROM DUAL;
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4002
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4748
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   8328
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   3667
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   7464
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4893
    SQL> /
    TRUNC(DBMS_RANDOM.VALUE(1000,9999))
                                   4961In mine case there is no repetition using Oracle 11.2.0.1 on Windows XP.
    Regards
    Girish Sharma

  • Generate Random number at VB6

    Thank you for reading below scenario:
    assume user will input 4 digits number to a text
    Input Number : 1119
    and I'll create a command button, after click on the command button it will generate above number
    Generate : 1119
    1191
    1911
    9111
    I did using "Randomize" but it generate the same number as result... .Can anyone give me an idea how to generate random number using Visual Basic as the above scenario?
    Thank's a lot

    The first thing to do is to rewrite in PHP.
    -- CJ

  • How to generate random number

    Hi I am trying to generate a random number between 0 to 100. Anyone know how to do this. I know we can use the Random class, but I don't know how to implement it between 0 and 100.
    Thanks

    XPOST:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=547130&tstart=0&trange=15
    http://forum.java.sun.com/thread.jsp?forum=31&thread=547129&tstart=0&trange=15

  • Generating random number within size of map problem (why me!!) ?

    Hi Guys,
    I'm trying to generator random numbers between 0 and a map width and another random number between 0 and a map height i.e if the map width was 3 i can generator 0,1,2.
    The coding i am using to do this is :
    int randomCol;
    int randomRow;
    randomCol = newMapWidth - 0 + 1;
    int itemp = generator.nextInt() % randomCol;
    if (itemp < 0)
          itemp = -itemp;
    randomCol = 0 + itemp;
    randomRow = newMapHeight - 0 + 1;
    int jtemp = generator.nextInt() % randomRow;
    if (jtemp < 0)
         jtemp = -jtemp;
    randomRow = 0 + jtemp;I've had a look at similar problems and searched penalty but can't seem to get it right for whatever way i implement. It leads to some array out of bound errors.
    If any can help me resolve this problem it would be greatly appreciated.
    Thanks A lot !

    Hippolyte wrote:
    randomRow = 0 + jtemp;I'll bite: what's the "0 + " voodoo for?It?s for clarity and Code readability, I guess. @OP: Random.nextFloat() generates numbers from 0.0f to 1.0f. Multiplying this number with your max value will generate a number between 0 and that given max value. BTW, you can generate numbers from -a to a by using (Random.nextFloat()- .5f) * (2 * a).
    Shazaam.

  • Need help with codings on generating random words

    hi guys.. i need help with generating random words from a list of array. please help me with the codings.. let me know the other variables that are needed if required as well.. thanks a million..
    private String wordList[] = { "abstraction", "command", "arithmetic", "backslash" };

    Hi,
    You can use the Random class to generate Random number between 0 to the array length and use the generated random number as index in to the Strign array.
    To generate Random number use the following code
    Random r = new Random();
    num = ((r.nextInt() >>> 1) % wordList.length);
    num will have the randomly generated number.

  • Generate random new GUID for Config Manager Client?

    How can I generate a random new GUID for Config Manager 2012 R2 client.?
    I tried by deleting smscgf.ini, by using RESETKEYINFORMATION=True switch and also by doing a force reinstall of client, but the same GUID persists.
    Any help is appreciated. Thanks

    More info:
    System Center Configuration Manager Duplicate GUID for Clients
    http://kamalakannansccmblog.wordpress.com/2013/04/28/system-center-configuration-manager-duplicate-guid-for-clients/
    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.

Maybe you are looking for

  • Optimzing, Defragmenting,etc. on the Macmini

    Hi all, I'd like your thoughts on optimizing and defragmenting the Mac mini to perform at tip top shape and prevent any viruses. I have cocktail software but havent really learned the ins and outs. Thanks for your help, web dude

  • Noise on line and long disconnects since repair

    Hi there. I posted on here previously. Had a major line fault just after activation. Basically something blew and the line died as soon as I tried to use bb but a line check showed as ok. Based on advice on here, arranged for an open reach engineer t

  • Connecting to ABAP Trial Version

    Hi all, I am able to install the trial version. I can connect and login and work from the same computer. I have another computer and I would like to connect from the second computer to this one. I am trying to connect from a windows xp box and Trial

  • Including a variable in cmax

    This is a very simple one... but it is slowly driving me mad. I have some data, i want to know the maximum, but i want to go through several channels so i'm using a variable for my channel number.... Option Explicit  'Forces the explicit declaration

  • HOW TO INSTALL GCC 3.4.6 IN A SOLARIS10 SERVER

    I am trying to install gcc-3.4.6 into a Solaris 10 Server, I always get a problem : after doing: mkdir objdir cd objdir ../configure with-as=/usr/ccs/bin/as with-ld=/usr/ccs/bin/ld *** The command 'cc -o conftest -g conftest.c' failed. *** You must s