List of usage examples for org.apache.commons.lang RandomStringUtils randomNumeric
public static String randomNumeric(int count)
Creates a random string whose length is the number of characters specified.
Characters will be chosen from the set of numeric characters.
From source file:org.ejbca.core.model.ca.caadmin.CVCCA.java
/** * @param sequence an optional requested sequence number (serial number) for the certificate. If null a random sequence will be generated. * requestX509Name is never used./*from ww w. j ava 2s . c o m*/ */ public Certificate generateCertificate(UserDataVO subject, X509Name requestX509Name, PublicKey publicKey, int keyusage, Date notBefore, Date notAfter, CertificateProfile certProfile, X509Extensions extensions, String sequence) throws Exception { if (log.isTraceEnabled()) { log.trace(">generateCertificate(" + notBefore + ", " + notAfter + ")"); } // Get the fields for the Holder Reference fields // country is taken from C in a DN string, mnemonic from CN in a DN string and seq from SERIALNUMBER in a DN string String country = CertTools.getPartFromDN(subject.getCertificateDN(), "C"); String mnemonic = CertTools.getPartFromDN(subject.getCertificateDN(), "CN"); String seq = sequence; if (seq == null) { log.info("No sequence in request, using random 5 number sequence."); seq = RandomStringUtils.randomNumeric(5); } if (seq.length() > 5) { log.info("Sequence " + seq + " is too long, only using first 5."); seq = seq.substring(0, 4); } if (seq.length() < 5) { log.info("Sequence " + seq + " is too short, padding with zeroes."); for (int i = seq.length(); i < 5; i++) { seq = "0" + seq; } } // The DN 'CN=00111,O=CVCA-RPS,C=SE' will make the following reference //HolderReferenceField holderRef = new HolderReferenceField("SE","CVCA-RPS","00111"); HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq); // Check if this is a root CA we are creating boolean isRootCA = false; if (certProfile.getType() == CertificateProfile.TYPE_ROOTCA) { isRootCA = true; } // Get CA reference CardVerifiableCertificate cacert = (CardVerifiableCertificate) getCACertificate(); // Get certificate validity time notBefore and notAfter CertificateValidity val = new CertificateValidity(subject, certProfile, notBefore, notAfter, cacert, isRootCA); // We must take the issuer DN directly from the CA-certificate, if we are not creating a new Root CA CAReferenceField caRef = null; AuthorizationRoleEnum authRole = AuthorizationRoleEnum.IS; if (isRootCA) { // This will be an initial root CA, since no CA-certificate exists if (log.isDebugEnabled()) { log.debug("Using Holder Ref also as CA Ref, because it is a root CA"); } caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(), holderRef.getSequence()); log.debug("Using AuthorizationRoleEnum.CVCA"); authRole = AuthorizationRoleEnum.CVCA; } else { if (log.isDebugEnabled()) { log.debug("Using CA Ref directly from the CA certificates Holder Ref"); } HolderReferenceField hr = cacert.getCVCertificate().getCertificateBody().getHolderReference(); caRef = new CAReferenceField(hr.getCountry(), hr.getMnemonic(), hr.getSequence()); if (certProfile.getType() == CertificateProfile.TYPE_SUBCA) { // If the holder DV's country and the CA's country is the same, this is a domestic DV // If the holder DV's country is something else, it is a foreign DV if (StringUtils.equals(caRef.getCountry(), holderRef.getCountry())) { authRole = AuthorizationRoleEnum.DV_D; log.debug("Using AuthorizationRoleEnum.DV_D"); } else { authRole = AuthorizationRoleEnum.DV_F; log.debug("Using AuthorizationRoleEnum.DV_F"); } } } AccessRightEnum accessRights = AccessRightEnum.READ_ACCESS_NONE; int rights = certProfile.getCVCAccessRights(); log.debug("Access rights in certificate profile: " + rights); switch (rights) { case CertificateProfile.CVC_ACCESS_DG3: accessRights = AccessRightEnum.READ_ACCESS_DG3; break; case CertificateProfile.CVC_ACCESS_DG4: accessRights = AccessRightEnum.READ_ACCESS_DG4; break; case CertificateProfile.CVC_ACCESS_DG3DG4: accessRights = AccessRightEnum.READ_ACCESS_DG3_AND_DG4; break; case CertificateProfile.CVC_ACCESS_NONE: accessRights = AccessRightEnum.READ_ACCESS_NONE; break; } // Generate the CVC certificate using Keijos library CATokenContainer catoken = getCAToken(); String sigAlg = catoken.getCATokenInfo().getSignatureAlgorithm(); log.debug("Creating CV certificate with algorithm " + sigAlg + ", using provider " + catoken.getProvider() + ", public key algorithm from CVC request must match this algorithm."); log.debug("CARef: " + caRef.getConcatenated() + "; holderRef: " + holderRef.getConcatenated()); CVCertificate cvc = CertificateGenerator.createCertificate(publicKey, catoken.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN), sigAlg, caRef, holderRef, authRole, accessRights, val.getNotBefore(), val.getNotAfter(), catoken.getProvider()); if (log.isDebugEnabled()) { log.debug("Certificate: " + cvc.toString()); log.debug("Certificate bytes: " + new String(Base64.encode(cvc.getDEREncoded()))); } CardVerifiableCertificate retCert = new CardVerifiableCertificate(cvc); // Verify certificate before returning retCert.verify(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN)); if (log.isTraceEnabled()) { log.trace("<generateCertificate()"); } return retCert; }
From source file:org.ejbca.core.protocol.ws.client.CvcRequestCommand.java
/** * Runs the command//from ww w . jav a2 s .co m * * @throws IllegalAdminCommandException Error in command args * @throws ErrorAdminCommandException Error running command */ public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException { try { if (args.length < 9 || args.length > 11) { getPrintStream().println("Number of arguments: " + args.length); usage(); System.exit(-1); // NOPMD, this is not a JEE app } String username = args[ARG_USERNAME]; String userpassword = args[ARG_PASSWORD]; String dn = args[ARG_SUBJECTDN]; String sequence = args[ARG_SEQUENCE]; String signatureAlg = args[ARG_SIGNALG]; String keySpec = args[ARG_KEYSPEC]; boolean genrequest = args[ARG_GENREQ].equalsIgnoreCase("true"); String basefilename = args[ARG_BASEFILENAME]; String authSignKeyFile = null; if (args.length > (ARG_AUTHSIGNKEY)) { authSignKeyFile = args[ARG_AUTHSIGNKEY]; } String authSignCertFile = null; if (args.length > (ARG_AUTHSIGNCERT)) { authSignCertFile = args[ARG_AUTHSIGNCERT]; } getPrintStream().println("Enrolling user:"); getPrintStream().println("Username: " + username); getPrintStream().println("Subject name: " + dn); getPrintStream().println("Sequence: " + sequence); getPrintStream().println("Signature algorithm: " + signatureAlg); getPrintStream().println("Key spec: " + keySpec); try { CryptoProviderTools.installBCProvider(); String cvcreq = null; if (genrequest) { getPrintStream().println("Generating a new request with base filename: " + basefilename); // Generate keys for the request String keytype = "RSA"; if (signatureAlg.contains("ECDSA")) { keytype = "ECDSA"; } KeyPair keyPair = KeyTools.genKeys(keySpec, keytype); String country = CertTools.getPartFromDN(dn, "C"); String mnemonic = CertTools.getPartFromDN(dn, "CN"); if (sequence.equalsIgnoreCase("null")) { sequence = RandomStringUtils.randomNumeric(5); getPrintStream().println("No sequence given, using random 5 number sequence: " + sequence); } //CAReferenceField caRef = new CAReferenceField(country,mnemonic,sequence); CAReferenceField caRef = null; // Don't create a caRef in the self signed request // We are making a self signed request, so holder ref is same as ca ref HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, sequence); CVCertificate request = CertificateGenerator.createRequest(keyPair, signatureAlg, caRef, holderRef); byte[] der = request.getDEREncoded(); if (authSignKeyFile != null) { getPrintStream().println("Reading private key from pkcs8 file " + authSignKeyFile + " to create an authenticated request"); byte[] keybytes = FileTools.readFiletoBuffer(authSignKeyFile); KeyFactory keyfact = KeyFactory.getInstance(keytype, "BC"); PrivateKey privKey = keyfact.generatePrivate(new PKCS8EncodedKeySpec(keybytes)); KeyPair authKeyPair = new KeyPair(null, privKey); // We don't need the public key // Default caRef if we do not pass in a certificate to get caRef from CAReferenceField authCaRef = new CAReferenceField(country, mnemonic, sequence); CVCertificate authCert = null; if (authSignCertFile != null) { getPrintStream().println("Reading cert from cvcert file " + authSignCertFile + " to create an authenticated request"); CVCObject parsedObject = CvcPrintCommand.getCVCObject(authSignCertFile); authCert = (CVCertificate) parsedObject; String c = authCert.getCertificateBody().getHolderReference().getCountry(); String m = authCert.getCertificateBody().getHolderReference().getMnemonic(); String s = authCert.getCertificateBody().getHolderReference().getSequence(); authCaRef = new CAReferenceField(c, m, s); } CVCAuthenticatedRequest authRequest = CertificateGenerator .createAuthenticatedRequest(request, authKeyPair, signatureAlg, authCaRef); // Test to verify it yourself first if (authCert != null) { getPrintStream().println("Verifying the request before sending it..."); PublicKey pk = KeyTools.getECPublicKeyWithParams( authCert.getCertificateBody().getPublicKey(), keySpec); authRequest.verify(pk); } der = authRequest.getDEREncoded(); } cvcreq = new String(Base64.encode(der)); // Print the generated request to file FileOutputStream fos = new FileOutputStream(basefilename + ".cvreq"); fos.write(der); fos.close(); getPrintStream().println("Wrote binary request to: " + basefilename + ".cvreq"); fos = new FileOutputStream(basefilename + ".pkcs8"); fos.write(keyPair.getPrivate().getEncoded()); fos.close(); getPrintStream().println("Wrote private key in " + keyPair.getPrivate().getFormat() + " format to to: " + basefilename + ".pkcs8"); } else { // Read request from file getPrintStream().println("Reading request from filename: " + basefilename + ".cvreq"); byte[] der = FileTools.readFiletoBuffer(basefilename + ".cvreq"); cvcreq = new String(Base64.encode(der)); } // Edit a user, creating it if it does not exist // Actually don't do that, leverage the existing commands and force to use the editUser command instead. // This also makes this CLI exactly represent the actual WS-API call // getEjbcaRAWS().editUser(userdata); getPrintStream().println("Submitting CVC request for user '" + username + "'."); getPrintStream().println(); // Use the request and request a certificate List<Certificate> resp = getEjbcaRAWS().cvcRequest(username, userpassword, cvcreq); // Handle the response Certificate cert = resp.get(0); byte[] b64cert = cert.getCertificateData(); CVCObject parsedObject = CertificateParser.parseCertificate(Base64.decode(b64cert)); CVCertificate cvcert = (CVCertificate) parsedObject; FileOutputStream fos = new FileOutputStream(basefilename + ".cvcert"); fos.write(cvcert.getDEREncoded()); fos.close(); getPrintStream().println("Wrote binary certificate to: " + basefilename + ".cvcert"); getPrintStream().println("You can look at the certificate with the command cvcwscli.sh cvcprint " + basefilename + ".cvcert"); } catch (AuthorizationDeniedException_Exception e) { getPrintStream().println("Error : " + e.getMessage()); } catch (UserDoesntFullfillEndEntityProfile_Exception e) { getPrintStream() .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage()); } } catch (Exception e) { if (e instanceof EjbcaException_Exception) { EjbcaException_Exception e1 = (EjbcaException_Exception) e; getPrintStream() .println("Error code is: " + e1.getFaultInfo().getErrorCode().getInternalErrorCode()); } throw new ErrorAdminCommandException(e); } }
From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java
public void execute(String[] args) throws ErrorAdminCommandException { if (args.length < 4) { getLogger().info("Description: " + getDescription()); getLogger().info(/* ww w . ja va 2 s .c o m*/ "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>"); getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA."); getLogger().info("Usage 2: " + getCommand() + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>"); getLogger().info( " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA."); getLogger().info( " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc."); getLogger().info( " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated."); return; } try { String caName = args[1]; String pkFile = args[2]; String certFile = args[3]; // Import key and certificate CryptoProviderTools.installBCProvider(); byte[] pkbytes = FileTools.readFiletoBuffer(pkFile); PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes); KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well PrivateKey privKey = keyfact.generatePrivate(spec); byte[] certbytes = FileTools.readFiletoBuffer(certFile); Certificate cert = null; try { // First check if it was a PEM formatted certificate Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes)); cert = certs.iterator().next(); } catch (IOException e) { // This was not a PEM certificate, I hope it's binary... cert = CertTools.getCertfromByteArray(certbytes); } PublicKey pubKey = cert.getPublicKey(); // Verify that the public and private key belongs together getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm()); KeyTools.testKey(privKey, pubKey, null); Certificate cacert = null; if (args.length > 6) { // Create a self signed CVCA cert from the DN getLogger().info("Generating new self signed certificate."); String dn = args[4]; String sigAlg = args[5]; Integer valdays = Integer.parseInt(args[6]); String country = CertTools.getPartFromDN(dn, "C"); String mnemonic = CertTools.getPartFromDN(dn, "CN"); String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER"); if (StringUtils.isEmpty(seq)) { seq = RandomStringUtils.randomNumeric(5); getLogger().info("No sequence given, using random 5 number sequence: " + seq); } HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq); CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(), holderRef.getSequence()); AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA; Date notBefore = new Date(); Calendar notAfter = Calendar.getInstance(); notAfter.add(Calendar.DAY_OF_MONTH, valdays); CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef, holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(), "BC"); cacert = new CardVerifiableCertificate(cvc); } else { getLogger().info("Using passed in self signed certificate."); cacert = cert; } try { cacert.verify(pubKey); } catch (SignatureException e) { getLogger().info("Can not verify self signed certificate: " + e.getMessage()); System.exit(3); // NOPMD } Certificate[] chain = new Certificate[1]; chain[0] = cacert; ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null, null); } catch (ErrorAdminCommandException e) { throw e; } catch (Exception e) { throw new ErrorAdminCommandException(e); } }
From source file:org.encuestame.test.business.service.TestSecurityService.java
/** * Test get {@link UserAccountBean} by code. * * @throws EnMeNoResultsFoundException//w w w .j a v a 2 s.co m */ @Test @Category(DefaultTest.class) public void testGetUserAccountbyCode() throws EnMeNoResultsFoundException { final String inviteCode = RandomStringUtils.randomNumeric(6); final UserAccount account = createUserAccount("jota", "jota@jota.com", createAccount()); account.setInviteCode(inviteCode); getAccountDao().saveOrUpdate(account); final UserAccountBean userAccBean = securityService.getUserAccountbyCode(inviteCode); assertNotNull(userAccBean); }
From source file:org.encuestame.test.config.AbstractBase.java
/** * Helper to create Secondary User./* w ww . ja v a 2 s .c o m*/ * @param name user name * @param secUser {@link Account} * @return state */ public UserAccount createUserAccount(final String name, final Account account) { return createUserAccount(name, name.replace(" ", "") + "." + RandomStringUtils.randomNumeric(6) + "@users.com", account); }
From source file:org.encuestame.test.config.AbstractBase.java
public UserAccount createSecondaryUserGroup(final String name, final Account secUser, final Group group) { return createSecondaryUserGroup(name, name.replace(" ", "") + "." + RandomStringUtils.randomNumeric(6) + "@users.com", secUser, group); }
From source file:org.flite.cach3.aop.ReadThroughMultiCacheTest.java
@Test public void testInitialKey2Result() { final String ns = RandomStringUtils.randomAlphanumeric(6); final Map<String, Object> expectedString2Object = new HashMap<String, Object>(); final Map<String, Object> key2Result = new HashMap<String, Object>(); final Set<Object> missObjects = new HashSet<Object>(); final int length = 15; for (int ix = 0; ix < length; ix++) { final String object = RandomStringUtils.randomAlphanumeric(2 + ix); final String key = cut.buildCacheKey(object, ns, null); expectedString2Object.put(key, object); // There are 3 possible outcomes when fetching by key from memcached: // 0) You hit, and the key & result are in the map // 1) You hit, but the result is null, which counts as a miss. // 2) You miss, and the key doesn't even get into the result map. final int option = RandomUtils.nextInt(3); if (option == 0) { key2Result.put(key, key + RandomStringUtils.randomNumeric(5)); }/*from w w w . ja va 2s .c om*/ if (option == 1) { key2Result.put(key, null); missObjects.add(object); } if (option == 2) { missObjects.add(object); } } try { coord.setInitialKey2Result(null); fail("Expected Exception."); } catch (RuntimeException ex) { } coord.getKey2Obj().putAll(expectedString2Object); coord.setInitialKey2Result(key2Result); assertTrue(coord.getMissObjects().containsAll(missObjects)); assertTrue(missObjects.containsAll(coord.getMissObjects())); }
From source file:org.flite.cach3.test.UpdateMultiCacheTest.java
@Test public void testVelocity() { final String original = RandomStringUtils.randomAlphanumeric(7); final Long second = Long.valueOf("1337" + RandomStringUtils.randomNumeric(5)); final List<Long> firsts = new ArrayList<Long>(); final List<String> baseIds = new ArrayList<String>(); final long base = RandomUtils.nextInt(2000) + 1000; for (int ix = 0; ix < 3; ix++) { final Long val = base + ix; firsts.add(val); baseIds.add(val + "&&" + second); }/*from w ww . ja va 2 s. com*/ final Long extra = base + 10; final String extraString = original + extra.toString(); final TestSvc test = (TestSvc) context.getBean("testSvc"); final StubUpdateMultiCacheListenerImpl listener = (StubUpdateMultiCacheListenerImpl) context .getBean("stubUM"); final int previous = listener.getTriggers().size(); final List<String> results = test.updateCompoundStrings(second, original, firsts); // Testing that the listener got invoked as required. assertTrue("Doesn't look like the listener got called.", listener.getTriggers().size() == previous + 1); final String expected = StubUpdateMultiCacheListenerImpl.formatTriggers(TestDAOImpl.COMPOUND_NAMESPACE, TestDAOImpl.COMPOUND_PREFIX, baseIds, (List<Object>) (List) results, // Using Erasure to satisfy the compiler. YUCK! results, new Object[] { second, original, firsts }); assertEquals(expected, listener.getTriggers().get(listener.getTriggers().size() - 1)); // This part just double-checks the sublist aspect of the ReadThroughMultiCache firsts.add(extra); Collections.shuffle(firsts); final List<String> r2 = test.getCompoundStrings(firsts, extraString, second); for (int ix = 0; ix < firsts.size(); ix++) { final Long value = firsts.get(ix); assertEquals(value.equals(extra) ? extraString : original, r2.get(ix)); } }
From source file:org.hydracache.data.partitioning.ConsistentHashNodePartitionTestConcurrency.java
private void startTestThread(final ConsistentHashNodePartition<ServerNode> circle, final CountDownLatch doneLatch) { new Thread() { @Override/*www . j av a2s. c o m*/ public void run() { try { messWithHashRing(circle); doneLatch.countDown(); } catch (Exception e) { e.printStackTrace(); failed = true; } } private void messWithHashRing(final ConsistentHashNodePartition<ServerNode> circle) { ServerNode node = new ServerNode(RandomUtils.nextInt(100)); circle.remove(node); Thread.yield(); ServerNode n = circle.get(RandomStringUtils.randomNumeric(5)); assertNotNull(n); Thread.yield(); circle.add(node); } }.start(); }
From source file:org.jboss.as.quickstarts.batch.controller.BatchController.java
public void generate() throws IOException { File tempFile = new File(System.getProperty("java.io.tmpdir"), fileName); try (BufferedWriter bos = new BufferedWriter(new FileWriter(tempFile, false))) { log.info("Starting to generate " + numRecords + " in file " + tempFile); String previousName = null; for (int x = 0; x < numRecords; x++) { String name = RandomStringUtils.randomAlphabetic(10); String phone = RandomStringUtils.randomNumeric(9); // Generate a duplicate name; if (generateWithError && x == (numRecords / 2)) { name = previousName;//from w w w . j a v a 2 s . co m } String record = (x + 1) + "|" + name + "|" + phone; bos.write(record + "\n"); previousName = name; } log.info("File generated at " + tempFile); facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "File generated with " + numRecords + " records to be imported. File name: " + getFileName(), null)); if (generateWithError) { facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Attention: This file contains duplicate records for test purpose.", null)); } } }