Java Code Examples for java.security.Signature#sign()
The following examples show how to use
java.security.Signature#sign() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TestSignatures.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
private static void testSignature(String algorithm, PrivateKey privateKey, PublicKey publicKey) throws Exception { System.out.println("Testing " + algorithm + "..."); Signature s = Signature.getInstance(algorithm, provider); s.initSign(privateKey); s.update(data); byte[] sig = s.sign(); s.initVerify(publicKey); s.update(data); boolean result; result = s.verify(sig); if (result == false) { throw new Exception("Verification 1 failed"); } s.update(data); result = s.verify(sig); if (result == false) { throw new Exception("Verification 2 failed"); } result = s.verify(sig); if (result == true) { throw new Exception("Verification 3 succeeded"); } }
Example 2
Source File: CryptographicUtilities.java From openemm with GNU Affero General Public License v3.0 | 6 votes |
public static byte[] signStream(InputStream dataStream, PrivateKey privateKey, String signatureMethod) throws Exception { Security.addProvider(new BouncyCastleProvider()); try { Signature signature = Signature.getInstance(signatureMethod, "BC"); signature.initSign(privateKey); byte[] buffer = new byte[4096]; int bytesRead = dataStream.read(buffer); while (bytesRead >= 0) { signature.update(buffer, 0, bytesRead); bytesRead = dataStream.read(buffer); } return signature.sign(); } catch (Exception e) { throw new Exception("Cannot create signature", e); } }
Example 3
Source File: BouncyCryptography.java From Jabit with Apache License 2.0 | 6 votes |
@Override public byte[] getSignature(byte[] data, PrivateKey privateKey) { try { ECParameterSpec spec = new ECParameterSpec( EC_CURVE_PARAMETERS.getCurve(), EC_CURVE_PARAMETERS.getG(), EC_CURVE_PARAMETERS.getN(), EC_CURVE_PARAMETERS.getH(), EC_CURVE_PARAMETERS.getSeed() ); BigInteger d = keyToBigInt(privateKey.getPrivateSigningKey()); KeySpec keySpec = new ECPrivateKeySpec(d, spec); java.security.PrivateKey privKey = KeyFactory.getInstance(ALGORITHM_ECDSA, provider) .generatePrivate(keySpec); Signature sig = Signature.getInstance(ALGORITHM_ECDSA, provider); sig.initSign(privKey); sig.update(data); return sig.sign(); } catch (GeneralSecurityException e) { throw new ApplicationException(e); } }
Example 4
Source File: DynamoDbSigner.java From aws-dynamodb-encryption-java with Apache License 2.0 | 5 votes |
byte[] calculateSignature(Map<String, AttributeValue> itemAttributes, Map<String, Set<EncryptionFlags>> attributeFlags, byte[] associatedData, PrivateKey key) throws GeneralSecurityException { byte[] stringToSign = calculateStringToSign(itemAttributes, attributeFlags, associatedData); Signature sig = Signature.getInstance(signingAlgorithm); sig.initSign(key, rnd); sig.update(stringToSign); return sig.sign(); }
Example 5
Source File: RSASigner.java From fusionauth-jwt with Apache License 2.0 | 5 votes |
public byte[] sign(String message) { Objects.requireNonNull(message); try { Signature signature = cryptoProvider.getSignatureInstance(algorithm.getName()); signature.initSign(privateKey); signature.update(message.getBytes(StandardCharsets.UTF_8)); return signature.sign(); } catch (InvalidKeyException | NoSuchAlgorithmException | SignatureException e) { throw new JWTSigningException("An unexpected exception occurred when attempting to sign the JWT", e); } }
Example 6
Source File: JacksonProtocolManager.java From incubator-retired-gossip with Apache License 2.0 | 5 votes |
private static byte[] sign(byte [] bytes, PrivateKey pk){ Signature dsa; try { dsa = Signature.getInstance("SHA1withDSA", "SUN"); dsa.initSign(pk); dsa.update(bytes); return dsa.sign(); } catch (NoSuchAlgorithmException | NoSuchProviderException | InvalidKeyException | SignatureException e) { throw new RuntimeException(e); } }
Example 7
Source File: KeyPair.java From java-stellar-sdk with Apache License 2.0 | 5 votes |
/** * Sign the provided data with the keypair's private key. * @param data The data to sign. * @return signed bytes, null if the private key for this keypair is null. */ public byte[] sign(byte[] data) { if (mPrivateKey == null) { throw new RuntimeException("KeyPair does not contain secret key. Use KeyPair.fromSecretSeed method to create a new KeyPair with a secret key."); } try { Signature sgr = new EdDSAEngine(MessageDigest.getInstance("SHA-512")); sgr.initSign(mPrivateKey); sgr.update(data); return sgr.sign(); } catch (GeneralSecurityException e) { throw new RuntimeException(e); } }
Example 8
Source File: ECDSATest.java From java_security with MIT License | 5 votes |
/** * * @author timliu * 说明: 用java的jdk里面相关方法实现ECDSA的签名及签名验证,要jdk7.x以上,ECDSA:椭圆曲线数字签名算法 */ public static void jdkECDSA() { try { // 1.初始化密钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC"); keyPairGenerator.initialize(256); KeyPair keyPair = keyPairGenerator.generateKeyPair(); ECPublicKey ecPublicKey = (ECPublicKey)keyPair.getPublic(); ECPrivateKey ecPrivateKey = (ECPrivateKey)keyPair.getPrivate(); // 2.进行签名 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(ecPrivateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("EC"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance("SHA1withECDSA"); signature.initSign(privateKey); signature.update(src.getBytes()); byte[] result = signature.sign(); System.out.println("jdk ecdsa sign:" + Hex.encodeHexString(result) ); // 3.验证签名 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(ecPublicKey.getEncoded()); keyFactory = KeyFactory.getInstance("EC"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); signature = Signature.getInstance("SHA1withECDSA"); signature.initVerify(publicKey); signature.update(src.getBytes()); boolean bool = signature.verify(result); System.out.println("jdk ecdsa verify:" + bool); } catch (Exception e) { System.out.println(e.toString()); } }
Example 9
Source File: CryptoServiceImpl.java From paymentgateway with GNU General Public License v3.0 | 5 votes |
protected String sign(PrivateKey key, String plainData) throws MipsException { try { Signature instance = Signature.getInstance("SHA256withRSA"); instance.initSign(key); instance.update(plainData.getBytes("UTF-8")); byte[] signature = instance.sign(); return Base64.encodeBase64String(signature); } catch (Exception e) { throw new MipsException(RespCode.INTERNAL_ERROR, "sign failed: ", e); } }
Example 10
Source File: CryptoServiceImpl.java From paymentgateway with GNU General Public License v3.0 | 5 votes |
protected String sign(PrivateKey key, String plainData) throws MipsException { try { Signature instance = Signature.getInstance("SHA1withRSA"); instance.initSign(key); instance.update(plainData.getBytes("UTF-8")); byte[] signature = instance.sign(); return Base64.encodeBase64String(signature); } catch (Exception e) { throw new MipsException(RespCode.INTERNAL_ERROR, "sign failed: ", e); } }
Example 11
Source File: EcValidationTests.java From azure-keyvault-java with MIT License | 5 votes |
private static void signVerify(PublicKey publicKey, PrivateKey privateKey, JsonWebKeyCurveName curve) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException { Signature signature = Signature.getInstance(CURVE_TO_SIGNATURE.get(curve), Security.getProvider("SunEC")); signature.initSign(privateKey); MessageDigest digest = MessageDigest.getInstance(algorithm.get(curve)); byte[] plaintext = new byte[10]; new Random().nextBytes(plaintext); byte[] hash = digest.digest(plaintext); signature.update(hash); byte[] signed_hash = signature.sign(); signature.initVerify(publicKey); signature.update(hash); Assert.assertTrue(signature.verify(signed_hash)); }
Example 12
Source File: KeyUtils.java From Bitcoin with Apache License 2.0 | 5 votes |
public static final byte[] signMsg(Signature enc, byte[] bytes) { byte[] signed = null; try { enc.update(bytes); signed = enc.sign(); } catch (Exception e) { System.err.println("Could not encode msg. "+e); } return signed; }
Example 13
Source File: RSATest.java From java_security with MIT License | 5 votes |
/** * * @author timliu * 说明: 用java的jdk里面相关方法实现rsa的签名及签名验证 */ public static void jdkRSA() { try { // 1.初始化密钥 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(512); KeyPair keyPair = keyPairGenerator.generateKeyPair(); RSAPublicKey rsaPublicKey = (RSAPublicKey)keyPair.getPublic(); RSAPrivateKey rsaPrivateKey = (RSAPrivateKey)keyPair.getPrivate(); // 2.进行签名 PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(rsaPrivateKey.getEncoded()); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(src.getBytes()); byte[] result = signature.sign(); System.out.println("jdk rsa sign:" + Hex.encodeHexString(result) ); // 3.验证签名 X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKey.getEncoded()); keyFactory = KeyFactory.getInstance("RSA"); PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec); signature = Signature.getInstance("MD5withRSA"); signature.initVerify(publicKey); signature.update(src.getBytes()); boolean bool = signature.verify(result); System.out.println("jdk rsa verify:" + bool); } catch (Exception e) { System.out.println(e.toString()); } }
Example 14
Source File: RSA.java From UAF with Apache License 2.0 | 5 votes |
public static byte[] signPSS(PrivateKey privateKey, byte[] signedData) throws SignatureException, InvalidKeyException, NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException { Signature signature = Signature.getInstance("SHA256withRSA/PSS", BC); signature.setParameter(new PSSParameterSpec("SHA-256", "MGF1", new MGF1ParameterSpec("SHA-256"), 32, 1)); signature.initSign(privateKey); signature.update(signedData); return signature.sign(); }
Example 15
Source File: PolizasPeriodov11.java From factura-electronica with Apache License 2.0 | 5 votes |
String getSignature(PrivateKey key) throws Exception { byte[] bytes = getOriginalBytes(); Signature sig = Signature.getInstance("SHA1withRSA"); sig.initSign(key); sig.update(bytes); byte[] signed = sig.sign(); Base64 b64 = new Base64(-1); return b64.encodeToString(signed); }
Example 16
Source File: Common.java From fido2 with GNU Lesser General Public License v2.1 | 4 votes |
/** * Function to create the U2F Authentication response in the software * authenticator. * * @param chalparam String containing the Base64-encoded hash of the * challenge nonce sent by SKCE (U2F server) from the preregister call * @param appparam String containing the Base64-encoded hash of the facet-id * (application parameter) * @param keyhandle String containing the Base64-encoded encrypted KeyHandle * @param counter * @return String containing the base64-encoded signed authentication * response * @throws java.security.spec.InvalidParameterSpecException */ public static String createAuthenticationSignatureResponse(String chalparam, String appparam, String keyhandle, int counter) throws InvalidParameterSpecException { // Recover challenge parameter byte[] cpbytes = Base64.getUrlDecoder().decode(chalparam); int cplen = cpbytes.length; // Recover application parameter byte[] apbytes = Base64.getUrlDecoder().decode(appparam); int aplen = apbytes.length; // Create a new byte-array to-be-signed. The 1 is for user-presence-byte // while the 4 is for the byte-array of the (authenticator) counter value byte[] tbs = new byte[aplen + 1 + Constants.AUTHENTICATOR_COUNTER_LENGTH + cplen]; // Initialize current position int currpos = 0; // Copy application parameter into TBS System.arraycopy(apbytes, 0, tbs, currpos, aplen); currpos += aplen; // Copy user-presence-byte into TBBS tbs[currpos] = Constants.AUTHENTICATOR_USERPRESENCE_BYTE; currpos += 1; // Copy counter value into TBS - verify if less than Integer.MAX_VALUE if (counter > 2147483647) { System.err.println("Authenticator Counter MAX value reached; wrapping around..."); counter = 1; } byte[] counterbytes = ByteBuffer.allocate(Constants.AUTHENTICATOR_COUNTER_LENGTH).putInt(counter).array(); System.arraycopy(counterbytes, 0, tbs, currpos, Constants.AUTHENTICATOR_COUNTER_LENGTH); currpos += Constants.AUTHENTICATOR_COUNTER_LENGTH; // Copy challenge parameter into TBS; done with curpos here System.arraycopy(cpbytes, 0, tbs, currpos, cplen); // Decrypt KeyHandle @SuppressWarnings("UnusedAssignment") String khjson = null; byte[] signedbytes; try { khjson = decryptKeyHandle(keyhandle); // System.out.println("PlaintextKeyHandle: " + khjson); // Extract user's private-key PrivateKey pvk = getUserPrivateKey(decodeKeyHandle(khjson, 0)); // Sign TBS with private-key Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS"); sig.initSign(pvk, new SecureRandom()); sig.update(tbs); signedbytes = sig.sign(); } catch (DecoderException | NoSuchAlgorithmException | NoSuchProviderException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | ShortBufferException | IllegalBlockSizeException | BadPaddingException | UnsupportedEncodingException | InvalidKeySpecException | SignatureException ex) { System.err.println("Fatal Error: KeyHandle exception: " + ex.getLocalizedMessage()); return null; } // Create Signature Data byte-array and reset current position // The 1 byte in signdata is for the user-presence-byte byte[] signdata = new byte[1 + Constants.AUTHENTICATOR_COUNTER_LENGTH + signedbytes.length]; currpos = 0; // Copy user-presence byte into first position of signdata signdata[currpos] = Constants.AUTHENTICATOR_USERPRESENCE_BYTE; currpos += 1; // Copy counter bytes into signdata System.arraycopy(counterbytes, 0, signdata, currpos, Constants.AUTHENTICATOR_COUNTER_LENGTH); currpos += Constants.AUTHENTICATOR_COUNTER_LENGTH; // Copy signed-bytes into signdata System.arraycopy(signedbytes, 0, signdata, currpos, signedbytes.length); // Return Base64-encoded signature response return org.apache.commons.codec.binary.Base64.encodeBase64URLSafeString(signdata); }
Example 17
Source File: TestKeyOpts.java From julongchain with Apache License 2.0 | 4 votes |
@Test public void test2() { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048); KeyPair key = keyGen.generateKeyPair(); PKCS11KeyData keyraw = new PKCS11KeyData(); keyraw.setRawPri(key.getPrivate().getEncoded()); keyraw.setRawPub(key.getPublic().getEncoded()); IKeyImportOpts opts = new RsaOpts.RSAPrivateKeyImportOpts(false); IKey mykey = csp.keyImport(keyraw, opts); Assert.assertNotNull(mykey); String input2 = "Hello world !TOM"; PKCS11HashOpts.SHA1Opts hashopt_sha1 = new PKCS11HashOpts.SHA1Opts(); byte[] bytehash = csp.hash(input2.getBytes(), hashopt_sha1); Assert.assertNotNull(bytehash); Signature signature = Signature.getInstance("SHA1withRSA"); signature.initSign(key.getPrivate()); signature.update(bytehash); byte[] signvalue1 = signature.sign(); Assert.assertNotNull(signvalue1); byte[] signvalue = csp.sign(mykey, bytehash, RsaSignOpts.SHA1); Assert.assertNotNull(signvalue); boolean bverify = csp.verify(mykey, signvalue, bytehash, RsaSignOpts.SHA1); Assert.assertNotNull(bverify); signature.initVerify(key.getPublic()); signature.update(bytehash); boolean bverify1 = signature.verify(signvalue); Assert.assertTrue(bverify1); } catch (JulongChainException | InvalidKeyException |NoSuchAlgorithmException| SignatureException e) { e.printStackTrace(); } }
Example 18
Source File: ValidationTest.java From snowblossom with Apache License 2.0 | 4 votes |
@Test public void testBasicTx() throws Exception { MessageDigest md_bc = DigestUtil.getMD(); Transaction.Builder tx = Transaction.newBuilder(); TransactionInner.Builder inner = TransactionInner.newBuilder(); inner.setVersion(1); byte[] to_addr = new byte[Globals.ADDRESS_SPEC_HASH_LEN]; rnd.nextBytes(to_addr); KeyPair key_pair = KeyUtil.generateECCompressedKey(); byte[] public_key = key_pair.getPublic().getEncoded(); byte[] src_tx = new byte[Globals.BLOCKCHAIN_HASH_LEN]; rnd.nextBytes(src_tx); AddressSpec claim = AddressSpec.newBuilder() .setRequiredSigners(1) .addSigSpecs( SigSpec.newBuilder() .setSignatureType(SignatureUtil.SIG_TYPE_ECDSA) .setPublicKey(ByteString.copyFrom(public_key)) .build()) .build(); AddressSpecHash addr_spec = AddressUtil.getHashForSpec(claim, DigestUtil.getMDAddressSpec()); inner.addInputs( TransactionInput.newBuilder() .setSpecHash(addr_spec.getBytes()) .setSrcTxId( ByteString.copyFrom(src_tx) ) .setSrcTxOutIdx (1) .build() ); inner.addOutputs( TransactionOutput.newBuilder() .setValue(50000L) .setRecipientSpecHash(ByteString.copyFrom(to_addr)) .build()); inner.addOutputs( TransactionOutput.newBuilder() .setValue(50000L) .setRecipientSpecHash(ByteString.copyFrom(to_addr)) .build()); inner.addClaims(claim); inner.setFee(50L); inner.setExtra(ByteString.copyFrom(new String("hellllo").getBytes())); ByteString inner_data= inner.build().toByteString(); tx.setInnerData(inner_data); tx.setTxHash(ByteString.copyFrom(md_bc.digest(inner_data.toByteArray()))); Signature sig_engine = Signature.getInstance("ECDSA"); sig_engine.initSign(key_pair.getPrivate()); sig_engine.update(tx.getTxHash().toByteArray()); byte[] sig = sig_engine.sign(); tx.addSignatures( SignatureEntry.newBuilder() .setClaimIdx(0) .setKeyIdx(0) .setSignature( ByteString.copyFrom(sig) ) .build()); Validation.checkTransactionBasics(tx.build(), false); crossCheckTxOut(tx.build()); System.out.println("Basic transaction size: " + tx.build().toByteString().size()); }
Example 19
Source File: ThroughputLatencyClient.java From library with Apache License 2.0 | 4 votes |
public Client(int id, int numberOfOps, int requestSize, int interval, boolean readOnly, boolean verbose, int sign) { super("Client "+id); this.id = id; this.numberOfOps = numberOfOps; this.requestSize = requestSize; this.interval = interval; this.readOnly = readOnly; this.verbose = verbose; this.proxy = new ServiceProxy(id); this.request = new byte[this.requestSize]; Random rand = new Random(System.nanoTime() + this.id); rand.nextBytes(request); byte[] signature = new byte[0]; Signature eng; try { if (sign > 0) { if (sign == 1) { eng = TOMUtil.getSigEngine(); eng.initSign(proxy.getViewManager().getStaticConf().getPrivateKey()); } else { eng = Signature.getInstance("SHA256withECDSA", "BC"); //KeyFactory kf = KeyFactory.getInstance("EC", "BC"); //Base64.Decoder b64 = Base64.getDecoder(); //PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(b64.decode(ThroughputLatencyClient.privKey)); //eng.initSign(kf.generatePrivate(spec)); KeyFactory keyFactory = KeyFactory.getInstance("EC"); EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(privKey)); PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec); eng.initSign(privateKey); } eng.update(request); signature = eng.sign(); } ByteBuffer buffer = ByteBuffer.allocate(request.length + signature.length + (Integer.BYTES * 2)); buffer.putInt(request.length); buffer.put(request); buffer.putInt(signature.length); buffer.put(signature); this.request = buffer.array(); } catch (NoSuchAlgorithmException | SignatureException | NoSuchProviderException | InvalidKeyException | InvalidKeySpecException ex) { ex.printStackTrace(); System.exit(0); } }
Example 20
Source File: GetPrivateKey.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
public static void main(String[] args) throws Exception { if (initSecmod() == false) { return; } String configName = BASE + SEP + "nss.cfg"; Provider p = getSunPKCS11(configName); System.out.println(p); Security.addProvider(p); if (args.length > 1 && "sm".equals(args[0])) { System.setProperty("java.security.policy", BASE + File.separator + args[1]); System.setSecurityManager(new SecurityManager()); } KeyStore ks = KeyStore.getInstance(PKCS11, p); ks.load(null, password); Collection<String> aliases = new TreeSet<>( Collections.list(ks.aliases())); System.out.println("entries: " + aliases.size()); System.out.println(aliases); PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password); System.out.println(privateKey); byte[] data = generateData(1024); System.out.println("Signing..."); Signature signature = Signature.getInstance("MD5withRSA"); signature.initSign(privateKey); signature.update(data); byte[] sig = signature.sign(); X509Certificate[] chain = (X509Certificate[]) ks.getCertificateChain(keyAlias); signature.initVerify(chain[0].getPublicKey()); signature.update(data); boolean ok = signature.verify(sig); if (ok == false) { throw new Exception("Signature verification error"); } System.out.println("OK"); }