List of usage examples for java.security Signature initSign
public final void initSign(PrivateKey privateKey) throws InvalidKeyException
From source file:mx.com.quadrum.service.util.firma.ValidacionesCertificado.java
/** * Mtodo que valida el password y que la llave privada corresponda a la * llave publica//from w w w . j av a2s. co m * * @return true si el password y llave privada corresponden, en otro caso * false */ public boolean validaCorrespondencias() { try { PKCS8Key pkcs8 = new PKCS8Key(this.clavePrivada, this.password.toCharArray()); //valida el pass PrivateKey pk = pkcs8.getPrivateKey(); //valida que la llave privada corresponda a la llave publica X509Certificate cert = X509Certificate.getInstance(this.clavePublica); Signature firma = Signature.getInstance("SHA1withRSA"); firma.initSign(pk); byte[] firmado = firma.sign(); firma.initVerify(cert.getPublicKey()); if (firma.verify(firmado)) { return this.correcto; } else { return this.error; } } catch (GeneralSecurityException e) { return this.error; } catch (CertificateException e) { return this.error; } }
From source file:com.vimukti.accounter.license.LicenseManager.java
public LicensePair doEncode(License license) { byte[] licenseText = null; byte[] hash;// www . ja va 2 s.co m try { licenseText = Zip.compressBytes(new PropertiesPersister().getLicenseAsString(license)); } catch (UnsupportedEncodingException e) { throw new LicenseException(e); } catch (IOException e) { throw new LicenseException(e); } try { Signature signature = Signature.getInstance("SHA1withDSA"); signature.initSign(getPrivateKey()); signature.update(licenseText); hash = signature.sign(); } catch (InvalidKeyException e) { throw new LicenseException(e); } catch (SignatureException e) { throw new LicenseException(e); } catch (NoSuchAlgorithmException e) { throw new LicenseException(e); } String packLicense = packLicense(licenseText, hash); return new LicensePair(licenseText, hash, packLicense); }
From source file:com.adito.security.pki.dsa.SshDssPrivateKey.java
/** * * * @param data/*from w w w .java 2 s . com*/ * * @return * * @throws InvalidSshKeySignatureException */ public byte[] generateSignature(byte[] data) throws InvalidSignatureException { try { Signature sig = Signature.getInstance("SHA1withDSA"); sig.initSign(prvkey); sig.update(data); byte[] signature = sig.sign(); byte[] decoded = new byte[40]; SimpleASNReader asn = new SimpleASNReader(signature); asn.getByte(); asn.getLength(); asn.getByte(); byte[] r = asn.getData(); asn.getByte(); byte[] s = asn.getData(); if (r.length >= 20) { System.arraycopy(r, r.length - 20, decoded, 0, 20); } else { System.arraycopy(r, 0, decoded, 20 - r.length, r.length); } if (s.length >= 20) { System.arraycopy(s, s.length - 20, decoded, 20, 20); } else { System.arraycopy(s, 0, decoded, 20 + (20 - s.length), s.length); } if (log.isDebugEnabled()) { log.debug("s length is " + String.valueOf(s.length)); log.debug("r length is " + String.valueOf(r.length)); String str = ""; for (int i = 0; i < signature.length; i++) { str += (Integer.toHexString(signature[i] & 0xFF) + " "); } log.debug("Java signature is " + str); str = ""; for (int i = 0; i < decoded.length; i++) { str += (Integer.toHexString(decoded[i] & 0xFF) + " "); } log.debug("SSH signature is " + str); } ByteArrayWriter baw = new ByteArrayWriter(); baw.writeString(getAlgorithmName()); baw.writeBinaryString(decoded); return baw.toByteArray(); } catch (Exception e) { throw new InvalidSignatureException(e); } }
From source file:com.subgraph.vega.internal.http.proxy.ssl.CertificateCreator.java
private X500Signer createCertificateSigner(X500Principal issuer, PrivateKey issuerPrivate) throws IOException, GeneralSecurityException { final X500Name issuerName = new X500Name(issuer.getName()); final Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); signature.initSign(issuerPrivate); return new X500Signer(signature, issuerName); }
From source file:service.GoogleCalendarAuth.java
public GoogleCalendarAuth(String client_id, String key) { final long now = System.currentTimeMillis() / 1000L; final long exp = now + 3600; final char[] password = "notasecret".toCharArray(); final String claim = "{\"iss\":\"" + client_id + "\"," + "\"scope\":\"" + SCOPE + "\"," + "\"aud\":\"https://accounts.google.com/o/oauth2/token\"," + "\"exp\":" + exp + "," + // "\"prn\":\"some.user@somecorp.com\"," + // This require some.user to have their email served from a googlemail domain? "\"iat\":" + now + "}"; try {/*from ww w . ja v a2 s.c om*/ final String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); final byte[] jwt_data = jwt.getBytes("UTF8"); final Signature sig = Signature.getInstance("SHA256WithRSA"); final KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), password); sig.initSign((PrivateKey) ks.getKey("privatekey", password)); sig.update(jwt_data); final byte[] signatureBytes = sig.sign(); final String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); final String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); final String data = "grant_type=assertion" + "&assertion_type=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8") + "&assertion=" + URLEncoder.encode(assertion, "UTF-8"); // Make the Access Token Request URLConnection conn = null; try { final URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { final InputStream error = ((HttpURLConnection) conn).getErrorStream(); final BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) sb.append(line); System.out.println("Error: " + ex + "\n " + sb.toString()); } System.out.println("access_token=" + access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }
From source file:GCS_Auth.java
public GCS_Auth(String client_id, String key) { String SCOPE = "https://www.googleapis.com/auth/shoppingapi"; SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent"; try {/* ww w . j av a 2 s . co m*/ String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; long now = System.currentTimeMillis() / 1000L; long exp = now + 3600; String iss = client_id; String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now + "}"; String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "." + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8")); byte[] jwt_data = jwt.getBytes("UTF8"); Signature sig = Signature.getInstance("SHA256WithRSA"); KeyStore ks = java.security.KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(key), "notasecret".toCharArray()); sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray())); sig.update(jwt_data); byte[] signatureBytes = sig.sign(); String b64sig = Base64.encodeBase64URLSafeString(signatureBytes); String assertion = jwt + "." + b64sig; //System.out.println("Assertion: " + assertion); String data = "grant_type=assertion"; data += "&" + "assertion_type" + "=" + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8"); data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8"); URLConnection conn = null; try { URL url = new URL("https://accounts.google.com/o/oauth2/token"); conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); wr.write(data); wr.flush(); BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { if (line.split(":").length > 0) if (line.split(":")[0].trim().equals("\"access_token\"")) access_token = line.split(":")[1].trim().replace("\"", "").replace(",", ""); System.out.println(line); } wr.close(); rd.close(); } catch (Exception ex) { InputStream error = ((HttpURLConnection) conn).getErrorStream(); BufferedReader br = new BufferedReader(new InputStreamReader(error)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line); } System.out.println("Error: " + ex + "\n " + sb.toString()); } //System.out.println(access_token); } catch (Exception ex) { System.out.println("Error: " + ex); } }
From source file:test.be.fedict.eid.applet.RSATest.java
@Test public void testPSS() throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); SecureRandom random = new SecureRandom(); keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random); KeyPair keyPair = keyPairGenerator.generateKeyPair(); PrivateKey privateKey = keyPair.getPrivate(); PublicKey publicKey = keyPair.getPublic(); Signature signature = Signature.getInstance("SHA256withRSA/PSS", "BC"); byte[] data = "hello world".getBytes(); signature.initSign(privateKey); signature.update(data);/*w w w . j a v a 2 s . c om*/ byte[] signatureValue = signature.sign(); LOG.debug("signature size: " + signatureValue.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue))); signature.initVerify(publicKey); signature.update(data); boolean result = signature.verify(signatureValue); assertTrue(result); signature.initSign(privateKey); signature.update(data); byte[] signatureValue2 = signature.sign(); LOG.debug("signature size: " + signatureValue2.length); LOG.debug("signature value: " + new String(Hex.encodeHex(signatureValue2))); assertFalse(Arrays.equals(signatureValue, signatureValue2)); MessageDigest messageDigest = MessageDigest.getInstance("SHA-256", "BC"); byte[] digest = messageDigest.digest(data); signature = Signature.getInstance("RAWRSASSA-PSS", "BC"); signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); signature.initVerify(publicKey); signature.update(digest); result = signature.verify(signatureValue); assertTrue(result); }
From source file:net.sf.dsig.query.QuerystringStrategy.java
private String signInternal(String plaintext, PrivateKey privateKey) throws Exception { Signature signature = Signature.getInstance(signatureAlgorithm); signature.initSign(privateKey); signature.update(plaintext.getBytes()); return new String(Base64.encodeBase64(signature.sign())); }
From source file:org.ejbca.core.protocol.cmp.CmpTestCase.java
protected static PKIMessage genRenewalReq(X500Name userDN, Certificate cacert, byte[] nonce, byte[] transid, KeyPair keys, boolean raVerifiedPopo, X500Name reqSubjectDN, String reqIssuerDN, AlgorithmIdentifier pAlg, DEROctetString senderKID) throws IOException, NoSuchAlgorithmException, InvalidKeyException, SignatureException, CertificateEncodingException { 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); if (reqSubjectDN != null) { myCertTemplate.setSubject(reqSubjectDN); }//from w w w . ja v a 2s . c o m if (reqIssuerDN != null) { myCertTemplate.setIssuer(new X500Name(reqIssuerDN)); } 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(); } 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); 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); } // 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("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 JcaX509CertificateHolder((X509Certificate) cacert).getSubject())); 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(PKIBody.TYPE_KEY_UPDATE_REQ, myCertReqMessages); // Key Update Request PKIMessage myPKIMessage = new PKIMessage(myPKIHeader.build(), myPKIBody); return myPKIMessage; }
From source file:org.springframework.boot.actuate.autoconfigure.cloudfoundry.reactive.ReactiveTokenValidatorTests.java
private String getSignedToken(byte[] header, byte[] claims) throws Exception { PrivateKey privateKey = getPrivateKey(); Signature signature = Signature.getInstance("SHA256WithRSA"); signature.initSign(privateKey); byte[] content = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encode(claims)); signature.update(content);//from w w w. j a v a 2 s . c o m byte[] crypto = signature.sign(); byte[] token = dotConcat(Base64Utils.encodeUrlSafe(header), Base64Utils.encodeUrlSafe(claims), Base64Utils.encodeUrlSafe(crypto)); return new String(token, StandardCharsets.UTF_8); }