List of usage examples for java.security Signature getInstance
public static Signature getInstance(String algorithm) throws NoSuchAlgorithmException
From source file:test.be.fedict.eid.applet.PKCS11Test.java
@Test public void testPKCS1viaPKCS11() throws Exception { File tmpConfigFile = File.createTempFile("pkcs11-", "conf"); tmpConfigFile.deleteOnExit();// w w w . j a v a 2s.c om PrintWriter configWriter = new PrintWriter(new FileOutputStream(tmpConfigFile), true); configWriter.println("name=SmartCard"); configWriter.println("library=/usr/lib/libbeidpkcs11.so.0"); configWriter.println("slotListIndex=2"); SunPKCS11 provider = new SunPKCS11(tmpConfigFile.getAbsolutePath()); Security.addProvider(provider); KeyStore keyStore = KeyStore.getInstance("PKCS11", provider); keyStore.load(null, null); PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry("Authentication", null); PrivateKey privateKey = privateKeyEntry.getPrivateKey(); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(privateKey); byte[] toBeSigned = "hello world".getBytes(); signature.update(toBeSigned); byte[] signatureValue = signature.sign(); X509Certificate certificate = (X509Certificate) privateKeyEntry.getCertificate(); RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey(); BigInteger signatureValueBigInteger = new BigInteger(signatureValue); BigInteger messageBigInteger = signatureValueBigInteger.modPow(publicKey.getPublicExponent(), publicKey.getModulus()); LOG.debug("original message: " + new String(Hex.encodeHex(messageBigInteger.toByteArray()))); // LOG.debug("ASN.1 signature: " + ASN1Dump.dumpAsString(obj) }
From source file:org.codice.ddf.commands.util.DigitalSignature.java
public byte[] createDigitalSignature(InputStream data, String alias, String password) throws IOException { PrivateKey privateKey = getPrivateKey(alias, password); if (privateKey == null) { throw new CatalogCommandRuntimeException("Unable to retrieve private key"); }//from w ww . j a va 2 s. c o m try { Signature rsa = Signature.getInstance("SHA256withRSA"); rsa.initSign(privateKey); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = data.read(buffer)) >= 0) { rsa.update(buffer, OFFSET, len); } return rsa.sign(); } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { String message = "An error occurred while signing file"; LOGGER.debug(message, e); throw new CatalogCommandRuntimeException(message, e); } }
From source file:com.yazino.web.payment.googlecheckout.AndroidInAppOrderSecurity.java
/** * Verifies that the signature from google play matches the computed signature on {@code orderData}. * Returns true if the data is correctly signed. * * @param gameType gameType purchases were made from, required to enable retrieval of correct public key * @param orderData signed order data from Google Play to verify * @param signature signature of {@code orderData} from Google Play * @param partnerId// w w w .j a v a2 s. co m * @return true if the data and signature match */ public boolean verify(String gameType, String orderData, String signature, final Partner partnerId) { LOG.debug("verifying gametype:{}, orderData:{}, signature:{}, partner:{}"); validateArgs(gameType, orderData, signature); LOG.debug("verifying orderData {} for gameType {} against signature {}", orderData, gameType, signature); PublicKey publicKey = generatePublicKey(gameType, partnerId); Signature sig; try { sig = Signature.getInstance(SIGNATURE_ALGORITHM); sig.initVerify(publicKey); sig.update(orderData.getBytes()); if (!sig.verify(Base64.decode(signature.getBytes()))) { return false; } return true; } catch (Exception e) { LOG.error("Signature is invalid. orderData {}, gameType {}, signature {}, partnerId {}", orderData, gameType, signature, partnerId, e); } return false; }
From source file:com.thoughtworks.go.server.util.EncryptionHelper.java
public static boolean verifyRSASignature(String subordinatePublicKeyContent, String signatureContent, String masterPublicKeyContent) throws NoSuchProviderException, NoSuchAlgorithmException, IOException, InvalidKeySpecException, InvalidKeyException, SignatureException { PublicKey masterPublicKey = getRSAPublicKeyFrom(masterPublicKeyContent); signatureContent = signatureContent.replace("\n", ""); Signature signature = Signature.getInstance("SHA512withRSA"); signature.initVerify(masterPublicKey); signature.update(subordinatePublicKeyContent.getBytes()); return signature.verify(Base64.getDecoder().decode(signatureContent.getBytes())); }
From source file:org.carewebframework.api.security.CipherUtil.java
/** * Verifies a digitally signed payload.//w w w . j a v a 2 s. co m * * @param key Public key to verify digital signature. * @param base64Signature Digital signature of content. * @param content The content that was signed. * @param timestamp Optional timestamp for time-sensitive payloads. * @param duration Optional validity duration in minutes for time-sensitive payloads. * @return True if signature is valid. * @throws Exception Unspecified exception. */ public static boolean verify(PublicKey key, String base64Signature, String content, String timestamp, int duration) throws Exception { if (key == null || base64Signature == null || content == null || timestamp == null) { return false; } try { if (timestamp != null && duration > 0) { validateTime(timestamp, duration); } Signature signature = Signature.getInstance(SIGN_ALGORITHM); signature.initVerify(key); signature.update(content.getBytes()); byte[] signatureBytes = Base64.decodeBase64(base64Signature); return signature.verify(signatureBytes); } catch (Exception e) { log.error("Authentication Exception:verifySignature", e); throw e; } }
From source file:com.linkage.crm.csb.sign.CtSignature.java
/** * @param originalText String /* w w w . ja v a 2 s.c om*/ * @param pwd String * @param alias String * @param priKeyFile * @return String */ public static String signature(String originalText, String pwd, String alias, String priKeyFile) { try { KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream ksfis = new FileInputStream(priKeyFile); BufferedInputStream ksbufin = new BufferedInputStream(ksfis); char[] kpass = pwd.toCharArray(); ks.load(ksbufin, kpass); PrivateKey priKey = (PrivateKey) ks.getKey(alias, kpass); Signature rsa = Signature.getInstance("SHA1withDSA"); rsa.initSign(priKey); rsa.update(originalText.getBytes()); byte[] signedText = rsa.sign(); return HexUtils.toHexString(signedText); } catch (Exception ex) { logger.error("errors appeared while trying to signature", ex); return null; } }
From source file:fi.vm.kapa.identification.shibboleth.extauthn.util.CertificateUtil.java
public static boolean checkSignature(String data, String signature, X509Certificate cert) { boolean result = false; try {//from w ww. j av a 2s . com logger.debug("checkSignature: data={}, signature={}, cert={}", data, signature, cert.toString()); byte[] sigToVerify = Base64.getDecoder().decode(signature); Signature sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(cert); sig.update(Base64.getDecoder().decode(data)); result = sig.verify(sigToVerify); } catch (Exception e) { logger.warn("checkSignature: Got exception " + e.getClass(), e); } return result; }
From source file:architecture.common.license.LicenseSigner.java
protected void init(Reader keyReader) throws IOException, NoSuchAlgorithmException, DecoderException, InvalidKeySpecException, InvalidKeyException { BufferedReader in = new BufferedReader(keyReader); String privateKey = in.readLine(); in.close();//from www. j a v a2s . co m KeyFactory keyFactory = KeyFactory.getInstance("DSA"); sig = Signature.getInstance("SHA1withDSA"); PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(Hex.decodeHex(privateKey.toCharArray())); java.security.PrivateKey privKey = keyFactory.generatePrivate(privKeySpec); sig.initSign(privKey); }
From source file:org.dasein.cloud.google.GenerateToken.java
public static String getToken(String iss, String p12File) { String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}"; String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": \"{3}\", \"iat\": \"{4}\"'}'"; try {//from ww w . ja va 2 s.co m StringBuffer token = new StringBuffer(); //Encode the JWT Header and add it to our string to sign token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8"))); //Separate with a period token.append("."); //Create the JWT Claims Object String[] claimArray = new String[5]; claimArray[0] = iss; claimArray[1] = "https://www.googleapis.com/auth/compute"; claimArray[2] = "https://accounts.google.com/o/oauth2/token"; claimArray[3] = Long.toString((System.currentTimeMillis() / 1000) + 300); claimArray[4] = Long.toString((System.currentTimeMillis() / 1000)); MessageFormat claims; claims = new MessageFormat(claimTemplate); String payload = claims.format(claimArray); // System.out.println(claimArray[3]); // System.out.println(claimArray[4]); //Add the encoded claims object token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8"))); char[] password = "notasecret".toCharArray(); FileInputStream fin = new FileInputStream(new File(p12File)); KeyStore store = KeyStore.getInstance("PKCS12"); try { store.load(fin, password); } finally { try { fin.close(); } catch (IOException e) { } } String alias = ""; // KeyStore keystore = getKeyStore(password); Enumeration<String> enum1 = store.aliases(); // List the aliases while (enum1.hasMoreElements()) { String keyStoreAlias = enum1.nextElement().toString(); if (store.isKeyEntry(keyStoreAlias)) { //Does alias refer to a private key? alias = keyStoreAlias; break; } } PrivateKey privateKey = (PrivateKey) store.getKey(alias, password); //Sign the JWT Header + "." + JWT Claims Object Signature signature = Signature.getInstance("SHA256withRSA"); signature.initSign(privateKey); signature.update(token.toString().getBytes("UTF-8")); String signedPayload = Base64.encodeBase64URLSafeString(signature.sign()); //Separate with a period token.append("."); //Add the encoded signature token.append(signedPayload); // System.out.println(token.toString()); return token.toString(); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:net.sf.zekr.common.util.CryptoUtils.java
public static byte[] sign(byte[] text, byte[] prvKeyBytes) throws GeneralSecurityException { PKCS8EncodedKeySpec prvSpec = new PKCS8EncodedKeySpec(prvKeyBytes); KeyFactory keyFactory = KeyFactory.getInstance("DSA"); PrivateKey prvKey = keyFactory.generatePrivate(prvSpec); Signature sig = Signature.getInstance("SHA1withDSA"); sig.initSign(prvKey);/*from www . j a va 2 s . co m*/ sig.update(text); return sig.sign(); }