List of usage examples for org.bouncycastle.crypto.params RSAKeyParameters RSAKeyParameters
public RSAKeyParameters(boolean isPrivate, BigInteger modulus, BigInteger exponent)
From source file:VerifyDescriptors.java
License:Open Source License
private static boolean verifySignature(String digest, String signature, String signingKey) throws Exception { byte[] signatureBytes = Base64.decodeBase64(signature.substring(0 + "-----BEGIN SIGNATURE-----\n".length(), signature.length() - "-----END SIGNATURE-----\n".length()).replaceAll("\n", "")); RSAPublicKey rsaSigningKey = (RSAPublicKey) new PEMReader(new StringReader(signingKey)).readObject(); RSAKeyParameters rsakp = new RSAKeyParameters(false, rsaSigningKey.getModulus(), rsaSigningKey.getPublicExponent()); PKCS1Encoding pe = new PKCS1Encoding(new RSAEngine()); pe.init(false, rsakp);/*w w w . j a v a2 s. co m*/ byte[] decryptedSignatureDigest = pe.processBlock(signatureBytes, 0, signatureBytes.length); String decryptedSignatureDigestString = Hex.encodeHexString(decryptedSignatureDigest); return decryptedSignatureDigestString.equalsIgnoreCase(digest); }
From source file:bluecrystal.service.service.SignVerifyService.java
License:Open Source License
public boolean verify(int hashId, byte[] contentHash, byte[] sigBytes, X509Certificate cert) throws Exception { RSAPublicKey pubK = (RSAPublicKey) cert.getPublicKey(); CipherParameters param = new RSAKeyParameters(false, pubK.getModulus(), pubK.getPublicExponent()); RSABlindedEngine cipher2 = new RSABlindedEngine(); cipher2.init(false, param);//from w w w . j av a 2 s. c o m AsymmetricBlockCipher cipher = new PKCS1Encoding(cipher2); byte[] sig = cipher.processBlock(sigBytes, 0, sigBytes.length); AlgorithmIdentifier algId = createAlgorithm(hashId); byte[] expected = derEncode(contentHash, algId); LOG.debug("Sig:(" + sigBytes.length + ")" + Utils.conv(sigBytes)); LOG.debug("Has:(" + contentHash.length + ")" + Utils.conv(contentHash)); LOG.debug("Sig:(" + sig.length + ")" + Utils.conv(sig)); LOG.debug("Exp:(" + expected.length + ")" + Utils.conv(expected)); if (sig.length == expected.length) { for (int i = 0; i < sig.length; i++) { if (sig[i] != expected[i]) { return false; } } } else if (sig.length == expected.length - 2) // NULL left out { int sigOffset = sig.length - contentHash.length - 2; int expectedOffset = expected.length - contentHash.length - 2; expected[1] -= 2; // adjust lengths expected[3] -= 2; for (int i = 0; i < contentHash.length; i++) { if (sig[sigOffset + i] != expected[expectedOffset + i]) // check hash { return false; } } for (int i = 0; i < sigOffset; i++) { if (sig[i] != expected[i]) // check header less NULL { return false; } } } else { return false; } return true; }
From source file:cf.monteux.silvertunnel.netlib.layer.tor.util.Encryption.java
License:Open Source License
/** * decrypt data with asymmetric key. create asymmetrically encrypted data:<br> * <ul>//from w w w .j av a 2 s . c o m * <li>OAEP padding [42 bytes] (RSA-encrypted)</li> * <li>Symmetric key [16 bytes]</li> * <li>First part of data [70 bytes]</li> * <li>Second part of data [x-70 bytes] (Symmetrically encrypted)</li> * </ul> * encrypt and store in result * * @param priv key to use for decryption * @param data to be decrypted, needs currently to be at least 70 bytes long * @return raw data */ public static byte[] asymDecrypt(final RSAPrivateKey priv, final byte[] data) throws TorException { if (data == null) { throw new NullPointerException("can't encrypt NULL data"); } if (data.length < 70) { throw new TorException("input array too short"); } try { int encryptedBytes = 0; // init OAEP final OAEPEncoding oaep = new OAEPEncoding(new RSAEngine()); oaep.init(false, new RSAKeyParameters(true, priv.getModulus(), priv.getPrivateExponent())); // apply RSA+OAEP encryptedBytes = oaep.getInputBlockSize(); final byte[] oaepInput = new byte[encryptedBytes]; System.arraycopy(data, 0, oaepInput, 0, encryptedBytes); final byte[] part1 = oaep.decodeBlock(oaepInput, 0, encryptedBytes); // extract symmetric key final byte[] symmetricKey = new byte[16]; System.arraycopy(part1, 0, symmetricKey, 0, 16); // init AES final AESCounterMode aes = new AESCounterMode(symmetricKey); // apply AES final byte[] aesInput = new byte[data.length - encryptedBytes]; System.arraycopy(data, encryptedBytes, aesInput, 0, aesInput.length); final byte[] part2 = aes.processStream(aesInput); // replace unencrypted data final byte[] result = new byte[part1.length - 16 + part2.length]; System.arraycopy(part1, 16, result, 0, part1.length - 16); System.arraycopy(part2, 0, result, part1.length - 16, part2.length); return result; } catch (final InvalidCipherTextException e) { logger.error("Encryption.asymDecrypt(): can't decrypt cipher text:" + e.getMessage()); throw new TorException("Encryption.asymDecrypt(): InvalidCipherTextException:" + e.getMessage()); } }
From source file:ch.ge.ve.offlineadmin.services.KeyGenerator.java
License:Open Source License
private ContentSigner createSigner(KeyPair keyPair) throws PropertyConfigurationException, OperatorCreationException { ContentSigner signer;/* w ww . j a v a2 s . c om*/ String hashAlgo = propertyConfigurationService.getConfigValue(CERT_HASH_ALGORITHM); if (keyPair.getPrivate() instanceof RSAPrivateKey) { RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder() .find(hashAlgo + "withRSA"); AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId); signer = new BcRSAContentSignerBuilder(sigAlgId, digAlgId) .build(new RSAKeyParameters(true, privateKey.getModulus(), privateKey.getPrivateExponent())); } else { throw new KeyGenerationRuntimeException("Unsupported key type"); } return signer; }
From source file:co.lqnt.lockbox.key.PublicKey.java
License:Open Source License
/** * Get the Bouncy Castle RSA public key parameters. * * @return The Bouncy Castle RSA public key parameters. *//*from w w w. j ava2 s . c o m*/ public RSAKeyParameters bcPublicKeyParameters() { return new RSAKeyParameters(false, this.modulus(), this.publicExponent()); }
From source file:com.android.builder.internal.packaging.sign.SignatureTestUtils.java
License:Apache License
/** * Generates a private key / certificate. * * @param sign the asymmetric cypher, <em>e.g.</em>, {@code RSA} * @param full the full signature algorithm name, <em>e.g.</em>, {@code SHA1withRSA} * @return the pair with the private key and certificate * @throws Exception failed to generate the signature data *//*from w w w .j a va2 s . c o m*/ @NonNull public static Pair<PrivateKey, X509Certificate> generateSignature(@NonNull String sign, @NonNull String full) throws Exception { // http://stackoverflow.com/questions/28538785/ // easy-way-to-generate-a-self-signed-certificate-for-java-security-keystore-using KeyPairGenerator generator = null; try { generator = KeyPairGenerator.getInstance(sign); } catch (NoSuchAlgorithmException e) { Assume.assumeNoException("Algorithm " + sign + " not supported.", e); } assertNotNull(generator); KeyPair keyPair = generator.generateKeyPair(); Date notBefore = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000); Date notAfter = new Date(System.currentTimeMillis() + 365L * 24 * 60 * 60 * 1000); X500Name issuer = new X500Name(new X500Principal("cn=Myself").getName()); SubjectPublicKeyInfo publicKeyInfo; if (keyPair.getPublic() instanceof RSAPublicKey) { RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic(); publicKeyInfo = SubjectPublicKeyInfoFactory.createSubjectPublicKeyInfo( new RSAKeyParameters(false, rsaPublicKey.getModulus(), rsaPublicKey.getPublicExponent())); } else if (keyPair.getPublic() instanceof ECPublicKey) { publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()); } else { fail(); publicKeyInfo = null; } X509v1CertificateBuilder builder = new X509v1CertificateBuilder(issuer, BigInteger.ONE, notBefore, notAfter, issuer, publicKeyInfo); ContentSigner signer = new JcaContentSignerBuilder(full).setProvider(new BouncyCastleProvider()) .build(keyPair.getPrivate()); X509CertificateHolder holder = builder.build(signer); JcaX509CertificateConverter converter = new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()); return Pair.of(keyPair.getPrivate(), converter.getCertificate(holder)); }
From source file:com.bitbreeds.webrtc.dtls.WebrtcDtlsServer.java
License:Open Source License
protected TlsSignerCredentials getRSASignerCredentials() throws IOException { RSAPrivateCrtKeyImpl key = (RSAPrivateCrtKeyImpl) (pair.getValue().getPrivate()); return new DefaultTlsSignerCredentials(context, cert, new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()), new SignatureAndHashAlgorithm(HashAlgorithm.sha256, SignatureAlgorithm.rsa)); }
From source file:com.codename1.payments.GooglePlayValidator.java
/** * Create JWT token. See https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority * @param payload/*from www . ja va 2 s . c om*/ * @return */ private String createJWT(String payload) { try { Map header = new HashMap(); header.put("alg", "RS256"); header.put("typ", "JWT"); Map claims = new HashMap(); claims.put("iss", getGoogleClientId()); claims.put("scope", "https://www.googleapis.com/auth/androidpublisher"); claims.put("aud", "https://www.googleapis.com/oauth2/v4/token"); claims.put("exp", String.valueOf(System.currentTimeMillis() / 1000l + 1800)); claims.put("iat", String.valueOf(System.currentTimeMillis() / 1000l)); String headerEnc = Base64.encodeNoNewline(Result.fromContent(header).toString().getBytes("UTF-8")) .replace('+', '-').replace('/', '_').replace("=", " "); String claimsEnc = Base64.encodeNoNewline(Result.fromContent(claims).toString().getBytes("UTF-8")) .replace('+', '-').replace('/', '_').replace("=", " "); ; String sigContent = headerEnc + "." + claimsEnc; Digest digest = new SHA256Digest(); Signer signer = new RSADigestSigner(digest); String pkey = getGooglePrivateKey(); RSAPrivateKey rpkey = getRSAPrivateKey(pkey); signer.init(true, new RSAKeyParameters(true, rpkey.getModulus(), rpkey.getPrivateExponent())); byte[] sigBytes = sigContent.getBytes("UTF-8"); signer.update(sigBytes, 0, sigBytes.length); byte[] sig = signer.generateSignature(); RSAKeyParameters kp = new RSAKeyParameters(false, rpkey.getModulus(), rpkey.getPublicExponent()); signer.init(false, kp); signer.update(sigBytes, 0, sigBytes.length); boolean res = signer.verifySignature(sig); if (!res) { throw new RuntimeException("Failed to verify signature after creating it"); } String jwt = headerEnc + "." + claimsEnc + "." + Base64.encodeNoNewline(sig).replace('+', '-').replace('/', '_').replace("=", " "); ; return jwt; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.foilen.smalltools.crypt.asymmetric.RSACrypt.java
License:Open Source License
@Override public AsymmetricKeys createKeyPair(RSAKeyDetails keyDetails) { BigInteger modulus = keyDetails.getModulus(); AssertTools.assertNotNull(modulus, "The modulus must be present"); AsymmetricKeys asymmetricKeys = new AsymmetricKeys(); try {/* w w w . j av a 2 s.c o m*/ BigInteger publicExponent = keyDetails.getPublicExponent(); BigInteger privateExponent = keyDetails.getPrivateExponent(); if (publicExponent != null) { RSAKeyParameters publicKeyParameters = new RSAKeyParameters(false, modulus, publicExponent); asymmetricKeys.setPublicKey(publicKeyParameters); } if (privateExponent != null) { RSAKeyParameters privateKeyParameters = new RSAKeyParameters(true, modulus, privateExponent); asymmetricKeys.setPrivateKey(privateKeyParameters); } return asymmetricKeys; } catch (Exception e) { throw new SmallToolsException("Could not create the keys", e); } }
From source file:com.foilen.smalltools.crypt.bouncycastle.asymmetric.RSACrypt.java
License:Open Source License
@Override public AsymmetricKeys createKeyPair(RSAKeyDetails keyDetails) { if (keyDetails.getModulus() == null && keyDetails.getPrivateExponent() == null && keyDetails.getPublicExponent() == null) { return null; }/* w ww . java2 s . c om*/ BigInteger modulus = keyDetails.getModulus(); AssertTools.assertNotNull(modulus, "The modulus must be present"); AsymmetricKeys asymmetricKeys = new AsymmetricKeys(); try { BigInteger publicExponent = keyDetails.getPublicExponent(); BigInteger privateExponent = keyDetails.getPrivateExponent(); if (publicExponent != null) { RSAKeyParameters publicKeyParameters = new RSAKeyParameters(false, modulus, publicExponent); asymmetricKeys.setPublicKey(publicKeyParameters); } if (privateExponent != null) { RSAKeyParameters privateKeyParameters; if (keyDetails.isCrt()) { privateKeyParameters = new RSAPrivateCrtKeyParameters(modulus, publicExponent, privateExponent, keyDetails.getPrimeP(), keyDetails.getPrimeQ(), keyDetails.getPrimeExponentP(), keyDetails.getPrimeExponentQ(), keyDetails.getCrtCoefficient()); } else { privateKeyParameters = new RSAKeyParameters(true, modulus, privateExponent); } asymmetricKeys.setPrivateKey(privateKeyParameters); } return asymmetricKeys; } catch (Exception e) { throw new SmallToolsException("Could not create the keys", e); } }