List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:be.fedict.eid.applet.service.impl.handler.AuthenticationDataMessageHandler.java
private void verifySignature(String signatureAlgo, byte[] signatureData, PublicKey publicKey, HttpServletRequest request, byte[]... data) throws ServletException { Signature signature;// www .j a va 2 s. c o m try { signature = Signature.getInstance(signatureAlgo); } catch (NoSuchAlgorithmException e) { throw new ServletException("algo error: " + e.getMessage(), e); } try { signature.initVerify(publicKey); } catch (InvalidKeyException e) { throw new ServletException("key error: " + e.getMessage(), e); } try { for (byte[] dataItem : data) { signature.update(dataItem); } boolean result = signature.verify(signatureData); if (false == result) { AuditService auditService = this.auditServiceLocator.locateService(); if (null != auditService) { String remoteAddress = request.getRemoteAddr(); auditService.identityIntegrityError(remoteAddress); } throw new ServletException("signature incorrect"); } } catch (SignatureException e) { throw new ServletException("signature error: " + e.getMessage(), e); } }
From source file:com.netscape.cms.servlet.test.DRMTest.java
/** * Verify the generated asymmetric key pair. * * @param keyAlgorithm - Algorithm used to generate keys. * @param privateKey - binary data of the private key. * @param publicKey - binary data of he public key. * @return/*from w w w . jav a 2 s . co m*/ * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException * @throws InvalidKeyException * @throws SignatureException * @throws IOException */ public static boolean isKeyPairValid(String keyAlgorithm, byte[] privateKey, byte[] publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, IOException { String algorithm = keyAlgorithm.toUpperCase(); String signingAlgorithm = "SHA1with" + algorithm; KeyFactory factory = KeyFactory.getInstance(algorithm); PrivateKey priKey = factory.generatePrivate(new PKCS8EncodedKeySpec(privateKey)); PublicKey pubKey = factory.generatePublic(new X509EncodedKeySpec(publicKey)); Signature sig = Signature.getInstance(signingAlgorithm); sig.initSign(priKey); String s = "Data to test asymmetric keys."; sig.update(s.getBytes()); // Sign the data with the private key. byte[] realSig = sig.sign(); Signature sig2 = Signature.getInstance(signingAlgorithm); sig2.initVerify(pubKey); sig2.update(s.getBytes()); // Verify the signature with the public key. return sig2.verify(realSig); }
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// w w w . j av a2 s.c o 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:test.unit.be.fedict.eid.applet.service.AuthenticationDataMessageHandlerTest.java
public void testHandleMessageWithoutAuditService() throws Exception { // setup//from w w w . j ava2 s. c om KeyPair keyPair = MiscTestUtils.generateKeyPair(); DateTime notBefore = new DateTime(); DateTime notAfter = notBefore.plusYears(1); String userId = "1234"; X509Certificate certificate = MiscTestUtils.generateCertificate(keyPair.getPublic(), "CN=Test, SERIALNUMBER=" + userId, notBefore, notAfter, null, keyPair.getPrivate(), true, 0, null, null); byte[] salt = "salt".getBytes(); byte[] sessionId = "session-id".getBytes(); AuthenticationDataMessage message = new AuthenticationDataMessage(); message.authnCert = certificate; message.saltValue = salt; message.sessionId = sessionId; Map<String, String> httpHeaders = new HashMap<String, String>(); HttpSession testHttpSession = new HttpTestSession(); HttpServletRequest mockServletRequest = EasyMock.createMock(HttpServletRequest.class); ServletConfig mockServletConfig = EasyMock.createMock(ServletConfig.class); byte[] challenge = AuthenticationChallenge.generateChallenge(testHttpSession); AuthenticationContract authenticationContract = new AuthenticationContract(salt, null, null, sessionId, null, challenge); byte[] toBeSigned = authenticationContract.calculateToBeSigned(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(keyPair.getPrivate()); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); message.signatureValue = signatureValue; EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.CHALLENGE_MAX_MATURITY_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(AuthenticationTestService.class.getName()); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.HOSTNAME_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INET_ADDRESS_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVER_CERTIFICATE)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.SESSION_ID_CHANNEL_BINDING_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_SECRET_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUDIT_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_IDENTITY_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_CERTS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_ADDRESS_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.INCLUDE_PHOTO_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME)) .andStubReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(HelloMessageHandler.IDENTITY_INTEGRITY_SERVICE_INIT_PARAM_NAME + "Class")) .andStubReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter(HelloMessageHandler.CHANNEL_BINDING_SERVICE + "Class")) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_ORG_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect( mockServletConfig.getInitParameter(AuthenticationDataMessageHandler.NRCID_APP_ID_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig .getInitParameter(AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME)) .andReturn(null); EasyMock.expect(mockServletConfig.getInitParameter( AuthenticationDataMessageHandler.AUTHN_SIGNATURE_SERVICE_INIT_PARAM_NAME + "Class")) .andReturn(null); EasyMock.expect(mockServletRequest.getAttribute("javax.servlet.request.ssl_session")) .andStubReturn(new String(Hex.encodeHex(sessionId))); EasyMock.expect(mockServletConfig.getInitParameter(IdentityDataMessageHandler.INCLUDE_DATA_FILES)) .andReturn(null); EasyMock.expect(mockServletRequest.getRemoteAddr()).andStubReturn("1.2.3.4"); // prepare EasyMock.replay(mockServletRequest, mockServletConfig); // operate AppletServiceServlet.injectInitParams(mockServletConfig, this.testedInstance); this.testedInstance.init(mockServletConfig); this.testedInstance.handleMessage(message, httpHeaders, mockServletRequest, testHttpSession); // verify EasyMock.verify(mockServletRequest, mockServletConfig); assertTrue(AuthenticationTestService.isCalled()); assertNull(AuditTestService.getAuditUserId()); assertEquals(userId, testHttpSession.getAttribute("eid.identifier")); }
From source file:nl.knmi.adaguc.services.oauth2.OAuth2Handler.java
/** * RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) using SHA-256 * //www .ja v a 2 s. c o m * @param modulus_n * @param exponent_e * @param signinInput_M * @param signature_S * @return * @throws SignatureException * @throws InvalidKeyException * @throws NoSuchAlgorithmException * @throws InvalidKeySpecException */ static boolean RSASSA_PKCS1_V1_5_VERIFY(String modulus_n, String exponent_e, String signinInput_M, String signature_S) throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException { Debug.println("Starting verification"); /* RSA SHA-256 RSASSA-PKCS1-V1_5-VERIFY */ // Modulus (n from https://www.googleapis.com/oauth2/v2/certs) String n = modulus_n; // Exponent (e from https://www.googleapis.com/oauth2/v2/certs) String e = exponent_e; // The JWT Signing Input (JWT Header and JWT Payload concatenated with // ".") byte[] M = signinInput_M.getBytes(); // Signature (JWT Crypto) byte[] S = Base64.decodeBase64(signature_S); byte[] modulusBytes = Base64.decodeBase64(n); byte[] exponentBytes = Base64.decodeBase64(e); BigInteger modulusInteger = new BigInteger(1, modulusBytes); BigInteger exponentInteger = new BigInteger(1, exponentBytes); RSAPublicKeySpec rsaPubKey = new RSAPublicKeySpec(modulusInteger, exponentInteger); KeyFactory fact = KeyFactory.getInstance("RSA"); PublicKey pubKey = fact.generatePublic(rsaPubKey); Signature signature = Signature.getInstance("SHA256withRSA"); signature.initVerify(pubKey); signature.update(M); boolean isVerified = signature.verify(S); Debug.println("Verify result [" + isVerified + "]"); return isVerified; }
From source file:uk.bowdlerize.API.java
@Deprecated private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException { PKCS8EncodedKeySpec spec;//from w ww.java2 s.c o m if (isUser) { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0)); } else { spec = new PKCS8EncodedKeySpec( Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0)); } KeyFactory kf = KeyFactory.getInstance("RSA", "BC"); PrivateKey pk = kf.generatePrivate(spec); byte[] signed = null; //Log.e("algorithm", pk.getAlgorithm()); Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(pk); instance.update(dataToSign.getBytes()); signed = instance.sign(); Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, "")); Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "")); //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP)); return Base64.encodeToString(signed, Base64.NO_WRAP); }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * This method writes what readCredential() method expects to read. (Note the use of singular * credential). It is similar to writeCredentials(), except that it doesn't write * credential-properties./*from w w w . j av a2s .co m*/ */ public byte writeCredential(DataOutputStream dos, DataInputStream dis, String authInit, boolean isNotification, DistributedMember member, HeapDataOutputStream heapdos) throws IOException, GemFireSecurityException { if (!this.multiuserSecureMode && (authInit == null || authInit.length() == 0)) { // No credentials indicator heapdos.writeByte(CREDENTIALS_NONE); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } if (dhSKAlgo == null || dhSKAlgo.length() == 0) { // Normal credentials without encryption indicator heapdos.writeByte(CREDENTIALS_NORMAL); this.appSecureMode = CREDENTIALS_NORMAL; // DataSerializer.writeProperties(p_credentials, heapdos); heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); return -1; } byte acceptanceCode = -1; try { InternalLogWriter securityLogWriter = (InternalLogWriter) this.system.getSecurityLogWriter(); securityLogWriter.fine("HandShake: using Diffie-Hellman key exchange with algo " + dhSKAlgo); boolean requireAuthentication = (certificateFilePath != null && certificateFilePath.length() > 0); if (requireAuthentication) { securityLogWriter.fine("HandShake: server authentication using digital " + "signature required"); } // Credentials with encryption indicator heapdos.writeByte(CREDENTIALS_DHENCRYPT); this.appSecureMode = CREDENTIALS_DHENCRYPT; heapdos.writeBoolean(requireAuthentication); // Send the symmetric encryption algorithm name DataSerializer.writeString(dhSKAlgo, heapdos); // Send the DH public key byte[] keyBytes = dhPublicKey.getEncoded(); DataSerializer.writeByteArray(keyBytes, heapdos); byte[] clientChallenge = null; if (requireAuthentication) { // Authentication of server should be with the client supplied // challenge clientChallenge = new byte[64]; random.nextBytes(clientChallenge); DataSerializer.writeByteArray(clientChallenge, heapdos); } heapdos.flush(); dos.write(heapdos.toByteArray()); dos.flush(); // Expect the alias and signature in the reply acceptanceCode = dis.readByte(); if (acceptanceCode != REPLY_OK && acceptanceCode != REPLY_AUTH_NOT_REQUIRED) { // Ignore the useless data dis.readByte(); dis.readInt(); if (!isNotification) { DataSerializer.readByteArray(dis); } readMessage(dis, dos, acceptanceCode, member); } else if (acceptanceCode == REPLY_OK) { // Get the public key of the other side keyBytes = DataSerializer.readByteArray(dis); if (requireAuthentication) { String subject = DataSerializer.readString(dis); byte[] signatureBytes = DataSerializer.readByteArray(dis); if (!certificateMap.containsKey(subject)) { throw new AuthenticationFailedException( LocalizedStrings.HandShake_HANDSHAKE_FAILED_TO_FIND_PUBLIC_KEY_FOR_SERVER_WITH_SUBJECT_0 .toLocalizedString(subject)); } // Check the signature with the public key X509Certificate cert = (X509Certificate) certificateMap.get(subject); Signature sig = Signature.getInstance(cert.getSigAlgName()); sig.initVerify(cert); sig.update(clientChallenge); // Check the challenge string if (!sig.verify(signatureBytes)) { throw new AuthenticationFailedException( "Mismatch in client " + "challenge bytes. Malicious server?"); } securityLogWriter .fine("HandShake: Successfully verified the " + "digital signature from server"); } // Read server challenge bytes byte[] serverChallenge = DataSerializer.readByteArray(dis); X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes); KeyFactory keyFact = KeyFactory.getInstance("DH"); // PublicKey pubKey = keyFact.generatePublic(x509KeySpec); this.clientPublicKey = keyFact.generatePublic(x509KeySpec); HeapDataOutputStream hdos = new HeapDataOutputStream(Version.CURRENT); try { // Add the challenge string DataSerializer.writeByteArray(serverChallenge, hdos); // byte[] encBytes = encrypt.doFinal(hdos.toByteArray()); byte[] encBytes = encryptBytes(hdos.toByteArray(), getEncryptCipher(dhSKAlgo, this.clientPublicKey)); DataSerializer.writeByteArray(encBytes, dos); } finally { hdos.close(); } } } catch (IOException ex) { throw ex; } catch (GemFireSecurityException ex) { throw ex; } catch (Exception ex) { throw new AuthenticationFailedException("HandShake failed in Diffie-Hellman key exchange", ex); } dos.flush(); return acceptanceCode; }
From source file:com.yourkey.billing.util.InAppBilling.java
private boolean verifySignature(String signedData, String signature) { try {/*from w w w . j a v a 2 s. c o m*/ // do it only once if (appPublicKey == null) { // decode application public key from base64 to binary byte[] decodedKey = decodeBase64(appPublicKeyStr); if (decodedKey == null) return (false); // convert public key from binary to PublicKey object appPublicKey = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM) .generatePublic(new X509EncodedKeySpec(decodedKey)); } // decode signature byte[] decodedSig = decodeBase64(signature); if (decodedSig == null) return (false); // verify signature Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(appPublicKey); sig.update(signedData.getBytes()); return (sig.verify(decodedSig)); } catch (Exception e) { return (false); } }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
public Properties readCredential(DataInputStream dis, DataOutputStream dos, DistributedSystem system) throws GemFireSecurityException, IOException { Properties credentials = null; boolean requireAuthentication = securityService.isClientSecurityRequired(); try {//from ww w. j a v a 2 s .co m byte secureMode = dis.readByte(); throwIfMissingRequiredCredentials(requireAuthentication, secureMode != CREDENTIALS_NONE); if (secureMode == CREDENTIALS_NORMAL) { this.appSecureMode = CREDENTIALS_NORMAL; /* * if (requireAuthentication) { credentials = DataSerializer.readProperties(dis); } else { * DataSerializer.readProperties(dis); // ignore the credentials } */ } else if (secureMode == CREDENTIALS_DHENCRYPT) { this.appSecureMode = CREDENTIALS_DHENCRYPT; boolean sendAuthentication = dis.readBoolean(); InternalLogWriter securityLogWriter = (InternalLogWriter) system.getSecurityLogWriter(); // Get the symmetric encryption algorithm to be used // String skAlgo = DataSerializer.readString(dis); this.clientSKAlgo = 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"); this.clientPublicKey = 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); Cipher c = getDecryptCipher(this.clientSKAlgo, this.clientPublicKey); byte[] credentialBytes = decryptBytes(encBytes, c); ByteArrayInputStream bis = new ByteArrayInputStream(credentialBytes); DataInputStream dinp = new DataInputStream(bis); // credentials = DataSerializer.readProperties(dinp);//Hitesh: we don't send in handshake // now 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(); } } } 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:org.ejbca.core.protocol.scep.ProtocolScepHttpTest.java
/** * checks that a public and private key matches by signing and verifying a message *///from ww w.j a v a2 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); }