Java Code Examples for java.security.Signature#initSign()

The following examples show how to use java.security.Signature#initSign() . 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: ECKey.java    From wkcwallet-java with Apache License 2.0 6 votes vote down vote up
/**
 * Signs the given hash and returns the R and S components as BigIntegers
 * and put them in ECDSASignature
 *
 * @param input
 *            to sign
 * @return ECDSASignature signature that contains the R and S components
 */
public ECDSASignature doSign(byte[] input) {
    if (input.length != 32) {
        throw new IllegalArgumentException("Expected 32 byte input to ECDSA signature, not " + input.length);
    }
    // No decryption of private key required.
    if (privKey == null)
        throw new MissingPrivateKeyException();
    if (privKey instanceof BCECPrivateKey) {
        ECDSASigner signer = new ECDSASigner(new HMacDSAKCalculator(new SHA256Digest()));
        ECPrivateKeyParameters privKeyParams = new ECPrivateKeyParameters(((BCECPrivateKey) privKey).getD(), CURVE);
        signer.init(true, privKeyParams);
        BigInteger[] components = signer.generateSignature(input);
        return new ECDSASignature(components[0], components[1]).toCanonicalised();
    } else {
        try {
            final Signature ecSig = ECSignatureFactory.getRawInstance(provider);
            ecSig.initSign(privKey);
            ecSig.update(input);
            final byte[] derSignature = ecSig.sign();
            return ECDSASignature.decodeFromDER(derSignature).toCanonicalised();
        } catch (SignatureException | InvalidKeyException ex) {
            throw new RuntimeException("ECKey signing error", ex);
        }
    }
}
 
Example 2
Source File: CredentialProxy.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public byte[] sign(byte[] digestValue, String digestAlgo, String alias) throws SignatureException {
   try {
      Signature signature = Signature.getInstance("NONEwithRSA");
      signature.initSign(this.credential.getPrivateKey());
      ByteArrayOutputStream digestInfo = new ByteArrayOutputStream();
      if (!digestInfoPrefixes.containsKey(digestAlgo)) {
         throw new NoSuchAlgorithmException(digestAlgo);
      } else {
         byte[] digestInfoPrefix = (byte[])digestInfoPrefixes.get(digestAlgo);
         digestInfo.write(digestInfoPrefix);
         digestInfo.write(digestValue);
         signature.update(digestInfo.toByteArray());
         return signature.sign();
      }
   } catch (Exception var7) {
      throw new SignatureException(var7);
   }
}
 
Example 3
Source File: TestSignatureOidHelper.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private void runTest(OidAlgorithmPair oidAlgorithmPair, KeyPair keyPair)
        throws NoSuchAlgorithmException, NoSuchProviderException,
        InvalidKeyException, SignatureException {
    Signature sgAlgorithm =
            Signature.getInstance(oidAlgorithmPair.algorithm, provider);
    Signature sgOid = Signature.getInstance(oidAlgorithmPair.oid, provider);

    if (sgAlgorithm == null) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance failed.%n",
                oidAlgorithmPair.algorithm));
    }

    if (sgOid == null) {
        throw new RuntimeException(
                String.format("Test failed: OID %s getInstance failed.%n",
                        oidAlgorithmPair.oid));
    }

    if (!sgAlgorithm.getAlgorithm().equals(oidAlgorithmPair.algorithm)) {
        throw new RuntimeException(String.format(
                "Test failed: algorithm string %s getInstance "
                        + "doesn't generate expected algorithm.%n",
                oidAlgorithmPair.algorithm));
    }

    sgAlgorithm.initSign(keyPair.getPrivate());
    sgAlgorithm.update(INPUT);
    sgOid.initVerify(keyPair.getPublic());
    sgOid.update(INPUT);
    if (!sgOid.verify(sgAlgorithm.sign())) {
        throw new RuntimeException(
                "Signature verification failed unexpectedly");
    }
}
 
Example 4
Source File: RSAUtil.java    From anyline with Apache License 2.0 5 votes vote down vote up
/** 
 * 用私钥对信息生成数字签名 
 * @param data 已加密数据 
 * @param privateKey 私钥(BASE64编码) 
 *  
 * @return return
 * @throws Exception Exception
 */ 
public static String sign(byte[] data, String privateKey) throws Exception { 
    PrivateKey privateK = getPrivateKey(privateKey); 
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM); 
    signature.initSign(privateK); 
    signature.update(data); 
    return Base64Util.encode(signature.sign()); 
     
		 
}
 
Example 5
Source File: RevocationAuthority.java    From fabric-sdk-java with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a Credential Revocation Information object
 *
 * @param key              Private key
 * @param unrevokedHandles Array of unrevoked revocation handles
 * @param epoch            The counter (representing a time window) in which this CRI is valid
 * @param alg              Revocation algorithm
 * @return CredentialRevocationInformation object
 */
public static Idemix.CredentialRevocationInformation createCRI(PrivateKey key, BIG[] unrevokedHandles, int epoch, RevocationAlgorithm alg) throws CryptoException {
    Idemix.CredentialRevocationInformation.Builder builder = Idemix.CredentialRevocationInformation.newBuilder();
    builder.setRevocationAlg(alg.ordinal());
    builder.setEpoch(epoch);

    // Create epoch key
    WeakBB.KeyPair keyPair = WeakBB.weakBBKeyGen();
    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // Dummy PK in the proto
        builder.setEpochPk(IdemixUtils.transformToProto(IdemixUtils.genG2));
    } else {
        // Real PK only if we are going to use it
        builder.setEpochPk(IdemixUtils.transformToProto(keyPair.getPk()));
    }

    // Sign epoch + epoch key with the long term key
    byte[] signed;
    try {
        Idemix.CredentialRevocationInformation cri = builder.build();
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initSign(key);
        ecdsa.update(cri.toByteArray());
        signed = ecdsa.sign();

        builder.setEpochPkSig(ByteString.copyFrom(signed));
    } catch (NoSuchAlgorithmException | SignatureException | InvalidKeyException e) {
        throw new CryptoException("Error processing the signature");
    }

    if (alg == RevocationAlgorithm.ALG_NO_REVOCATION) {
        // build and return the credential information object
        return builder.build();
    } else {
        // If alg not supported, return null
        throw new IllegalArgumentException("Algorithm " + alg.name() + " not supported");
    }
}
 
Example 6
Source File: FingerprintActivity.java    From AndroidSamples with Apache License 2.0 5 votes vote down vote up
@Nullable
private Signature initSignature(String keyName) throws Exception {
    KeyPair keyPair = getKeyPair(keyName);

    if (keyPair != null) {
        Signature signature = Signature.getInstance("SHA256withECDSA");
        signature.initSign(keyPair.getPrivate());
        return signature;
    }
    return null;
}
 
Example 7
Source File: SM2Pkcs12MakerTest.java    From gmhelper with Apache License 2.0 5 votes vote down vote up
@Test
public void testPkcs12Sign() {
    //先生成一个pkcs12
    testMakePkcs12();

    try {
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        try (InputStream is = Files.newInputStream(Paths.get(TEST_P12_FILENAME),
                                  StandardOpenOption.READ)) {
            ks.load(is, TEST_P12_PASSWD);
        }

        PrivateKey privateKey = (BCECPrivateKey) ks.getKey("User Key", TEST_P12_PASSWD);
        X509Certificate cert = (X509Certificate) ks.getCertificate("User Key");

        byte[] srcData = "1234567890123456789012345678901234567890".getBytes();

        // create signature
        Signature sign = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        sign.initSign(privateKey);
        sign.update(srcData);
        byte[] signatureValue = sign.sign();

        // verify signature
        Signature verify = Signature.getInstance(SM2X509CertMaker.SIGN_ALGO_SM3WITHSM2, "BC");
        verify.initVerify(cert);
        verify.update(srcData);
        boolean sigValid = verify.verify(signatureValue);
        Assert.assertTrue("signature validation result", sigValid);
    } catch (Exception ex) {
        ex.printStackTrace();
        Assert.fail();
    }
}
 
Example 8
Source File: CryptoServiceImpl.java    From paymentgateway with GNU General Public License v3.0 5 votes vote down vote up
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 9
Source File: TestOzoneTokenIdentifier.java    From hadoop-ozone with Apache License 2.0 5 votes vote down vote up
public byte[] signTokenAsymmetric(OzoneTokenIdentifier tokenId,
    PrivateKey privateKey) throws NoSuchAlgorithmException,
    InvalidKeyException, SignatureException {
  Signature rsaSignature = Signature.getInstance("SHA256withRSA");
  rsaSignature.initSign(privateKey);
  rsaSignature.update(tokenId.getBytes());
  byte[] signature = rsaSignature.sign();
  return signature;
}
 
Example 10
Source File: PolizasPeriodov11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
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 11
Source File: RSAProvider.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static byte[] sign(byte[] data, Algorithm algorithm, PrivateKey privateKey) {
    try {
        Signature signature = getSignature(algorithm);
        signature.initSign(privateKey);
        signature.update(data);
        return signature.sign();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: CuentasContablesv11.java    From factura-electronica with Apache License 2.0 5 votes vote down vote up
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 13
Source File: RSAUtils.java    From rhizobia_J with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * @Description: 签名
 * @Param: oriData 待签名数据
 * @return: byte[] 数字签名
 */
public byte[] sign(String oriData) throws Exception {
    byte[] data = oriData.getBytes();
    // 实例化Signature
    Signature signature = Signature.getInstance(signatureAlgorithm);
    // 初始化Signature
    signature.initSign(privateKey);
    // 更新
    signature.update(data);
    // 签名
    byte[] encrypted= signature.sign();

    return encrypted;
}
 
Example 14
Source File: PackedAttestationStatement.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public byte[] signwithCredentialKey(PrivateKey pvtKey, byte[] tbs) {
    try {
        Signature sig = Signature.getInstance("SHA256withECDSA", "BCFIPS");
        sig.initSign(pvtKey, new SecureRandom());
        sig.update(tbs);
        signature = sig.sign();
        return signature;
    } catch (InvalidKeyException | NoSuchAlgorithmException |
            NoSuchProviderException | SignatureException ex)
    {
        Logger.getLogger(PackedAttestationStatement.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}
 
Example 15
Source File: ECSigner.java    From fusionauth-jwt with Apache License 2.0 5 votes vote down vote up
@Override
public byte[] sign(String message) {
  Objects.requireNonNull(message);

  try {
    Signature signature = cryptoProvider.getSignatureInstance(algorithm.getName());
    signature.initSign(privateKey, new SecureRandom());
    signature.update((message).getBytes(StandardCharsets.UTF_8));
    byte[] derEncoded = signature.sign();

    return new ECDSASignature(derEncoded).derDecode(algorithm);
  } catch (InvalidKeyException | IOException | NoSuchAlgorithmException | SignatureException e) {
    throw new JWTSigningException("An unexpected exception occurred when attempting to sign the JWT", e);
  }
}
 
Example 16
Source File: RsaSigner.java    From jjwt with Apache License 2.0 5 votes vote down vote up
protected byte[] doSign(byte[] data) throws InvalidKeyException, java.security.SignatureException {
    PrivateKey privateKey = (PrivateKey)key;
    Signature sig = createSignatureInstance();
    sig.initSign(privateKey);
    sig.update(data);
    return sig.sign();
}
 
Example 17
Source File: SolarisShortDSA.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
static boolean use(KeyPair kp) throws Exception {
     Signature sig = Signature.getInstance("SHA1withDSA");
     sig.initSign(kp.getPrivate());
     sig.update(data);
     byte[] signed = sig.sign();
     Signature sig2 = Signature.getInstance("SHA1withDSA");
     sig2.initVerify(kp.getPublic());
     sig2.update(data);
     return sig2.verify(signed);
}
 
Example 18
Source File: Main.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Generate a certificate: Read PKCS10 request from in, and print
 * certificate to out. Use alias as CA, sigAlgName as the signature
 * type.
 */
private void doGenCert(String alias, String sigAlgName, InputStream in, PrintStream out)
        throws Exception {


    Certificate signerCert = keyStore.getCertificate(alias);
    byte[] encoded = signerCert.getEncoded();
    X509CertImpl signerCertImpl = new X509CertImpl(encoded);
    X509CertInfo signerCertInfo = (X509CertInfo)signerCertImpl.get(
            X509CertImpl.NAME + "." + X509CertImpl.INFO);
    X500Name issuer = (X500Name)signerCertInfo.get(X509CertInfo.SUBJECT + "." +
                                       X509CertInfo.DN_NAME);

    Date firstDate = getStartDate(startDate);
    Date lastDate = new Date();
    lastDate.setTime(firstDate.getTime() + validity*1000L*24L*60L*60L);
    CertificateValidity interval = new CertificateValidity(firstDate,
                                                           lastDate);

    PrivateKey privateKey =
            (PrivateKey)recoverKey(alias, storePass, keyPass).fst;
    if (sigAlgName == null) {
        sigAlgName = getCompatibleSigAlgName(privateKey.getAlgorithm());
    }
    Signature signature = Signature.getInstance(sigAlgName);
    signature.initSign(privateKey);

    X509CertInfo info = new X509CertInfo();
    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(
                new java.util.Random().nextInt() & 0x7fffffff));
    info.set(X509CertInfo.VERSION,
                new CertificateVersion(CertificateVersion.V3));
    info.set(X509CertInfo.ALGORITHM_ID,
                new CertificateAlgorithmId(
                    AlgorithmId.get(sigAlgName)));
    info.set(X509CertInfo.ISSUER, issuer);

    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    boolean canRead = false;
    StringBuffer sb = new StringBuffer();
    while (true) {
        String s = reader.readLine();
        if (s == null) break;
        // OpenSSL does not use NEW
        //if (s.startsWith("-----BEGIN NEW CERTIFICATE REQUEST-----")) {
        if (s.startsWith("-----BEGIN") && s.indexOf("REQUEST") >= 0) {
            canRead = true;
        //} else if (s.startsWith("-----END NEW CERTIFICATE REQUEST-----")) {
        } else if (s.startsWith("-----END") && s.indexOf("REQUEST") >= 0) {
            break;
        } else if (canRead) {
            sb.append(s);
        }
    }
    byte[] rawReq = Base64.getMimeDecoder().decode(new String(sb));
    PKCS10 req = new PKCS10(rawReq);

    info.set(X509CertInfo.KEY, new CertificateX509Key(req.getSubjectPublicKeyInfo()));
    info.set(X509CertInfo.SUBJECT,
                dname==null?req.getSubjectName():new X500Name(dname));
    CertificateExtensions reqex = null;
    Iterator<PKCS10Attribute> attrs = req.getAttributes().getAttributes().iterator();
    while (attrs.hasNext()) {
        PKCS10Attribute attr = attrs.next();
        if (attr.getAttributeId().equals((Object)PKCS9Attribute.EXTENSION_REQUEST_OID)) {
            reqex = (CertificateExtensions)attr.getAttributeValue();
        }
    }
    CertificateExtensions ext = createV3Extensions(
            reqex,
            null,
            v3ext,
            req.getSubjectPublicKeyInfo(),
            signerCert.getPublicKey());
    info.set(X509CertInfo.EXTENSIONS, ext);
    X509CertImpl cert = new X509CertImpl(info);
    cert.sign(privateKey, sigAlgName);
    dumpCert(cert, out);
    for (Certificate ca: keyStore.getCertificateChain(alias)) {
        if (ca instanceof X509Certificate) {
            X509Certificate xca = (X509Certificate)ca;
            if (!isSelfSigned(xca)) {
                dumpCert(xca, out);
            }
        }
    }
}
 
Example 19
Source File: EncodeDecodeTest.java    From Bitcoin with Apache License 2.0 4 votes vote down vote up
@Test
public void test2() {
    byte[] data = "hello.".getBytes();

    /* Test generating and verifying a DSA signature */
    try {
        /* generate a key pair */
        final KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024, new SecureRandom());
        final KeyPair pair = keyGen.generateKeyPair();

        /* create a Signature object to use
         * for signing and verifying */
        final Signature dsa = Signature.getInstance("SHA/DSA"); 

        /* initialize the Signature object for signing */
        final PrivateKey priv = pair.getPrivate();
        dsa.initSign(priv);

        /* Update and sign the data */
        dsa.update(data);

        /* Now that all the data to be signed has been read in, sign it */
        final byte[] sig = dsa.sign();

        /* Verify the signature */

        /* Initialize the Signature object for verification */
        final PublicKey pub = pair.getPublic();
        /* Encode the public key into a byte array */
        final byte[] encoded = pub.getEncoded();
        /* Get the public key from the encoded byte array */
        final PublicKey fromEncoded = KeyFactory.getInstance("DSA", "SUN").generatePublic(new X509EncodedKeySpec(encoded));
        dsa.initVerify(fromEncoded);

        /* Update and verify the data */
        dsa.update(data);

        final boolean verified = dsa.verify(sig);
        Assert.assertTrue(verified);
    } catch (Exception e) {
        System.err.println("Caught exception " + e.toString());
    }
}
 
Example 20
Source File: RsaMessage.java    From MaxKey with Apache License 2.0 3 votes vote down vote up
/**
* ��˽Կǩ��
*
* @param message
* @param key
* @return
* @throws Exception
*/
public byte[] sign(String message, PrivateKey key) throws Exception {
Signature signetcheck = Signature.getInstance("MD5withRSA");
signetcheck.initSign(key);
signetcheck.update(message.getBytes("ISO-8859-1"));
return signetcheck.sign();
}