List of usage examples for java.security.interfaces RSAPublicKey getModulus
public BigInteger getModulus();
From source file:VerifyDescriptors.java
private static void verifyConsensuses() throws Exception { File certsDirectory = new File("in/certs"); File consensusDirectory = new File("in/consensuses"); if (!certsDirectory.exists() || !consensusDirectory.exists()) { return;// w ww.j ava 2s. co m } Map<String, String> signingKeys = new HashMap<String, String>(); DescriptorReader certsReader = DescriptorSourceFactory.createDescriptorReader(); certsReader.addDirectory(certsDirectory); Iterator<DescriptorFile> descriptorFiles = certsReader.readDescriptors(); int processedCerts = 0, verifiedCerts = 0; while (descriptorFiles.hasNext()) { DescriptorFile descriptorFile = descriptorFiles.next(); if (descriptorFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + descriptorFile.getFileName() + ": " + descriptorFile.getException().getMessage()); continue; } if (descriptorFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : descriptorFile.getDescriptors()) { if (!(descriptor instanceof DirectoryKeyCertificate)) { continue; } DirectoryKeyCertificate cert = (DirectoryKeyCertificate) descriptor; boolean isVerified = true; /* Verify that the contained fingerprint is a hash of the signing * key. */ String dirIdentityKeyHashString = determineKeyHash(cert.getDirIdentityKey()); String fingerprintString = cert.getFingerprint().toLowerCase(); if (!dirIdentityKeyHashString.equals(fingerprintString)) { System.out.println("In " + descriptorFile.getFile() + ", the calculated directory identity key hash " + dirIdentityKeyHashString + " does not match the contained fingerprint " + fingerprintString + "!"); isVerified = false; } /* Verify that the router signature was created using the signing * key. */ if (!verifySignature(cert.getCertificateDigest(), cert.getDirKeyCertification(), cert.getDirIdentityKey())) { System.out.println("In " + descriptorFile.getFile() + ", the decrypted directory key certification does not " + "match the certificate digest!"); isVerified = false; } /* Determine the signing key digest and remember the signing key * to verify consensus signatures. */ String dirSigningKeyString = cert.getDirSigningKey(); PEMReader pemReader2 = new PEMReader(new StringReader(dirSigningKeyString)); RSAPublicKey dirSigningKey = (RSAPublicKey) pemReader2.readObject(); ByteArrayOutputStream baos2 = new ByteArrayOutputStream(); new ASN1OutputStream(baos2) .writeObject(new org.bouncycastle.asn1.pkcs.RSAPublicKey(dirSigningKey.getModulus(), dirSigningKey.getPublicExponent()).toASN1Primitive()); byte[] pkcs2 = baos2.toByteArray(); byte[] dirSigningKeyHashBytes = new byte[20]; SHA1Digest sha1_2 = new SHA1Digest(); sha1_2.update(pkcs2, 0, pkcs2.length); sha1_2.doFinal(dirSigningKeyHashBytes, 0); String dirSigningKeyHashString = Hex.encodeHexString(dirSigningKeyHashBytes).toUpperCase(); signingKeys.put(dirSigningKeyHashString, cert.getDirSigningKey()); processedCerts++; if (isVerified) { verifiedCerts++; } } } System.out.println("Verified " + verifiedCerts + "/" + processedCerts + " certs."); DescriptorReader consensusReader = DescriptorSourceFactory.createDescriptorReader(); consensusReader.addDirectory(consensusDirectory); Iterator<DescriptorFile> consensusFiles = consensusReader.readDescriptors(); int processedConsensuses = 0, verifiedConsensuses = 0; while (consensusFiles.hasNext()) { DescriptorFile consensusFile = consensusFiles.next(); if (consensusFile.getException() != null) { System.err.println("Could not read/parse descriptor file " + consensusFile.getFileName() + ": " + consensusFile.getException().getMessage()); continue; } if (consensusFile.getDescriptors() == null) { continue; } for (Descriptor descriptor : consensusFile.getDescriptors()) { if (!(descriptor instanceof RelayNetworkStatusConsensus)) { continue; } RelayNetworkStatusConsensus consensus = (RelayNetworkStatusConsensus) descriptor; boolean isVerified = true; /* Verify all signatures using the corresponding certificates. */ if (consensus.getDirectorySignatures().isEmpty()) { System.out.println(consensusFile.getFile() + " does not contain any signatures."); continue; } for (DirectorySignature signature : consensus.getDirectorySignatures().values()) { String signingKeyDigest = signature.getSigningKeyDigest(); if (!signingKeys.containsKey(signingKeyDigest)) { System.out.println("Cannot find signing key with digest " + signingKeyDigest + "!"); } if (!verifySignature(consensus.getConsensusDigest(), signature.getSignature(), signingKeys.get(signingKeyDigest))) { System.out.println("In " + consensusFile.getFile() + ", the decrypted signature digest does not match the " + "consensus digest!"); isVerified = false; } } processedConsensuses++; if (isVerified) { verifiedConsensuses++; } } } System.out.println("Verified " + verifiedConsensuses + "/" + processedConsensuses + " consensuses."); }
From source file:cn.util.RSAUtils.java
/** * ,?116,?#/*from w w w. j a va2 s . c om*/ * * @param data * @param publicKey * @return * @throws Exception */ public static String encryptByPublicKey(String data) throws Exception { if (null == data) { return null; } RSAPublicKey publicKey = getPublicKey(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); // int key_len = publicKey.getModulus().bitLength() / 8; // ? <= -12116 50 String[] datas = null; if (data.getBytes().length > key_len - 12) { datas = splitString(data, 30); } else { datas = new String[1]; datas[0] = data; } String mi = ""; //-11? for (int i = 0; i < datas.length; i++) { if (i < datas.length - 1) { mi += Base64Util.encryptBASE64(cipher.doFinal(datas[i].getBytes())) + "#"; } else { mi += Base64Util.encryptBASE64(cipher.doFinal(datas[i].getBytes())); } } //\r\n mi = mi.replace("\r", ""); mi = mi.replace("\n", ""); return mi; }
From source file:net.adamcin.httpsig.testutil.KeyTestUtil.java
public static byte[] dumpKeyBlob(PublicKey publicKey) { ByteArrayOutputStream byteOs = new ByteArrayOutputStream(); try {// ww w. jav a 2 s . c o m if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-rsa".getBytes().length); dos.write("ssh-rsa".getBytes()); dos.writeInt(rsaPublicKey.getPublicExponent().toByteArray().length); dos.write(rsaPublicKey.getPublicExponent().toByteArray()); dos.writeInt(rsaPublicKey.getModulus().toByteArray().length); dos.write(rsaPublicKey.getModulus().toByteArray()); } else if (publicKey instanceof DSAPublicKey) { DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey; DSAParams dsaParams = dsaPublicKey.getParams(); DataOutputStream dos = new DataOutputStream(byteOs); dos.writeInt("ssh-dss".getBytes().length); dos.write("ssh-dss".getBytes()); dos.writeInt(dsaParams.getP().toByteArray().length); dos.write(dsaParams.getP().toByteArray()); dos.writeInt(dsaParams.getQ().toByteArray().length); dos.write(dsaParams.getQ().toByteArray()); dos.writeInt(dsaParams.getG().toByteArray().length); dos.write(dsaParams.getG().toByteArray()); dos.writeInt(dsaPublicKey.getY().toByteArray().length); dos.write(dsaPublicKey.getY().toByteArray()); } else { throw new IllegalArgumentException("Not a supported public key: " + publicKey); } } catch (IOException e) { // shouldn't happen LOGGER.error("failed to dump public key blob", e); } return byteOs.toByteArray(); }
From source file:uk.ac.ed.epcc.webapp.ssh.PublicKeyReaderUtil.java
/** format a key (of the types supported by the {@link #load(String)} method. * //from ww w .j a va 2s .co m * @param key * @return public key string * @throws PublicKeyParseException * @throws IOException */ public static String format(PublicKey key) throws PublicKeyParseException, IOException { StringBuilder sb = new StringBuilder(); String alg = key.getAlgorithm(); if (alg.equalsIgnoreCase("RSA")) { RSAPublicKey pub = (RSAPublicKey) key; sb.append(SSH2_RSA_KEY); sb.append(" "); SSH2ByteBuffer buf = new SSH2ByteBuffer(); buf.writeString(SSH2_RSA_KEY); buf.writeMPint(pub.getPublicExponent()); buf.writeMPint(pub.getModulus()); sb.append(Base64.encodeBase64String(buf.toByteArray())); } else if (alg.equalsIgnoreCase("DSA")) { DSAPublicKey pub = (DSAPublicKey) key; sb.append(SSH2_DSA_KEY); sb.append(" "); SSH2ByteBuffer buf = new SSH2ByteBuffer(); buf.writeString(SSH2_DSA_KEY); DSAParams params = pub.getParams(); buf.writeMPint(params.getP()); buf.writeMPint(params.getQ()); buf.writeMPint(params.getG()); buf.writeMPint(pub.getY()); sb.append(Base64.encodeBase64String(buf.toByteArray())); } else { throw new PublicKeyParseException(ErrorCode.UNKNOWN_PUBLIC_KEY_FILE_FORMAT); } return sb.toString(); }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Gets the key length of supported keys * @param pk PublicKey used to derive the keysize * @return -1 if key is unsupported, otherwise a number >= 0. 0 usually means the length can not be calculated, * for example if the key is an EC key and the "implicitlyCA" encoding is used. *//* w w w . j av a 2 s. co m*/ public static int getKeyLength(final PublicKey pk) { int len = -1; if (pk instanceof RSAPublicKey) { final RSAPublicKey rsapub = (RSAPublicKey) pk; len = rsapub.getModulus().bitLength(); } else if (pk instanceof JCEECPublicKey) { final JCEECPublicKey ecpriv = (JCEECPublicKey) pk; final org.bouncycastle.jce.spec.ECParameterSpec spec = ecpriv.getParameters(); if (spec != null) { len = spec.getN().bitLength(); } else { // We support the key, but we don't know the key length len = 0; } } else if (pk instanceof ECPublicKey) { final ECPublicKey ecpriv = (ECPublicKey) pk; final java.security.spec.ECParameterSpec spec = ecpriv.getParams(); if (spec != null) { len = spec.getOrder().bitLength(); // does this really return something we expect? } else { // We support the key, but we don't know the key length len = 0; } } else if (pk instanceof DSAPublicKey) { final DSAPublicKey dsapub = (DSAPublicKey) pk; if (dsapub.getParams() != null) { len = dsapub.getParams().getP().bitLength(); } else { len = dsapub.getY().bitLength(); } } return len; }
From source file:org.apache.xml.security.stax.ext.XMLSecurityUtils.java
public static void createKeyValueTokenStructure(AbstractOutputProcessor abstractOutputProcessor, OutputProcessorChain outputProcessorChain, PublicKey publicKey) throws XMLStreamException, XMLSecurityException { if (publicKey == null) { throw new XMLSecurityException("stax.signature.publicKeyOrCertificateMissing"); }/*from w w w .j a va 2 s . c o m*/ String algorithm = publicKey.getAlgorithm(); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyValue, true, null); if ("RSA".equals(algorithm)) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_RSAKeyValue, false, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Modulus, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(rsaPublicKey.getModulus().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Modulus); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Exponent, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(rsaPublicKey.getPublicExponent().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Exponent); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_RSAKeyValue); } else if ("DSA".equals(algorithm)) { DSAPublicKey dsaPublicKey = (DSAPublicKey) publicKey; BigInteger j = dsaPublicKey.getParams().getP().subtract(BigInteger.ONE) .divide(dsaPublicKey.getParams().getQ()); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DSAKeyValue, false, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_P, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getP().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_P); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Q, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getQ().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Q); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_G, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }) .encodeToString(dsaPublicKey.getParams().getG().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_G); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Y, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(dsaPublicKey.getY().toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_Y); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_J, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString(j.toByteArray())); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_J); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_DSAKeyValue); } else if ("EC".equals(algorithm)) { ECPublicKey ecPublicKey = (ECPublicKey) publicKey; List<XMLSecAttribute> attributes = new ArrayList<XMLSecAttribute>(1); attributes.add(abstractOutputProcessor.createAttribute(XMLSecurityConstants.ATT_NULL_URI, "urn:oid:" + ECDSAUtils.getOIDFromPublicKey(ecPublicKey))); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_ECKeyValue, true, null); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_NamedCurve, false, attributes); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_NamedCurve); abstractOutputProcessor.createStartElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_PublicKey, false, null); abstractOutputProcessor.createCharactersAndOutputAsEvent(outputProcessorChain, new Base64(76, new byte[] { '\n' }).encodeToString( ECDSAUtils.encodePoint(ecPublicKey.getW(), ecPublicKey.getParams().getCurve()))); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_PublicKey); abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig11_ECKeyValue); } abstractOutputProcessor.createEndElementAndOutputAsEvent(outputProcessorChain, XMLSecurityConstants.TAG_dsig_KeyValue); }
From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateParser.java
private void validatePublicKey() { PublicKey publicKey = certificate.getPublicKey(); result.rejectIfFalse("RSA".equals(publicKey.getAlgorithm()) && publicKey instanceof RSAPublicKey, PUBLIC_KEY_CERT_ALGORITHM, publicKey.getAlgorithm()); if (publicKey instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey; result.warnIfFalse(2048 == rsaPublicKey.getModulus().bitLength(), PUBLIC_KEY_CERT_SIZE, String.valueOf(rsaPublicKey.getModulus().bitLength())); }//from w ww. j av a 2 s . c om }
From source file:net.shopxx.controller.admin.LoginController.java
@RequestMapping public String index(HttpServletRequest request, ModelMap model) { String loginToken = WebUtils.getCookie(request, Admin.LOGIN_TOKEN_COOKIE_NAME); if (!StringUtils.equalsIgnoreCase(loginToken, adminService.getLoginToken())) { return "redirect:/"; }/* w w w .ja v a 2 s.c o m*/ if (adminService.isAuthenticated()) { return "redirect:common/main.jhtml"; } Message failureMessage = null; String loginFailure = (String) request .getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME); if (StringUtils.isNotEmpty(loginFailure)) { if (loginFailure.equals("net.shopxx.exception.IncorrectCaptchaException")) { failureMessage = Message.error("admin.captcha.invalid"); } else if (loginFailure.equals("org.apache.shiro.authc.UnknownAccountException")) { failureMessage = Message.error("admin.login.unknownAccount"); } else if (loginFailure.equals("org.apache.shiro.authc.DisabledAccountException")) { failureMessage = Message.error("admin.login.disabledAccount"); } else if (loginFailure.equals("org.apache.shiro.authc.LockedAccountException")) { failureMessage = Message.error("admin.login.lockedAccount"); } else if (loginFailure.equals("org.apache.shiro.authc.IncorrectCredentialsException")) { Setting setting = SystemUtils.getSetting(); if (ArrayUtils.contains(setting.getAccountLockTypes(), Setting.AccountLockType.admin)) { failureMessage = Message.error("admin.login.accountLockCount", setting.getAccountLockCount()); } else { failureMessage = Message.error("admin.login.incorrectCredentials"); } } else if (loginFailure.equals("net.shopxx.exception.IncorrectLicenseException")) { failureMessage = Message.error("admin.login.incorrectLicense"); } else if (loginFailure.equals("org.apache.shiro.authc.AuthenticationException")) { failureMessage = Message.error("admin.login.authentication"); } } RSAPublicKey publicKey = rsaService.generateKey(request); model.addAttribute("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray())); model.addAttribute("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray())); model.addAttribute("captchaId", UUID.randomUUID().toString()); model.addAttribute("failureMessage", failureMessage); return "/admin/login/index"; }
From source file:test.integ.be.fedict.trust.Foreigner201305Test.java
/** * wget --recursive -e robots=off http://certs.eid.belgium.be * //from w w w . j a va2 s.co m * @throws Exception */ @Test public void testAllCertificateAuthorities() throws Exception { File dirFile = new File("/home/fcorneli/certs/certs.eid.belgium.be"); LOG.debug("directory: " + dirFile.getAbsolutePath()); File[] certFiles = dirFile.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { LOG.debug(name); return name.endsWith("crt"); } }); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); for (File certFile : certFiles) { X509Certificate certificate = (X509Certificate) certificateFactory .generateCertificate(new FileInputStream(certFile)); LOG.debug("certificate: " + certificate.getSubjectX500Principal()); RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey(); int modulusSize = rsaPublicKey.getModulus().toByteArray().length; LOG.debug("modulus size: " + modulusSize); int signatureSize = certificate.getSignature().length; LOG.debug("signature size: " + signatureSize); assertEquals(modulusSize - 1, signatureSize); } LOG.debug("total number of CAs: " + certFiles.length); }
From source file:com.verisignlabs.dnssec.cl.KeyInfoTool.java
public void execute() throws Exception { for (int i = 0; i < state.keynames.length; ++i) { String keyname = state.keynames[i]; DnsKeyPair key = BINDKeyUtils.loadKey(keyname, null); DNSKEYRecord dnskey = key.getDNSKEYRecord(); DnsKeyAlgorithm dnskeyalg = DnsKeyAlgorithm.getInstance(); boolean isSEP = (dnskey.getFlags() & DNSKEYRecord.Flags.SEP_KEY) != 0; System.out.println(keyname + ":"); System.out.println("Name: " + dnskey.getName()); System.out.println("SEP: " + isSEP); System.out.println("Algorithm: " + dnskeyalg.algToString(dnskey.getAlgorithm()) + " (" + dnskey.getAlgorithm() + ")"); System.out.println("ID: " + dnskey.getFootprint()); System.out.println("KeyFileBase: " + BINDKeyUtils.keyFileBase(key)); int basetype = dnskeyalg.baseType(dnskey.getAlgorithm()); switch (basetype) { case DnsKeyAlgorithm.RSA: { RSAPublicKey pub = (RSAPublicKey) key.getPublic(); System.out.println("RSA Public Exponent: " + pub.getPublicExponent()); System.out.println("RSA Modulus: " + pub.getModulus()); break; }//from w w w.j a v a2s. c om case DnsKeyAlgorithm.DSA: { DSAPublicKey pub = (DSAPublicKey) key.getPublic(); System.out.println("DSA base (G): " + pub.getParams().getG()); System.out.println("DSA prime (P): " + pub.getParams().getP()); System.out.println("DSA subprime (Q): " + pub.getParams().getQ()); System.out.println("DSA public (Y): " + pub.getY()); break; } } if (state.keynames.length - i > 1) { System.out.println(); } } }