List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
public static Properties readCredentials(DataInputStream dis, DataOutputStream dos, DistributedSystem system, SecurityService securityService) throws GemFireSecurityException, IOException { boolean requireAuthentication = securityService.isClientSecurityRequired(); Properties credentials = null; try {/*from w w w. j a v a2 s.c om*/ byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { DataSerializer.readProperties(dis); // ignore the credentials } } else if (secureMode == CREDENTIALS_DHENCRYPT) { boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used String skAlgo = DataSerializer.readString(dis); // Get the public key of the other side byte[] keyBytes = DataSerializer.readByteArray(dis); byte[] challenge = null; PublicKey pubKey = null; if (requireAuthentication) { // Generate PublicKey from encoded form X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); pubKey = keyFact.generatePublic(x509KeySpec); // Send the public key to other side keyBytes = dhPublicKey.getEncoded(); challenge = new byte[64]; random.nextBytes(challenge); // If the server has to also authenticate itself then // sign the challenge from client. if (sendAuthentication) { // Get the challenge string from client byte[] clientChallenge = DataSerializer.readByteArray(dis); if (privateKeyEncrypt == null) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_SERVER_PRIVATE_KEY_NOT_AVAILABLE_FOR_CREATING_SIGNATURE .toLocalizedString()); } // Sign the challenge from client and send it to the client Signature sig = Signature.getInstance(privateKeySignAlgo); sig.initSign(privateKeyEncrypt); sig.update(clientChallenge); byte[] signedBytes = sig.sign(); dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); // DataSerializer.writeString(privateKeyAlias, dos); DataSerializer.writeString(privateKeySubject, dos); DataSerializer.writeByteArray(signedBytes, dos); securityLogWriter.fine("HandShake: sent the signed client challenge"); } else { // These two lines should not be moved before the if{} statement in // a common block for both if...then...else parts. This is to handle // the case when an AuthenticationFailedException is thrown by the // if...then part when sending the signature. dos.writeByte(REPLY_OK); DataSerializer.writeByteArray(keyBytes, dos); } // Now send the server challenge DataSerializer.writeByteArray(challenge, dos); securityLogWriter.fine("HandShake: sent the public key and challenge"); dos.flush(); // Read and decrypt the credentials byte[] encBytes = DataSerializer.readByteArray(dis); KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(dhPrivateKey); ka.doPhase(pubKey, true); Cipher decrypt; int keysize = getKeySize(skAlgo); int blocksize = getBlockSize(skAlgo); if (keysize == -1 || blocksize == -1) { SecretKey sKey = ka.generateSecret(skAlgo); decrypt = Cipher.getInstance(skAlgo); decrypt.init(Cipher.DECRYPT_MODE, sKey); } else { String algoStr = getDhAlgoStr(skAlgo); byte[] sKeyBytes = ka.generateSecret(); SecretKeySpec sks = new SecretKeySpec(sKeyBytes, 0, keysize, algoStr); IvParameterSpec ivps = new IvParameterSpec(sKeyBytes, keysize, blocksize); decrypt = Cipher.getInstance(algoStr + "/CBC/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, sks, ivps); } byte[] credentialBytes = decrypt.doFinal(encBytes); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); credentials = DataSerializer.readProperties(dinp); byte[] challengeRes = DataSerializer.readByteArray(dinp); // Check the challenge string if (!Arrays.equals(challenge, challengeRes)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_MISMATCH_IN_CHALLENGE_BYTES_MALICIOUS_CLIENT .toLocalizedString()); } dinp.close(); } else { if (sendAuthentication) { // Read and ignore the client challenge DataSerializer.readByteArray(dis); } dos.writeByte(REPLY_AUTH_NOT_REQUIRED); dos.flush(); } } else if (secureMode == SECURITY_MULTIUSER_NOTIFICATIONCHANNEL) { // hitesh there will be no credential CCP will get credential(Principal) using // ServerConnection.. logger.debug("readCredential where multiuser mode creating callback connection"); } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_FAILURE_IN_READING_CREDENTIALS.toLocalizedString(), ex); } return credentials; }
From source file:com.vmware.identity.samlservice.impl.SamlServiceImpl.java
@Override public String signMessage(String message) throws IllegalStateException { Validate.notNull(this.getSignAlgorithm()); Validate.notNull(this.getPrivateKey()); try {//from ww w . ja v a 2s . c om Signature sig = Signature.getInstance(this.getSignAlgorithm().getAlgorithmName()); sig.initSign(privateKey); byte[] messageBytes = message.getBytes("UTF-8"); sig.update(messageBytes); byte[] sigBytes = sig.sign(); String signature = Shared.encodeBytes(sigBytes); if (signature == null || signature.isEmpty()) { log.debug("Invalid signature - either null or empty. "); } return signature; } catch (Exception e) { log.error("Caught exception while signing message " + message + ", sigAlg " + this.getSignAlgorithm().getAlgorithmName()); throw new IllegalStateException(e); } }
From source file:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
/** * checks that a public and private key matches by signing and verifying a message *///from w w w.ja v a 2 s. c o m private boolean checkKeys(PrivateKey priv, PublicKey pub) throws SignatureException, NoSuchAlgorithmException, InvalidKeyException { Signature signer = Signature.getInstance("SHA1WithRSA"); signer.initSign(priv); signer.update("PrimeKey".getBytes()); byte[] signature = signer.sign(); Signature signer2 = Signature.getInstance("SHA1WithRSA"); signer2.initVerify(pub); signer2.update("PrimeKey".getBytes()); return signer2.verify(signature); }
From source file:zlicense.de.schlichtherle.xml.GenericCertificate.java
public final synchronized void sign(Object paramObject, PrivateKey paramPrivateKey, Signature paramSignature) throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException, PersistenceServiceException, InvalidKeyException { if (paramPrivateKey == null) { throw new NullPointerException("signingKey"); }/*from ww w . ja v a 2 s . c om*/ if (paramSignature == null) { throw new NullPointerException("signingEngine"); } PropertyChangeEvent localPropertyChangeEvent = new PropertyChangeEvent(this, "locked", Boolean.valueOf(isLocked()), Boolean.TRUE); if (isLocked()) { throw new GenericCertificateIsLockedException(localPropertyChangeEvent); } fireVetoableChange(localPropertyChangeEvent); try { byte[] arrayOfByte1 = PersistenceService.store2ByteArray(paramObject); paramSignature.initSign(paramPrivateKey); paramSignature.update(arrayOfByte1); byte[] arrayOfByte2 = Base64.encodeBase64(paramSignature.sign()); String str = new String(arrayOfByte2, 0, arrayOfByte2.length, "US-ASCII"); setEncoded(new String(arrayOfByte1, "UTF-8")); setSignature(str); setSignatureAlgorithm(paramSignature.getAlgorithm()); setSignatureEncoding("US-ASCII/Base64"); } catch (UnsupportedEncodingException localUnsupportedEncodingException) { throw new AssertionError(localUnsupportedEncodingException); } catch (SignatureException localSignatureException) { throw new AssertionError(localSignatureException); } this.locked = true; firePropertyChange(localPropertyChangeEvent); }
From source file:org.dasein.security.joyent.SignatureHttpAuth.java
@Override public void addPreemptiveAuth(@Nonnull HttpRequest request) throws CloudException, InternalException { if (provider.getContext() == null) { throw new CloudException("No context was defined for this request"); }/*from w w w .j a v a 2s .c om*/ Date date = Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTime(); String now = RFC1123_DATE_FORMAT.format(date); request.setHeader("Date", now); try { Security.addProvider(new BouncyCastleProvider()); Signature signature = Signature.getInstance(SIGN_ALGORITHM); List<ContextRequirements.Field> fields = provider.getContextRequirements().getConfigurableValues(); String keyName = ""; String privateKey = ""; char[] keyPassword = null; for (ContextRequirements.Field f : fields) { if (f.type.equals(ContextRequirements.FieldType.KEYPAIR)) { byte[][] keyPair = (byte[][]) provider.getContext().getConfigurationValue(f); keyName = new String(keyPair[0], "utf-8"); privateKey = new String(keyPair[1], "utf-8"); } else if (f.type.equals(ContextRequirements.FieldType.PASSWORD)) { byte[] password = (byte[]) provider.getContext().getConfigurationValue(f); if (password != null) { keyPassword = new String(password, "utf-8").toCharArray(); } } } signature.initSign(getKeyPair(privateKey, keyPassword).getPrivate()); String signingString = String.format(AUTH_SIGN, now); signature.update(signingString.getBytes("UTF-8")); byte[] signedDate = signature.sign(); byte[] encodedSignedDate = Base64.encode(signedDate); request.addHeader("Authorization", String.format(AUTH_HEADER, provider.getContext().getAccountNumber(), keyName, new String(encodedSignedDate))); } catch (NoSuchAlgorithmException e) { throw new InternalException(e); } catch (UnsupportedEncodingException e) { throw new InternalException(e); } catch (SignatureException e) { throw new InternalException(e); } catch (InvalidKeyException e) { throw new InternalException(e); } catch (IOException e) { throw new InternalException(e); } }
From source file:org.hyperledger.fabric.sdk.security.CryptoPrimitives.java
/** * Sign data with the specified elliptic curve private key. * * @param privateKey elliptic curve private key. * @param data data to sign//from w w w.j a v a2s .co m * @return the signed data. * @throws CryptoException */ private byte[] ecdsaSignToBytes(ECPrivateKey privateKey, byte[] data) throws CryptoException { if (data == null) { throw new CryptoException("Data that to be signed is null."); } if (data.length == 0) { throw new CryptoException("Data to be signed was empty."); } try { X9ECParameters params = ECNamedCurveTable.getByName(curveName); BigInteger curveN = params.getN(); Signature sig = SECURITY_PROVIDER == null ? Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM) : Signature.getInstance(DEFAULT_SIGNATURE_ALGORITHM, SECURITY_PROVIDER); sig.initSign(privateKey); sig.update(data); byte[] signature = sig.sign(); BigInteger[] sigs = decodeECDSASignature(signature); sigs = preventMalleability(sigs, curveN); try (ByteArrayOutputStream s = new ByteArrayOutputStream()) { DERSequenceGenerator seq = new DERSequenceGenerator(s); seq.addObject(new ASN1Integer(sigs[0])); seq.addObject(new ASN1Integer(sigs[1])); seq.close(); return s.toByteArray(); } } catch (Exception e) { throw new CryptoException("Could not sign the message using private key", e); } }
From source file:com.alfaariss.oa.authentication.remote.AbstractRemoteMethod.java
/** * Creates a signature over the supplied attributes in the map. * <br>/*from www . ja v a2s . c o m*/ * Uses a TreeSet to sort the request parameter names. * @param mapRequest A map containing the attributes to be signed. * @return The signed request attributes. * @throws OAException */ protected String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null; try { Signature oSignature = _cryptoManager.getSignature(); if (oSignature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } oSignature.initSign(keyPrivate); oSignature.update(sbSignatureData.toString().getBytes(CHARSET)); byte[] baSignature = oSignature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
From source file:com.alfaariss.oa.profile.aselect.logout.LogoutManager.java
private String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null;//from w w w . ja v a 2s . c om try { if (_cryptoManager == null) { _logger.warn("No crypto manager available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } Signature signature = _cryptoManager.getSignature(); if (signature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } signature.initSign(keyPrivate); signature.update(sbSignatureData.toString().getBytes(ASelectProcessor.CHARSET)); byte[] baSignature = signature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, ASelectProcessor.CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
From source file:com.alfaariss.oa.authentication.remote.aselect.logout.LogoutManager.java
private String createSignature(Map<String, String> mapRequest) throws OAException { String sSignature = null;/*from w w w. ja va2s . com*/ try { if (_cryptoManager == null) { _logger.warn("No crypto manager available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } Signature signature = _cryptoManager.getSignature(); if (signature == null) { _logger.warn("No signature object found"); throw new OAException(SystemErrors.ERROR_INTERNAL); } StringBuffer sbSignatureData = new StringBuffer(); TreeSet<String> sortedSet = new TreeSet<String>(mapRequest.keySet()); for (Iterator<String> iter = sortedSet.iterator(); iter.hasNext();) { String sKey = iter.next(); sbSignatureData.append(mapRequest.get(sKey)); } PrivateKey keyPrivate = _cryptoManager.getPrivateKey(); if (keyPrivate == null) { _logger.error("No private key available"); throw new OAException(SystemErrors.ERROR_INTERNAL); } signature.initSign(keyPrivate); signature.update(sbSignatureData.toString().getBytes(CHARSET)); byte[] baSignature = signature.sign(); byte[] baEncSignature = Base64.encodeBase64(baSignature); sSignature = new String(baEncSignature, CHARSET); } catch (OAException e) { throw e; } catch (Exception e) { _logger.fatal("Could not create signature for data: " + mapRequest, e); throw new OAException(SystemErrors.ERROR_INTERNAL); } return sSignature; }
From source file:de.schlichtherle.xml.GenericCertificate.java
/** * Encodes and signs the given <tt>content</tt> in this certificate and * locks it.//from ww w. ja v a2 s. c om * <p> * Please note the following: * <ul> * <li>This method will throw a <tt>PropertyVetoException</tt> if this * certificate is already locked, i.e. if it has been signed or * verified before.</li> * <li>Because this method locks this certificate, a subsequent call to * {@link #sign(Object, PrivateKey, Signature)} or * {@link #verify(PublicKey, Signature)} is redundant * and will throw a <tt>PropertyVetoException</tt>. * Use {@link #isLocked()} to detect whether a * generic certificate has been successfuly signed or verified before * or call {@link #getContent()} and expect an * Exception to be thrown if it hasn't.</li> * <li>There is no way to unlock this certificate. * Call the copy constructor of {@link GenericCertificate} if you * need an unlocked copy of the certificate.</li> * </ul> * * @param content The object to sign. This must either be a JavaBean or an * instance of any other class which is supported by * <tt>{@link PersistenceService}</tt> * - maybe <tt>null</tt>. * @param signingKey The private key for signing * - may <em>not</em> be <tt>null</tt>. * @param signingEngine The signature signing engine * - may <em>not</em> be <tt>null</tt>. * * @throws NullPointerException If the preconditions for the parameters * do not hold. * @throws GenericCertificateIsLockedException If this certificate is * already locked by signing or verifying it before. * Note that this is actually a subclass of * {@link PropertyVetoException}. * @throws PropertyVetoException If locking the certifificate (and thus * signing the object) is vetoed by any listener. * @throws PersistenceServiceException If the object cannot be serialised. * @throws InvalidKeyException If the verification key is invalid. */ public synchronized final void sign(final Object content, final PrivateKey signingKey, final Signature signingEngine) throws NullPointerException, GenericCertificateIsLockedException, PropertyVetoException, PersistenceServiceException, InvalidKeyException { // Check parameters. if (signingKey == null) throw new NullPointerException("signingKey"); if (signingEngine == null) throw new NullPointerException("signingEngine"); // Check lock status. final PropertyChangeEvent evt = new PropertyChangeEvent(this, "locked", Boolean.valueOf(isLocked()), Boolean.TRUE); // NOI18N if (isLocked()) throw new GenericCertificateIsLockedException(evt); // Notify vetoable listeners and give them a chance to veto. fireVetoableChange(evt); try { // Encode the object. final byte[] beo = PersistenceService.store2ByteArray(content); // Sign the byte encoded object. signingEngine.initSign(signingKey); signingEngine.update(beo); final byte[] b64es = Base64.encodeBase64(signingEngine.sign()); // the base64 encoded signature final String signature = new String(b64es, 0, b64es.length, BASE64_CHARSET); // Store results. setEncoded(new String(beo, XML_CHARSET)); setSignature(signature); setSignatureAlgorithm(signingEngine.getAlgorithm()); setSignatureEncoding(SIGNATURE_ENCODING); // NOI18N } catch (UnsupportedEncodingException cannotHappen) { throw new AssertionError(cannotHappen); } catch (SignatureException cannotHappen) { throw new AssertionError(cannotHappen); } // Lock this certificate and notify property change listeners. this.locked = true; firePropertyChange(evt); }