List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:com.mycompany.bankinterface.crypto.Signer.java
public String sign(String clearText) throws SignerException { Signature dsa; try {/*from w ww . ja v a 2 s . co m*/ dsa = Signature.getInstance(SIGNER_ALGORITHM, PROVIDER); } catch (NoSuchAlgorithmException | NoSuchProviderException ex) { throw new SignerException("Could not get signing instance", ex); } try { dsa.initSign(keyPair.getPrivate()); dsa.update(clearText.getBytes()); byte[] signature = dsa.sign(); String signatureAsString = Base64.encodeBase64String(signature); return signatureAsString; } catch (InvalidKeyException | SignatureException ex) { throw new SignerException("Failed to initialise signing algorithm", ex); } }
From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java
public BrowserPOSTResponse handleResponse(SignatureStatus signatureStatus, byte[] signedDocument, String artifact, X509Certificate signerCertificate, HttpSession httpSession, HttpServletRequest request, HttpServletResponse response) throws Exception { LOG.debug("handleResponse"); String target = retrieveTarget(httpSession); BrowserPOSTResponse browserPOSTResponse = new BrowserPOSTResponse(target); browserPOSTResponse.addAttribute("SignatureStatus", signatureStatus.getStatus()); /*/*from w ww . j a v a 2s. com*/ * Add RelayState if available */ String relayState = retrieveRelayState(httpSession); if (null != relayState) { browserPOSTResponse.addAttribute("RelayState", relayState); } if (SignatureStatus.OK == signatureStatus) { String signatureRequest = retrieveSignatureRequest(httpSession); String signatureRequestId = retrieveSignatureRequestId(httpSession); String encodedSignedDocument = Base64.encodeBase64String(signedDocument); if (null != signatureRequest) { browserPOSTResponse.addAttribute("SignatureResponse", encodedSignedDocument); } else { browserPOSTResponse.addAttribute("SignatureResponseId", artifact); } byte[] derSignerCertificate = signerCertificate.getEncoded(); String encodedSignatureCertificate = Base64.encodeBase64String(derSignerCertificate); browserPOSTResponse.addAttribute("SignatureCertificate", encodedSignatureCertificate); KeyStore.PrivateKeyEntry identityPrivateKeyEntry = this.dssContext.getIdentity(); if (null != identityPrivateKeyEntry) { LOG.debug("signing the response"); if (null != signatureRequest) { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequest," + "SignatureResponse," + "SignatureCertificate", "UTF-8")); } else { browserPOSTResponse.addAttribute("ServiceSigned", URLEncoder.encode( "target,SignatureRequestId," + "SignatureResponseId," + "SignatureCertificate", "UTF-8")); } // service signature Signature serviceSignature = Signature.getInstance("SHA1withRSA"); serviceSignature.initSign(identityPrivateKeyEntry.getPrivateKey()); serviceSignature.update(target.getBytes()); if (null != signatureRequest) { serviceSignature.update(signatureRequest.getBytes()); serviceSignature.update(encodedSignedDocument.getBytes()); } else { serviceSignature.update(signatureRequestId.getBytes()); serviceSignature.update(artifact.getBytes()); } serviceSignature.update(encodedSignatureCertificate.getBytes()); byte[] serviceSignatureValue = serviceSignature.sign(); String encodedServiceSignature = Base64.encodeBase64String(serviceSignatureValue); browserPOSTResponse.addAttribute("ServiceSignature", encodedServiceSignature); // service certificate chain Certificate[] serviceCertificateChain = identityPrivateKeyEntry.getCertificateChain(); browserPOSTResponse.addAttribute("ServiceCertificateChainSize", Integer.toString(serviceCertificateChain.length)); for (int certIdx = 0; certIdx < serviceCertificateChain.length; certIdx++) { Certificate certificate = serviceCertificateChain[certIdx]; String encodedServiceCertificate = Base64.encodeBase64String(certificate.getEncoded()); browserPOSTResponse.addAttribute("ServiceCertificate." + (certIdx + 1), encodedServiceCertificate); } } } return browserPOSTResponse; }
From source file:org.ejbca.ui.cmpclient.commands.KeyUpdateRequestCommand.java
@Override public PKIMessage generatePKIMessage(ParameterContainer parameters) throws Exception { boolean verbose = parameters.containsKey(VERBOSE_KEY); final X500Name userDN = new X500Name(parameters.get(SUBJECTDN_KEY)); final X500Name issuerDN = new X500Name(parameters.get(ISSUERDN_KEY)); boolean includePopo = parameters.containsKey(INCLUDE_POPO_KEY); if (verbose) { log.info("Creating KeyUpdate request with: SubjectDN=" + userDN.toString()); log.info("Creating KeyUpdate request with: IssuerDN=" + issuerDN.toString()); log.info("Creating KeyUpdate request with: IncludePopo=" + includePopo); }/*from w ww . j a v a 2 s. c o m*/ byte[] nonce = CmpClientMessageHelper.getInstance().createSenderNonce(); byte[] transid = CmpClientMessageHelper.getInstance().createSenderNonce(); KeyPair keys = KeyTools.genKeys("1024", AlgorithmConstants.KEYALGORITHM_RSA); CertTemplateBuilder myCertTemplate = new CertTemplateBuilder(); ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); optionalValidityV.add(new DERTaggedObject(true, 0, nb)); optionalValidityV.add(new DERTaggedObject(true, 1, na)); OptionalValidity myOptionalValidity = OptionalValidity.getInstance(new DERSequence(optionalValidityV)); myCertTemplate.setValidity(myOptionalValidity); byte[] bytes = keys.getPublic().getEncoded(); ByteArrayInputStream bIn = new ByteArrayInputStream(bytes); ASN1InputStream dIn = new ASN1InputStream(bIn); try { SubjectPublicKeyInfo keyInfo = new SubjectPublicKeyInfo((ASN1Sequence) dIn.readObject()); myCertTemplate.setPublicKey(keyInfo); } finally { dIn.close(); } myCertTemplate.setSubject(userDN); 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); 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(); } // myCertReqMsg.addRegInfo(new AttributeTypeAndValue(new // ASN1ObjectIdentifier("1.3.6.2.2.2.2.3.1"), new // DERInteger(1122334455))); AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("")); 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); PKIBody myPKIBody = new PKIBody(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java
private PKIMessage buildCertBasedPKIProtection(PKIMessage pKIMessage, CMPCertificate[] extraCerts, PrivateKey key, String digestAlg, String provider, boolean verbose) throws NoSuchProviderException, NoSuchAlgorithmException, SecurityException, SignatureException, InvalidKeyException { // Select which signature algorithm we should use for the response, based on the digest algorithm and key type. ASN1ObjectIdentifier oid = AlgorithmTools.getSignAlgOidFromDigestAndKey(digestAlg, key.getAlgorithm()); if (verbose) { log.info("Selected signature alg oid: " + oid.getId() + ", key algorithm: " + key.getAlgorithm()); }//from w w w.ja va2 s . co m // According to PKCS#1 AlgorithmIdentifier for RSA-PKCS#1 has null Parameters, this means a DER Null (asn.1 encoding of null), not Java null. // For the RSA signature algorithms specified above RFC3447 states "...the parameters MUST be present and MUST be NULL." PKIHeaderBuilder headerBuilder = getHeaderBuilder(pKIMessage.getHeader()); AlgorithmIdentifier pAlg = null; if ("RSA".equalsIgnoreCase(key.getAlgorithm())) { pAlg = new AlgorithmIdentifier(oid, DERNull.INSTANCE); } else { pAlg = new AlgorithmIdentifier(oid); } headerBuilder.setProtectionAlg(pAlg); // Most PKCS#11 providers don't like to be fed an OID as signature algorithm, so // we use BC classes to translate it into a signature algorithm name instead PKIHeader head = headerBuilder.build(); String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid); if (verbose) { log.info("Signing CMP message with signature alg: " + signatureAlgorithmName); } Signature sig = Signature.getInstance(signatureAlgorithmName, provider); sig.initSign(key); sig.update(getProtectedBytes(head, pKIMessage.getBody())); if ((extraCerts != null) && (extraCerts.length > 0)) { pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign()), extraCerts); } else { pKIMessage = new PKIMessage(head, pKIMessage.getBody(), new DERBitString(sig.sign())); } return pKIMessage; }
From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java
@Test public void testPkcs1Signature() throws Exception { // setup//from w w w .j ava 2 s .c o m KeyPair keyPair = PkiTestUtils.generateKeyPair(); byte[] toBeSigned = "hello world".getBytes(); // operate Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); // verify signature.initVerify(keyPair.getPublic()); signature.update(toBeSigned); boolean signatureResult = signature.verify(signatureValue); assertTrue(signatureResult); }
From source file:com.example.android.basicandroidkeystore.BasicAndroidKeyStoreFragment.java
/** * Signs the data using the key pair stored in the Android Key Store. This signature can be * used with the data later to verify it was signed by this application. * @return A string encoding of the data signature generated *//*from w w w . java 2s. c om*/ public String signData(String inputStr) throws KeyStoreException, UnrecoverableEntryException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, IOException, CertificateException { byte[] data = inputStr.getBytes(); // BEGIN_INCLUDE(sign_load_keystore) KeyStore ks = KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE); // Weird artifact of Java API. If you don't have an InputStream to load, you still need // to call "load", or it'll crash. ks.load(null); // Load the key pair from the Android Key Store KeyStore.Entry entry = ks.getEntry(mAlias, null); /* If the entry is null, keys were never stored under this alias. * Debug steps in this situation would be: * -Check the list of aliases by iterating over Keystore.aliases(), be sure the alias * exists. * -If that's empty, verify they were both stored and pulled from the same keystore * "AndroidKeyStore" */ if (entry == null) { Log.w(TAG, "No key found under alias: " + mAlias); Log.w(TAG, "Exiting signData()..."); return null; } /* If entry is not a KeyStore.PrivateKeyEntry, it might have gotten stored in a previous * iteration of your application that was using some other mechanism, or been overwritten * by something else using the same keystore with the same alias. * You can determine the type using entry.getClass() and debug from there. */ if (!(entry instanceof KeyStore.PrivateKeyEntry)) { Log.w(TAG, "Not an instance of a PrivateKeyEntry"); Log.w(TAG, "Exiting signData()..."); return null; } // END_INCLUDE(sign_data) // BEGIN_INCLUDE(sign_create_signature) // This class doesn't actually represent the signature, // just the engine for creating/verifying signatures, using // the specified algorithm. Signature s = Signature.getInstance(SecurityConstants.SIGNATURE_SHA256withRSA); // Initialize Signature using specified private key s.initSign(((KeyStore.PrivateKeyEntry) entry).getPrivateKey()); // Sign the data, store the result as a Base64 encoded String. s.update(data); byte[] signature = s.sign(); String result = Base64.encodeToString(signature, Base64.DEFAULT); // END_INCLUDE(sign_data) return result; }
From source file:com.mytalentfolio.h_daforum.CconnectToServer.java
/** * Returns the string formatted digital signature for the data. * /*from w w w . j av a2 s . c om*/ * @param key * Private key for signing the data. * @param data * Data for which the signature is to be generated. * @return signed data with the provide private key. * @throws NoSuchAlgorithmException * if the specified algorithm is not available. * @throws InvalidKeyException * if privateKey is not valid. * @throws SignatureException * if this Signature instance is not initialized properly. */ private String getDataSig(PrivateKey key, String data) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException { // Generate Signature For the data Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(key); signature.update(data.getBytes()); byte[] sigBytes = signature.sign(); return Base64.encodeToString(sigBytes, Base64.DEFAULT); }
From source file:org.apache.cxf.fediz.service.idp.protocols.TrustedIdpSAMLProtocolHandler.java
/** * Sign a request according to the redirect binding spec for Web SSO *///from ww w . j a v a2 s .c o m private void signRequest(String authnRequest, String relayState, Idp config, UriBuilder ub) throws Exception { Crypto crypto = getCrypto(config.getCertificate()); if (crypto == null) { LOG.error("No crypto instance of properties file configured for signature"); throw new IllegalStateException("Invalid IdP configuration"); } String alias = crypto.getDefaultX509Identifier(); X509Certificate cert = CertsUtils.getX509Certificate(crypto, alias); if (cert == null) { LOG.error("No cert was found to sign the request using alias: " + alias); throw new IllegalStateException("Invalid IdP configuration"); } String sigAlgo = SSOConstants.RSA_SHA1; String pubKeyAlgo = cert.getPublicKey().getAlgorithm(); String jceSigAlgo = "SHA1withRSA"; LOG.debug("automatic sig algo detection: " + pubKeyAlgo); if (pubKeyAlgo.equalsIgnoreCase("DSA")) { sigAlgo = SSOConstants.DSA_SHA1; jceSigAlgo = "SHA1withDSA"; } LOG.debug("Using Signature algorithm " + sigAlgo); ub.queryParam(SSOConstants.SIG_ALG, URLEncoder.encode(sigAlgo, "UTF-8")); // Get the password String password = config.getCertificatePassword(); // Get the private key PrivateKey privateKey = crypto.getPrivateKey(alias, password); // Sign the request Signature signature = Signature.getInstance(jceSigAlgo); signature.initSign(privateKey); String requestToSign = SSOConstants.SAML_REQUEST + "=" + authnRequest + "&" + SSOConstants.RELAY_STATE + "=" + relayState + "&" + SSOConstants.SIG_ALG + "=" + URLEncoder.encode(sigAlgo, "UTF-8"); signature.update(requestToSign.getBytes("UTF-8")); byte[] signBytes = signature.sign(); String encodedSignature = Base64.encode(signBytes); ub.queryParam(SSOConstants.SIGNATURE, URLEncoder.encode(encodedSignature, "UTF-8")); }
From source file:org.wso2.carbon.apimgt.impl.token.AbstractJWTGenerator.java
private byte[] signJWT(String assertion, String endUserName) throws APIManagementException { try {/*from ww w . j ava 2s . c om*/ //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:org.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java
@Override public String sign(String signingInput, String alias, String sharedSecret, SignatureAlgorithm signatureAlgorithm) throws Exception { if (signatureAlgorithm == SignatureAlgorithm.NONE) { return ""; } else if (SignatureAlgorithmFamily.HMAC.equals(signatureAlgorithm.getFamily())) { SecretKey secretKey = new SecretKeySpec(sharedSecret.getBytes(Util.UTF8_STRING_ENCODING), signatureAlgorithm.getAlgorithm()); Mac mac = Mac.getInstance(signatureAlgorithm.getAlgorithm()); mac.init(secretKey);/*w w w . ja v a 2 s.c o m*/ byte[] sig = mac.doFinal(signingInput.getBytes()); return Base64Util.base64urlencode(sig); } else { // EC or RSA PrivateKey privateKey = getPrivateKey(alias); Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm(), "BC"); //Signature signature = Signature.getInstance(signatureAlgorithm.getAlgorithm()); signature.initSign(privateKey); signature.update(signingInput.getBytes()); return Base64Util.base64urlencode(signature.sign()); } }