List of usage examples for java.security Signature update
public final void update(ByteBuffer data) throws SignatureException
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
private byte[] createSignature(PrivateKey privateKey) throws SpkacException { try {/* w w w. j a v a 2 s.c o m*/ byte[] publicKeyAndChallenge = createPublicKeyAndChallengeForSigning(); Signature sig = Signature.getInstance(getSignatureAlgorithm().jce()); sig.initSign(privateKey); sig.update(publicKeyAndChallenge); return sig.sign(); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoCreateSpkacSignature.exception.message"), ex); } }
From source file:net.sf.keystore_explorer.crypto.csr.spkac.Spkac.java
/** * Verify SPKAC.//from w ww .j ava 2 s . com * * @return True if verified successfully, false otherwise * @throws SpkacException * If verification fails */ public boolean verify() throws SpkacException { try { byte[] publicKeyAndChallenge = createPublicKeyAndChallengeForSigning(); Signature sig = Signature.getInstance(getSignatureAlgorithm().jce()); sig.initVerify(getPublicKey()); sig.update(publicKeyAndChallenge); return sig.verify(signature); } catch (GeneralSecurityException ex) { throw new SpkacException(res.getString("NoVerifySpkacSignature.exception.message"), ex); } }
From source file:Manifest.java
/** * This method creates a manifest file with the specified name, for the * specified vector of files, using the named message digest algorithm. If * signername is non-null, it adds a digital signature to the manifest, * using the named signature algorithm. This method can throw a bunch of * exceptions.//from w w w. jav a2 s . c om */ public static void create(String manifestfile, String digestAlgorithm, String signername, String signatureAlgorithm, KeyStore keystore, String password, List filelist) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, KeyStoreException, UnrecoverableKeyException, IOException { // For computing a signature, we have to process the files in a fixed, // repeatable order, so sort them alphabetically. Collections.sort(filelist); int numfiles = filelist.size(); Properties manifest = new Properties(), metadata = new Properties(); MessageDigest md = MessageDigest.getInstance(digestAlgorithm); Signature signature = null; byte[] digest; // If a signer name was specified, then prepare to sign the manifest if (signername != null) { // Get a Signature object signature = Signature.getInstance(signatureAlgorithm); // Look up the private key of the signer from the keystore PrivateKey key = (PrivateKey) keystore.getKey(signername, password.toCharArray()); // No prepare to create a signature for the specified signer signature.initSign(key); } // Now, loop through the files, in a well-known alphabetical order System.out.print("Computing message digests"); for (int i = 0; i < numfiles; i++) { String filename = (String) filelist.get(i); // Compute the digest for each, and skip files that don't exist. try { digest = getFileDigest(filename, md); } catch (IOException e) { System.err.println("\nSkipping " + filename + ": " + e); continue; } // If we're computing a signature, use the bytes of the filename // and of the digest as part of the data to sign. if (signature != null) { signature.update(filename.getBytes()); signature.update(digest); } // Store the filename and the encoded digest bytes in the manifest manifest.put(filename, hexEncode(digest)); System.out.print('.'); System.out.flush(); } // If a signer was specified, compute signature for the manifest byte[] signaturebytes = null; if (signature != null) { System.out.print("done\nComputing digital signature..."); System.out.flush(); // Compute the digital signature by encrypting a message digest of // all the bytes passed to the update() method using the private // key of the signer. This is a time consuming operation. signaturebytes = signature.sign(); } // Tell the user what comes next System.out.print("done\nWriting manifest..."); System.out.flush(); // Store some metadata about this manifest, including the name of the // message digest algorithm it uses metadata.put("__META.DIGESTALGORITHM", digestAlgorithm); // If we're signing the manifest, store some more metadata if (signername != null) { // Store the name of the signer metadata.put("__META.SIGNER", signername); // Store the name of the algorithm metadata.put("__META.SIGNATUREALGORITHM", signatureAlgorithm); // And generate the signature, encode it, and store it metadata.put("__META.SIGNATURE", hexEncode(signaturebytes)); } // Now, save the manifest data and the metadata to the manifest file FileOutputStream f = new FileOutputStream(manifestfile); manifest.store(f, "Manifest message digests"); metadata.store(f, "Manifest metadata"); System.out.println("done"); }
From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java
private byte[] generateSignature(String tokenString) { byte[] signature = null; File ksFile = ConfigurationListener.getLterKeyStore(); String ksType = ConfigurationListener.getLterKeyStoreType(); String ksAlias = ConfigurationListener.getLterKeyStoreAlias(); char[] storePass = ConfigurationListener.getLterStorePasswd().toCharArray(); char[] keyPass = ConfigurationListener.getLterKeyPasswd().toCharArray(); try {/*w ww . j a va2s . c om*/ KeyStore ks = KeyStore.getInstance(ksType); FileInputStream ksFis = new FileInputStream(ksFile); BufferedInputStream ksBufIn = new BufferedInputStream(ksFis); ks.load(ksBufIn, storePass); PrivateKey priv = (PrivateKey) ks.getKey(ksAlias, keyPass); Signature rsa = Signature.getInstance("MD5withRSA"); rsa.initSign(priv); rsa.update(tokenString.getBytes()); signature = rsa.sign(); } catch (Exception e) { logger.error(e.getMessage()); e.printStackTrace(); } return signature; }
From source file:edu.lternet.pasta.gatekeeper.GatekeeperFilter.java
private Boolean isValidSignature(String tokenString, byte[] signature) { Boolean isValid = false;//from w w w. ja v a2 s.c o m File lterCert = ConfigurationListener.getLterCertificate(); try { FileInputStream certFis = new FileInputStream(lterCert); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(certFis); PublicKey pubKey = cert.getPublicKey(); Signature sig = Signature.getInstance("MD5withRSA"); sig.initVerify(pubKey); sig.update(tokenString.getBytes()); isValid = sig.verify(signature); } catch (FileNotFoundException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (CertificateException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (NoSuchAlgorithmException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (InvalidKeyException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } catch (SignatureException e) { logger.error("Gatekeeper.validateSignature :" + e.getMessage()); e.printStackTrace(); } return isValid; }
From source file:org.ejbca.ui.cmpclient.commands.CrmfRequestCommand.java
@Override public PKIMessage generatePKIMessage(final ParameterContainer parameters) throws Exception { final boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY)); final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY)); String authmodule = parameters.get(AUTHENTICATION_MODULE_KEY); String endentityPassword = ""; if (authmodule != null && StringUtils.equals(authmodule, CmpConfiguration.AUTHMODULE_REG_TOKEN_PWD)) { endentityPassword = parameters.containsKey(AUTHENTICATION_PARAM_KEY) ? parameters.get(AUTHENTICATION_PARAM_KEY) : "foo123"; }//from ww w . j a v a 2 s . c om String altNames = parameters.get(ALTNAME_KEY); String serno = parameters.get(SERNO_KEY); BigInteger customCertSerno = null; if (serno != null) { customCertSerno = new BigInteger(serno, 16); } boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY); if (verbose) { log.info("Creating CRMF request with: SubjectDN=" + userDN.toString()); log.info("Creating CRMF request with: IssuerDN=" + issuerDN.toString()); log.info("Creating CRMF request with: AuthenticationModule=" + authmodule); log.info("Creating CRMF request with: EndEntityPassword=" + endentityPassword); log.info("Creating CRMF request with: SubjectAltName=" + altNames); log.info("Creating CRMF request with: CustomCertSerno=" + (customCertSerno == null ? "" : customCertSerno.toString(16))); log.info("Creating CRMF request with: IncludePopo=" + includePopo); } final KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); final byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); final byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); // We should be able to back date the start time when allow validity // override is enabled in the certificate profile Calendar cal = Calendar.getInstance(); cal.add(Calendar.DAY_OF_WEEK, -1); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds // in validity Date notBefore = cal.getTime(); cal.add(Calendar.DAY_OF_WEEK, 3); cal.set(Calendar.MILLISECOND, 0); // Certificates don't use milliseconds org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time(notBefore); // in validity Date notAfter = cal.getTime(); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(notAfter); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); myCertTemplate.setValidity(myOptionalValidity); if (issuerDN != null) { myCertTemplate.setIssuer(issuerDN); } myCertTemplate.setSubject(userDN); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); dIn.close(); myCertTemplate.setPublicKey(keyInfo); // Create standard extensions ByteArrayOutputStream bOut = new ByteArrayOutputStream(); ASN1OutputStream dOut = new ASN1OutputStream(bOut); ExtensionsGenerator extgen = new ExtensionsGenerator(); if (altNames != null) { GeneralNames san = CertTools.getGeneralNamesFromAltName(altNames); dOut.writeObject(san); byte[] value = bOut.toByteArray(); extgen.addExtension(Extension.subjectAlternativeName, false, value); } // KeyUsage int bcku = 0; bcku = KeyUsage.digitalSignature | KeyUsage.keyEncipherment | KeyUsage.nonRepudiation; KeyUsage ku = new KeyUsage(bcku); extgen.addExtension(Extension.keyUsage, false, new DERBitString(ku)); // Make the complete extension package Extensions exts = extgen.generate(); myCertTemplate.setExtensions(exts); if (customCertSerno != null) { // Add serialNumber to the certTemplate, it is defined as a MUST NOT be used in RFC4211, but we will use it anyway in order // to request a custom certificate serial number (something not standard anyway) myCertTemplate.setSerialNumber(new ASN1Integer(customCertSerno)); } CertRequest myCertRequest = new CertRequest(4, myCertTemplate.build(), null); // POPO /* * PKMACValue myPKMACValue = new PKMACValue( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("8.2.1.2.3.4"), new DERBitString(new byte[] { 8, * 1, 1, 2 })), new DERBitString(new byte[] { 12, 29, 37, 43 })); * * POPOPrivKey myPOPOPrivKey = new POPOPrivKey(new DERBitString(new * byte[] { 44 }), 2); //take choice pos tag 2 * * POPOSigningKeyInput myPOPOSigningKeyInput = new POPOSigningKeyInput( * myPKMACValue, new SubjectPublicKeyInfo( new AlgorithmIdentifier(new * ASN1ObjectIdentifier("9.3.3.9.2.2"), new DERBitString(new byte[] { 2, * 9, 7, 3 })), new byte[] { 7, 7, 7, 4, 5, 6, 7, 7, 7 })); */ ProofOfPossession myProofOfPossession = null; if (includePopo) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DEROutputStream mout = new DEROutputStream(baos); mout.writeObject(myCertRequest); mout.close(); byte[] popoProtectionBytes = baos.toByteArray(); String sigalg = AlgorithmTools.getSignAlgOidFromDigestAndKey(null, keys.getPrivate().getAlgorithm()) .getId(); Signature sig = Signature.getInstance(sigalg, "BC"); sig.initSign(keys.getPrivate()); sig.update(popoProtectionBytes); DERBitString bs = new DERBitString(sig.sign()); POPOSigningKey myPOPOSigningKey = new POPOSigningKey(null, new AlgorithmIdentifier(new ASN1ObjectIdentifier(sigalg)), bs); myProofOfPossession = new ProofOfPossession(myPOPOSigningKey); } else { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String(endentityPassword)); AttributeTypeAndValue[] avs = { av }; CertReqMsg myCertReqMsg = new CertReqMsg(myCertRequest, myProofOfPossession, avs); CertReqMessages myCertReqMessages = new CertReqMessages(myCertReqMsg); PKIHeaderBuilder myPKIHeader = new PKIHeaderBuilder(2, new GeneralName(userDN), new GeneralName(issuerDN)); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(null); myPKIHeader.setSenderKID(new byte[0]); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.wso2.carbon.apimgt.impl.token.AbstractJWTGenerator.java
private byte[] signJWT(String assertion, String endUserName) throws APIManagementException { try {// w ww .j a va 2 s . c o m //get tenant domain String tenantDomain = MultitenantUtils.getTenantDomain(endUserName); //get tenantId int tenantId = APIUtil.getTenantId(endUserName); Key privateKey = null; if (!(privateKeys.containsKey(tenantId))) { APIUtil.loadTenantRegistry(tenantId); //get tenant's key store manager KeyStoreManager tenantKSM = KeyStoreManager.getInstance(tenantId); if (!tenantDomain.equals(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME)) { //derive key store name String ksName = tenantDomain.trim().replace(".", "-"); String jksName = ksName + ".jks"; //obtain private key //TODO: maintain a hash map with tenants' private keys after first initialization privateKey = tenantKSM.getPrivateKey(jksName, tenantDomain); } else { try { privateKey = tenantKSM.getDefaultPrivateKey(); } catch (Exception e) { log.error("Error while obtaining private key for super tenant", e); } } if (privateKey != null) { privateKeys.put(tenantId, privateKey); } } else { privateKey = privateKeys.get(tenantId); } //initialize signature with private key and algorithm Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign((PrivateKey) privateKey); //update signature with data to be signed byte[] dataInBytes = assertion.getBytes(); signature.update(dataInBytes); //sign the assertion and return the signature byte[] signedInfo = signature.sign(); return signedInfo; } catch (NoSuchAlgorithmException e) { String error = "Signature algorithm not found."; //do not log throw new APIManagementException(error); } catch (InvalidKeyException e) { String error = "Invalid private key provided for the signature"; //do not log throw new APIManagementException(error); } catch (SignatureException e) { String error = "Error in signature"; //do not log throw new APIManagementException(error); } catch (RegistryException e) { throw new APIManagementException("Error occurred while loading tenant registry", e); } }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testNonRepudiationSignature() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null);/*www. j a v a 2 s . c o m*/ PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(signPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature"); assertNotNull(signCertificateChain); }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testLocale() throws Exception { Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter(); beIDKeyStoreParameter.setLocale(Locale.FRENCH); beIDKeyStoreParameter.setLogger(new TestLogger()); keyStore.load(beIDKeyStoreParameter); PrivateKey privateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey);/*from w w w .ja va 2 s.com*/ byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); signature.sign(); }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testNonRepudiationSignaturePPDU() throws Exception { CCID.riskPPDU(true);// w w w . j av a2 s. c o m Security.addProvider(new BeIDProvider()); KeyStore keyStore = KeyStore.getInstance("BeID"); keyStore.load(null); PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(signPrivateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); assertNotNull(signatureValue); Certificate[] signCertificateChain = keyStore.getCertificateChain("Signature"); assertNotNull(signCertificateChain); }