List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm, Provider provider) throws NoSuchAlgorithmException
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Sign a hash using the user's private key * //from w w w . j a v a 2s . co m * @param hash * @param key * @return * @throws Exception */ public byte[] signHash(byte[] hash, String password) throws Exception { String alg = config.getProperty(RepositoryManagedSignatureProviderFactory.SIGNATURE_ALGORITHM); String prov = config.getProperty(RepositoryManagedSignatureProviderFactory.JAVA_SIGNATURE_PROVIDER); String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS); KeyStore ks = getUserKeyStore(password); PrivateKey key = (PrivateKey) ks.getKey(alias, password.toCharArray()); Signature signer = Signature.getInstance(alg, prov); signer.initSign(key); signer.update(hash); return signer.sign(); }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
/** * Creates a test signature and verifies it. * * @param privateKey Private key to sign with * @param publicKey Public key to verify with * @param signatureProvider Name of provider to sign with * @throws NoSuchAlgorithmException In case the key or signature algorithm is unknown * @throws NoSuchProviderException In case the supplied provider name is unknown or BC is not installed * @throws InvalidKeyException If signature verification failed or the key was invalid * @throws SignatureException If the signature could not be made or verified correctly *//* w w w .j a v a2s .c om*/ public static void testSignAndVerify(PrivateKey privateKey, PublicKey publicKey, String signatureProvider) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException { final byte input[] = "Lillan gick pa vagen ut, motte dar en katt...".getBytes(); final String sigAlg = suggestSigAlg(publicKey); if (sigAlg == null) { throw new NoSuchAlgorithmException("Unknown key algorithm: " + publicKey.getAlgorithm()); } if (LOG.isDebugEnabled()) { LOG.debug("Testing keys with algorithm: " + publicKey.getAlgorithm()); LOG.debug("testSigAlg: " + sigAlg); LOG.debug("provider: " + signatureProvider); LOG.trace("privateKey: " + privateKey); LOG.trace("privateKey class: " + privateKey.getClass().getName()); LOG.trace("publicKey: " + publicKey); LOG.trace("publicKey class: " + publicKey.getClass().getName()); } final Signature signSignature = Signature.getInstance(sigAlg, signatureProvider); signSignature.initSign(privateKey); signSignature.update(input); byte[] signBA = signSignature.sign(); if (LOG.isTraceEnabled()) { LOG.trace("Created signature of size: " + signBA.length); LOG.trace("Created signature: " + new String(Hex.encode(signBA))); } final Signature verifySignature = Signature.getInstance(sigAlg, "BC"); verifySignature.initVerify(publicKey); verifySignature.update(input); if (!verifySignature.verify(signBA)) { throw new InvalidKeyException("Test signature inconsistent"); } }
From source file:org.xdi.oxauth.model.util.JwtUtil.java
public static byte[] getSignatureRS256(byte[] signingInput, RSAPrivateKey rsaPrivateKey) throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException, NoSuchAlgorithmException { RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec); Signature signature = Signature.getInstance("SHA256withRSA", "BC"); signature.initSign(privateKey);/*from w w w.j a va2 s.c o m*/ signature.update(signingInput); return signature.sign(); }
From source file:com.orange.oidc.secproxy_service.KryptoUtils.java
static public boolean verifyJWS(String s, String algorithm, PublicKey pubKey, PrivateKey privKey) { // algorithm = "SHA256withRSA"; // algorithm = "SHA1withRSA"; boolean bverify = false; String parts[] = s.split("\\."); if (parts == null || parts.length != 3) return bverify; try {//from w w w . ja va2s. c om if ("RS256".compareTo(algorithm) == 0) algorithm = "SHA256withRSA"; Signature signature = Signature.getInstance(algorithm, "SC"); signature.initVerify(pubKey); signature.update((parts[0] + "." + parts[1]).getBytes()); bverify = signature.verify(decodeB64(parts[2])); Log.d("verifyJWS", "payload: " + new String(decodeB64(parts[1]))); /* // verify signature signature.initSign(privKey); signature.update((parts[0]+"."+parts[1]).getBytes()); byte sig[] = signature.sign(); String sig64 = encodeB64(sig); Log.d("verifyJWS","compute: "+sig64); */ } catch (Exception e) { e.printStackTrace(); } return bverify; }
From source file:com.orange.oidc.tim.service.KryptoUtils.java
static public boolean verifyJWS(String s, String algorithm, PublicKey pubKey, PrivateKey privKey) { // algorithm = "SHA256withRSA"; // algorithm = "SHA1withRSA"; boolean bverify = false; String parts[] = s.split("\\."); if (parts == null || parts.length != 3) return bverify; try {//from www . j a va 2 s.c om if ("RS256".compareTo(algorithm) == 0) algorithm = "SHA256withRSA"; Signature signature = Signature.getInstance(algorithm, "SC"); signature.initVerify(pubKey); signature.update((parts[0] + "." + parts[1]).getBytes()); bverify = signature.verify(decodeB64(parts[2])); Log.d("verifyJWS", "payload: " + new String(decodeB64(parts[1]))); /* // verify signature signature.initSign(privKey); signature.update((parts[0]+"."+parts[1]).getBytes()); byte sig[] = signature.sign(); String sig64 = encodeB64(sig); Log.d("verifyJWS","compute: "+sig64); Log.d("verifyJWS","SIM : "+parts[2]); */ } catch (Exception e) { e.printStackTrace(); } return bverify; }
From source file:eu.europa.ejusticeportal.dss.applet.DssApplet.java
/** * This methods checks if the data coming from the server can be trusted. * The hash provided by the server is checked using the public key. * @param data the data coming from the server. * @param serverHash the hash of the data coming from the server. * @param algo the algorithm used for the server hash. * @return <code>true</code> if the serverHash can be verified with the public key. *//*from w w w . j ava 2s. co m*/ private boolean canTrustServerHash(final String data, final String serverHash, final String algo) { Certificate certificate; InputStream pemInputStream; try { pemInputStream = getClass().getClassLoader().getResourceAsStream("certificate.pem"); if (pemInputStream == null) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } } catch (Exception e) { LOG.log(Level.SEVERE, "Missing certificate.pem file. Impossible to check if the data coming from the server can be trusted."); return false; } try { certificate = CertificateFactory.getInstance("X.509").generateCertificate(pemInputStream); PublicKey publicKey = certificate.getPublicKey(); Signature sigVerify = Signature.getInstance(new String(Base64.decodeBase64(algo)), "BC"); sigVerify.initVerify(publicKey); sigVerify.update(data.getBytes("UTF-8")); boolean signatureMatch = sigVerify.verify(Base64.decodeBase64(serverHash)); if (signatureMatch) { LOG.log(Level.INFO, "The data coming from the server can be trusted."); return true; } else { LOG.log(Level.SEVERE, "!!! Tampered data received !!!"); LOG.log(Level.INFO, serverHash); LOG.log(Level.INFO, data); return false; } } catch (CertificateException e) { LOG.error(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { LOG.error(e.getMessage(), e); } catch (NoSuchProviderException e) { LOG.error(e.getMessage(), e); } catch (InvalidKeyException e) { LOG.error(e.getMessage(), e); } catch (SignatureException e) { LOG.error(e.getMessage(), e); } catch (UnsupportedEncodingException e) { LOG.error(e.getMessage(), e); } LOG.log(Level.SEVERE, "Impossible to check if the data coming from the server can be trusted."); return false; }
From source file:org.xdi.oxauth.model.util.JwtUtil.java
public static byte[] getSignatureRS384(byte[] signingInput, RSAPrivateKey rsaPrivateKey) throws SignatureException, InvalidKeyException, NoSuchProviderException, InvalidKeySpecException, NoSuchAlgorithmException { RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(), rsaPrivateKey.getPrivateExponent()); KeyFactory keyFactory = KeyFactory.getInstance("RSA", "BC"); PrivateKey privateKey = keyFactory.generatePrivate(rsaPrivateKeySpec); Signature signature = Signature.getInstance("SHA384withRSA", "BC"); signature.initSign(privateKey);//w w w . j a v a 2 s .c o m signature.update(signingInput); return signature.sign(); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static PKIMessage genCertReq(String issuerDN, X500Name userDN, String altNames, KeyPair keys, Certificate cacert, byte[] nonce, byte[] transid, boolean raVerifiedPopo, Extensions extensions, Date notBefore, Date notAfter, BigInteger customCertSerno, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, InvalidKeyException, SignatureException { ASN1EncodableVector optionalValidityV = new ASN1EncodableVector(); org.bouncycastle.asn1.x509.Time nb = new org.bouncycastle.asn1.x509.Time( new DERGeneralizedTime("20030211002120Z")); if (notBefore != null) { nb = new org.bouncycastle.asn1.x509.Time(notBefore); }// w ww . j a va 2s.co m optionalValidityV.add(new DERTaggedObject(true, 0, nb)); org.bouncycastle.asn1.x509.Time na = new org.bouncycastle.asn1.x509.Time(new Date()); if (notAfter != null) { na = new org.bouncycastle.asn1.x509.Time(notAfter); } 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(new X500Name(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); // If we did not pass any extensions as parameter, we will create some of our own, standard ones Extensions exts = extensions; if (exts == null) { // SubjectAltName // Some altNames 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 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 (raVerifiedPopo) { // raVerified POPO (meaning there is no POPO) myProofOfPossession = new ProofOfPossession(); } else { 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); } AttributeTypeAndValue av = new AttributeTypeAndValue(CRMFObjectIdentifiers.id_regCtrl_regToken, new DERUTF8String("foo123")); 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( new X500Name(issuerDN != null ? issuerDN : ((X509Certificate) cacert).getSubjectDN().getName()))); myPKIHeader.setMessageTime(new ASN1GeneralizedTime(new Date())); // senderNonce myPKIHeader.setSenderNonce(new DEROctetString(nonce)); // TransactionId myPKIHeader.setTransactionID(new DEROctetString(transid)); myPKIHeader.setProtectionAlg(pAlg); myPKIHeader.setSenderKID(senderKID); PKIBody myPKIBody = new PKIBody(0, myCertReqMessages); // initialization // request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.jets3t.service.security.EncryptionUtil.java
/** * Generate an RSA SHA1 signature of the given data using the given private * key DER certificate.//from w ww . j a va 2 s.c o m * * Based on example code from: * http://www.java2s.com/Tutorial/Java/0490__Security/RSASignatureGeneration.htm * http://forums.sun.com/thread.jspa?threadID=5175986 * * @throws NoSuchAlgorithmException * @throws InvalidKeyException * @throws SignatureException * @throws InvalidKeySpecException * @throws NoSuchProviderException */ public static byte[] signWithRsaSha1(byte[] derPrivateKeyBytes, byte[] dataToSign) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, InvalidKeySpecException, NoSuchProviderException { // Build an RSA private key from private key data PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(derPrivateKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(privSpec); // Sign data Signature signature = Signature.getInstance("SHA1withRSA", "BC"); signature.initSign(privateKey, new SecureRandom()); signature.update(dataToSign); byte[] signatureBytes = signature.sign(); return signatureBytes; }
From source file:org.ejbca.core.protocol.cmp.authentication.EndEntityCertificateAuthenticationModule.java
@Override /*//from w w w . j a va2 s .com * Verifies the signature of 'msg'. msg should be signed and the signer's certificate should be * attached in msg in the extraCert field. * * When successful, the authentication string is set. */ public boolean verifyOrExtract(final PKIMessage msg, final String username) { //Check that msg is signed if (msg.getProtection() == null) { this.errorMessage = "PKI Message is not athenticated properly. No PKI protection is found."; return false; } // Read the extraCert and store it in a local variable extraCert = getExtraCert(msg); if (extraCert == null) { this.errorMessage = "Error while reading the certificate in the extraCert field"; return false; } boolean vendormode = impl.isVendorCertificateMode(msg.getBody().getType(), this.confAlias); boolean omitVerifications = cmpConfiguration.getOmitVerificationsInEEC(confAlias); boolean ramode = cmpConfiguration.getRAMode(confAlias); if (log.isDebugEnabled()) { log.debug("CMP is operating in RA mode: " + this.cmpConfiguration.getRAMode(this.confAlias)); log.debug("CMP is operating in Vendor mode: " + vendormode); log.debug("CMP message already been authenticated: " + authenticated); log.debug("Omitting som verifications: " + omitVerifications); } //---------------------------------------------------------------------------------------- // Perform the different checks depending on the configuration and previous authentication //---------------------------------------------------------------------------------------- // Not allowed combinations. if (ramode && vendormode) { this.errorMessage = "Vendor mode and RA mode cannot be combined"; return false; } if (omitVerifications && (!ramode || !authenticated)) { this.errorMessage = "Omitting some verifications can only be accepted in RA mode and when the " + "CMP request has already been authenticated, for example, through the use of NestedMessageContent"; return false; } // Accepted combinations if (omitVerifications && ramode && authenticated) { // Do nothing here if (log.isDebugEnabled()) { log.debug( "Skipping some verification of the extraCert certificate in RA mode and an already authenticated CMP message, tex. through NestedMessageContent"); } } else if (ramode) { // Get the CA to use for the authentication CAInfo cainfo = getCAInfoByName(authenticationparameter); if (cainfo == null) return false; // Check that extraCert is in the Database CertificateInfo certinfo = certSession.getCertificateInfo(CertTools.getFingerprintAsString(extraCert)); if (certinfo == null) { this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database."; return false; } // More extraCert verifications if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) { return false; } // Check that extraCert belong to an admin with sufficient access rights if (!isAuthorizedAdmin(certinfo, msg, cainfo.getCAId())) { this.errorMessage = "'" + CertTools.getSubjectDN(extraCert) + "' is not an authorized administrator."; return false; } } else if (!ramode) { // client mode String extraCertUsername = null; if (vendormode) { // Check that extraCert is issued by a configured VendorCA if (!impl.isExtraCertIssuedByVendorCA(admin, this.confAlias, extraCert)) { this.errorMessage = "The certificate in extraCert field is not issued by any of the configured Vendor CAs: " + cmpConfiguration.getVendorCA(confAlias); return false; } // Extract the username from extraCert to use for further authentication String subjectDN = CertTools.getSubjectDN(extraCert); extraCertUsername = CertTools.getPartFromDN(subjectDN, this.cmpConfiguration.getExtractUsernameComponent(this.confAlias)); if (log.isDebugEnabled()) { log.debug("Username (" + extraCertUsername + ") was extracted from the '" + this.cmpConfiguration.getExtractUsernameComponent(this.confAlias) + "' part of the subjectDN of the certificate in the 'extraCerts' field."); } } else { // Get the CA to use for the authentication CAInfo cainfo = getCAInfoByIssuer(CertTools.getIssuerDN(extraCert)); // Check that extraCert is in the Database CertificateInfo certinfo = certSession .getCertificateInfo(CertTools.getFingerprintAsString(extraCert)); if (certinfo == null) { this.errorMessage = "The certificate attached to the PKIMessage in the extraCert field could not be found in the database."; return false; } // More extraCert verifications if (!isExtraCertIssuedByCA(cainfo) || !isExtraCertValid() || !isExtraCertActive(certinfo)) { return false; } // Extract the username from extraCert to use for further authentication extraCertUsername = certinfo.getUsername(); } // Check if this certificate belongs to the user if ((username != null) && (extraCertUsername != null)) { if (!StringUtils.equals(username, extraCertUsername)) { this.errorMessage = "The End Entity certificate attached to the PKIMessage in the extraCert field does not belong to user '" + username + "'"; if (log.isDebugEnabled()) { // Use a different debug message, as not to reveal too much information log.debug(this.errorMessage + ", but to user '" + extraCertUsername + "'"); } return false; } //set the password of the request to this user's password so it can later be used when issuing the certificate if (log.isDebugEnabled()) { log.debug( "The End Entity certificate attached to the PKIMessage in the extraCert field belongs to user '" + username + "'."); log.debug("Extracting and setting password for user '" + username + "'."); } try { EndEntityInformation user = eeAccessSession.findUser(admin, username); password = user.getPassword(); if (password == null) { password = genRandomPwd(); user.setPassword(password); eeManagementSession.changeUser(admin, user, false); } } catch (AuthorizationDeniedException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (CADoesntExistsException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (UserDoesntFullfillEndEntityProfile e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (WaitingForApprovalException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (EjbcaException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } } } //------------------------------------------------------------- //Begin the signature verification process. //Verify the signature of msg using the public key of extraCert //------------------------------------------------------------- try { final Signature sig = Signature.getInstance(msg.getHeader().getProtectionAlg().getAlgorithm().getId(), "BC"); sig.initVerify(extraCert.getPublicKey()); sig.update(CmpMessageHelper.getProtectedBytes(msg)); if (sig.verify(msg.getProtection().getBytes())) { if (password == null) { // If not set earlier password = genRandomPwd(); } } else { this.errorMessage = "Failed to verify the signature in the PKIMessage"; return false; } } catch (InvalidKeyException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (NoSuchAlgorithmException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (NoSuchProviderException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } catch (SignatureException e) { if (log.isDebugEnabled()) { log.debug(e.getLocalizedMessage()); } this.errorMessage = e.getLocalizedMessage(); return false; } return this.password != null; }