org.spongycastle.jce.provider.BouncyCastleProvider Java Examples

The following examples show how to use org.spongycastle.jce.provider.BouncyCastleProvider. 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: ExportSignedPackage.java    From APDE with GNU General Public License v2.0 6 votes vote down vote up
protected ValidationResult loadCertificate(String keystoreUriPath, Uri keystoreUri, char[] keystorePassword, String alias) {
	Security.addProvider(new BouncyCastleProvider());
	
	ValidationResult result = new ValidationResult(13, ValidationResult.MessageSeverity.ERROR, R.string.export_signed_package_error_unexpected);
	
	ValidationResult keystoreResult = loadKeystore(keystoreUriPath, keystoreUri, keystorePassword);
	
	if (keystoreResult.resultCode() != 0) {
		result = keystoreResult;
	} else {
		try {
			if (keystore.containsAlias(alias)) {
				certificate = (X509Certificate) keystore.getCertificate(alias);
				
				//We just need to make sure that we can load these - we don't actually have to use them...
				result = new ValidationResult(0);
			}
		} catch (KeyStoreException e) {
			e.printStackTrace();
		}
	}
	
	return result;
}
 
Example #2
Source File: QlassifiedCrypto.java    From Qlassified-Android with MIT License 6 votes vote down vote up
public String encrypt(String input, RSAPublicKey publicKey) {

        if (input == null) {
            return null;
        }

        try {
            byte[] dataBytes = input.getBytes(CHARSET);
            Cipher cipher = Cipher.getInstance(ALGORITHM, new BouncyCastleProvider());
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            return Base64.encodeToString(cipher.doFinal(dataBytes), BASE64_MODE);
        } catch (IllegalBlockSizeException |
                BadPaddingException |
                NoSuchAlgorithmException |
                NoSuchPaddingException |
                UnsupportedEncodingException |
                InvalidKeyException e) {
            Log.e("QlassifiedCrypto", String.format("Could not encrypt this string. Stacktrace: %s", e));
            return null;
        }
    }
 
Example #3
Source File: SigningUtil.java    From commcare-android with Apache License 2.0 5 votes vote down vote up
private static boolean verifyMessageSignature(PublicKey publicKey,
                                              String messageString, byte[] signature)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
    Signature sign = Signature.getInstance("SHA256withRSA/PSS", new BouncyCastleProvider());
    byte[] message = messageString.getBytes();
    sign.initVerify(publicKey);
    sign.update(message);
    return sign.verify(signature);
}
 
Example #4
Source File: ExportSignedPackage.java    From APDE with GNU General Public License v2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected void writeKey(String keystoreUriPath, Uri keystoreUri, char[] keystorePassword,
						String alias, char[] password, int validity, String name,
						String orgUnit, String org, String city, String state, String country) {
	try {
		Security.addProvider(new BouncyCastleProvider());
		
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
		SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
		keyGen.initialize(1024, random);
		KeyPair pair = keyGen.generateKeyPair();
		
		X509V3CertificateGenerator v3CertGen = new X509V3CertificateGenerator();
		
		X509Principal principal = new X509Principal("CN=" + formatDN(name) + ", OU=" + formatDN(orgUnit) + ", O=" + formatDN(org)
				+ ", L=" + formatDN(city) + ", ST=" + formatDN(state) + ", C=" + formatDN(country));
		
		int serial = new SecureRandom().nextInt();
		
		v3CertGen.setSerialNumber(BigInteger.valueOf(serial < 0 ? -1 * serial : serial));
		v3CertGen.setIssuerDN(principal);
		v3CertGen.setNotBefore(new Date(System.currentTimeMillis()));
		v3CertGen.setNotAfter(new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * validity))); //TODO Doesn't take leap days / years into account...
		v3CertGen.setSubjectDN(principal);
		v3CertGen.setPublicKey(pair.getPublic());
		v3CertGen.setSignatureAlgorithm("MD5WithRSAEncryption");
		
		X509Certificate pkCertificate = v3CertGen.generateX509Certificate(pair.getPrivate());
		
		keystore.setKeyEntry(alias, pair.getPrivate(), password, new Certificate[] {pkCertificate});
		
		//Write the new key to the keystore
		writeKeystore(keystoreUriPath, keystoreUri, keystorePassword);
		
		//Reload the keystore so that the new key will appear
		loadAliases((ArrayList<String>) loadKeystore(keystoreUriPath, keystoreUri, keystorePassword).extra());
	} catch (NoSuchAlgorithmException | KeyStoreException | InvalidKeyException | SecurityException | SignatureException e) {
		e.printStackTrace();
	}
}
 
Example #5
Source File: SignatureService.java    From CameraV with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings({"deprecation" })
public void initKey(ISecretKey sk) throws PGPException {
	authKey = sk.secretAuthToken;
	secretKey = KeyUtility.extractSecretKey(sk.secretKey.getBytes());
	privateKey = secretKey.extractPrivateKey(authKey.toCharArray(), new BouncyCastleProvider());
	publicKey = secretKey.getPublicKey();
	
	sk = null;		
}
 
Example #6
Source File: JumbleCertificateGenerator.java    From Jumble with GNU General Public License v3.0 5 votes vote down vote up
public static X509Certificate generateCertificate(OutputStream output) throws NoSuchAlgorithmException, OperatorCreationException, CertificateException, KeyStoreException, NoSuchProviderException, IOException {
	BouncyCastleProvider provider = new BouncyCastleProvider(); // Use SpongyCastle provider, supports creating X509 certs
	KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
	generator.initialize(2048, new SecureRandom());
	
	KeyPair keyPair = generator.generateKeyPair();
	
	SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded());
	ContentSigner signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider(provider).build(keyPair.getPrivate());
	
	Date startDate = new Date();
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(startDate);
	calendar.add(Calendar.YEAR, YEARS_VALID);
    Date endDate = calendar.getTime();
	
	X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder(new X500Name(ISSUER),
			BigInteger.ONE, 
			startDate, endDate, new X500Name(ISSUER),
			publicKeyInfo);

	X509CertificateHolder certificateHolder = certBuilder.build(signer);
	
	X509Certificate certificate = new JcaX509CertificateConverter().setProvider(provider).getCertificate(certificateHolder);
	
	KeyStore keyStore = KeyStore.getInstance("PKCS12", provider);
	keyStore.load(null, null);
	keyStore.setKeyEntry("Jumble Key", keyPair.getPrivate(), null, new X509Certificate[] { certificate });
	
	keyStore.store(output, "".toCharArray());
	
	return certificate;
}
 
Example #7
Source File: CocosBcxApiWrapper.java    From AndroidWallet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Initialize SDK
 */
public void init(Context context) {
    //init ThreadPool
    proxy = ThreadManager.getThreadPollProxy();
    // need to init in case some class can not use
    Security.insertProviderAt(new BouncyCastleProvider(), 1);
    // init db dao
    accountDao = new AccountDao(context);
    //  class to deal business logic
    cocosBcxApi = CocosBcxApi.getBcxInstance();
}
 
Example #8
Source File: KeyCodec.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * Decode based on d - 32 byte integer
 *
 * @param privKey
 * @param curveName - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PrivateKey getPrivKeyFromCurve(byte[] privKey, String curveName) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
    KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec(curveName, spec.getCurve(), spec.getG(), spec.getN());
    ECPrivateKeySpec priKey = new ECPrivateKeySpec(
            new BigInteger(privKey), // d
            params);
    return kf.generatePrivate(priKey);
}
 
Example #9
Source File: KeyCodec.java    From UAF with Apache License 2.0 5 votes vote down vote up
/**
 * Decode based on X, Y 32 byte integers
 *
 * @param pubKey
 * @param curveName - Example secp256r1
 * @return
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
public static PublicKey getPubKeyFromCurve(byte[] pubKey, String curveName) throws InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {

    ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec(curveName);
    KeyFactory kf = KeyFactory.getInstance("ECDSA", new BouncyCastleProvider());
    ECNamedCurveSpec params = new ECNamedCurveSpec(curveName, spec.getCurve(), spec.getG(), spec.getN());
    ECPoint point = ECPointUtil.decodePoint(params.getCurve(), pubKey);
    ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
    ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);
    return pk;
}
 
Example #10
Source File: BitsharesApplication.java    From bitshares_wallet with MIT License 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();
    Fabric.with(this, new Crashlytics());
    Security.insertProviderAt(new BouncyCastleProvider(), 1);

    bitsharesDatabase = Room.databaseBuilder(
            this,
            BitsharesDatabase.class,
            "bitshares.db"
    ).build();

    // 注册回调,保证数据更新
}
 
Example #11
Source File: KeyStoreFileManager.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
public static KeyStore createKeyStore( String keystorePath, char[] password)
    throws Exception
{
    KeyStore ks = null;
    if (keystorePath.toLowerCase().endsWith(".bks")) {
        ks = KeyStore.getInstance("bks", new BouncyCastleProvider());
    }
    else ks = new JksKeyStore();
    ks.load(null, password);

    return ks;
}
 
Example #12
Source File: SpongyCryptography.java    From Jabit with Apache License 2.0 4 votes vote down vote up
public SpongyCryptography() {
    super(new BouncyCastleProvider());
}
 
Example #13
Source File: decrypt12.java    From WhatsApp-Crypt12-Decrypter with GNU General Public License v3.0 4 votes vote down vote up
public static void decrypt(String KeyFile, String C12File, String SQLFile) throws Exception {

		final File tempFile = new File(System.getProperty("java.io.tmpdir") + "/"
				+ (int) (System.currentTimeMillis() / 1000L) + "-msgstore.enc");

		if (!new File(KeyFile).isFile())
			quit("The specified input key file does not exist.");

		else if (new File(KeyFile).length() != 158)
			quit("The specified input key file is invalid.");

		else if (!new File(C12File).isFile())
			quit("The specified input crypt12 file does not exist.");

		InputStream KeyIn = new FileInputStream(KeyFile);
		InputStream WdbIn = new BufferedInputStream(new FileInputStream(C12File));

		byte[] KeyData = new byte[158];
		KeyIn.read(KeyData);
		byte[] T1 = new byte[32];
		System.arraycopy(KeyData, 30, T1, 0, 32);
		byte[] KEY = new byte[32];
		System.arraycopy(KeyData, 126, KEY, 0, 32);
		KeyIn.close();

		byte[] C12Data = new byte[67];
		WdbIn.read(C12Data);
		byte[] T2 = new byte[32];
		System.arraycopy(C12Data, 3, T2, 0, 32);
		byte[] IV = new byte[16];
		System.arraycopy(C12Data, 51, IV, 0, 16);

		if (!new String(T1, 0, T1.length, "ASCII").equals(new String(T2, 0, T2.length, "ASCII")))
			quit("Key file mismatch or crypt12 file is corrupt.");

		int InputLength = WdbIn.available();
		RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");

		byte[] tempBuffer = new byte[1024];
		int I;

		while ((I = WdbIn.read(tempBuffer)) != -1)
			raf.write(tempBuffer, 0, I);
		raf.setLength(InputLength - 20);
		raf.close();
		WdbIn.close();

		InputStream PdbSt = new BufferedInputStream(new FileInputStream(tempFile));

		Cipher cipher;
		Security.addProvider(new BouncyCastleProvider());
		cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC"); // BouncyCastle
		// cipher = Cipher.getInstance("AES/GCM/NoPadding", "SC"); // SpongyCastle (Android)

		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(KEY, "AES"), new IvParameterSpec(IV));
		CipherInputStream CipherStream = new CipherInputStream(PdbSt, cipher);

		InflaterInputStream CryptOutput = new InflaterInputStream(CipherStream, new Inflater(false));

		try {
			FileOutputStream InflateBuffer = new FileOutputStream(SQLFile);
			int N = 0;
			byte[] CryptBuffer = new byte[8192];

			while ((N = CryptOutput.read(CryptBuffer)) != -1) {
				InflateBuffer.write(CryptBuffer, 0, N);
			}
			InflateBuffer.close();

		} catch (IOException ex) {
			quit("Fatal error:" + ex);
		}

		CipherStream.close();
		tempFile.delete();

		InputStream SqlDB = new FileInputStream(SQLFile);

		byte[] SqlData = new byte[6];
		SqlDB.read(SqlData);
		byte[] MS = new byte[6];
		System.arraycopy(SqlData, 0, MS, 0, 6);
		SqlDB.close();

		if (!new String(MS, 0, MS.length, "ASCII").toLowerCase().equals("sqlite")) {
			new File(SQLFile).delete();
			quit("Decryption of crypt12 file has failed.");
		}

		else
			quit("Decryption of crypt12 file was successful.");
	}
 
Example #14
Source File: SpongyCastleAllTests.java    From wycheproof with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  TestUtil.installOnlyThisProvider(new BouncyCastleProvider());
}
 
Example #15
Source File: MainActivity.java    From PdfBox-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a simple pdf and encrypts it
 */
public void createEncryptedPdf(View v)
{
    String path = root.getAbsolutePath() + "/crypt.pdf";

    int keyLength = 128; // 128 bit is the highest currently supported

    // Limit permissions of those without the password
    AccessPermission ap = new AccessPermission();
    ap.setCanPrint(false);

    // Sets the owner password and user password
    StandardProtectionPolicy spp = new StandardProtectionPolicy("12345", "hi", ap);

    // Setups up the encryption parameters
    spp.setEncryptionKeyLength(keyLength);
    spp.setPermissions(ap);
    BouncyCastleProvider provider = new BouncyCastleProvider();
    Security.addProvider(provider);

    PDFont font = PDType1Font.HELVETICA;
    PDDocument document = new PDDocument();
    PDPage page = new PDPage();

    document.addPage(page);

    try
    {
        PDPageContentStream contentStream = new PDPageContentStream(document, page);

        // Write Hello World in blue text
        contentStream.beginText();
        contentStream.setNonStrokingColor(15, 38, 192);
        contentStream.setFont(font, 12);
        contentStream.newLineAtOffset(100, 700);
        contentStream.showText("Hello World");
        contentStream.endText();
        contentStream.close();

        // Save the final pdf document to a file
        document.protect(spp); // Apply the protections to the PDF
        document.save(path);
        document.close();
        tv.setText("Successfully wrote PDF to " + path);

    }
    catch (IOException e)
    {
        Log.e("PdfBox-Android-Sample", "Exception thrown while creating PDF for encryption", e);
    }
}
 
Example #16
Source File: SpongyCastleTest.java    From wycheproof with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void setUp() throws Exception {
  TestUtil.installOnlyThisProvider(new BouncyCastleProvider());
}
 
Example #17
Source File: ExampleUnitTest.java    From bitshares_wallet with MIT License 4 votes vote down vote up
public ExampleUnitTest() {
    Security.insertProviderAt(new BouncyCastleProvider(), 1);
}
 
Example #18
Source File: KeyUtility.java    From CameraV with GNU General Public License v3.0 3 votes vote down vote up
@SuppressWarnings({ "deprecation" })
public static byte[] applySignature(byte[] data, PGPSecretKey secretKey, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws NoSuchAlgorithmException, PGPException, IOException, SignatureException {
	BouncyCastleProvider bc = new BouncyCastleProvider();
	Security.addProvider(bc);

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	
	OutputStream targetOut = new ArmoredOutputStream(baos);
	
	PGPSignatureGenerator sGen = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, bc);
	sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);
	
	PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZLIB);
	BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(targetOut));
	
	sGen.update(data);
	
	sGen.generate().encode(bOut);
	
	cGen.close();
	bOut.close();
	targetOut.close();
	
	byte[] outdata = baos.toByteArray();
	return outdata;


}
 
Example #19
Source File: KeyUtility.java    From CameraV with GNU General Public License v3.0 3 votes vote down vote up
@SuppressWarnings({ "deprecation" })
public static void applySignature(InputStream is, OutputStream os, PGPSecretKey secretKey, PGPPublicKey publicKey, PGPPrivateKey privateKey) throws NoSuchAlgorithmException, PGPException, IOException, SignatureException {
	BouncyCastleProvider bc = new BouncyCastleProvider();
	Security.addProvider(bc);
	
	OutputStream targetOut = new ArmoredOutputStream(os);
	
	PGPSignatureGenerator sGen = new PGPSignatureGenerator(secretKey.getPublicKey().getAlgorithm(), PGPUtil.SHA1, bc);
	sGen.initSign(PGPSignature.BINARY_DOCUMENT, privateKey);
	
	PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(PGPCompressedDataGenerator.ZLIB);
	BCPGOutputStream bOut = new BCPGOutputStream(cGen.open(targetOut));
	
	byte[] buf = new byte[4096];
	int len;
	
	while ((len = is.read(buf)) > 0) {
	            sGen.update(buf, 0, len);

	}
	
	sGen.generate().encode(bOut);
	
	cGen.close();
	bOut.close();
	targetOut.close();
		
}
 
Example #20
Source File: PgpHelper.java    From CameraV with GNU General Public License v3.0 3 votes vote down vote up
public void encryptFile(OutputStream out, String fileName,
                        PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck)
        throws IOException, NoSuchProviderException, PGPException {

    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
            PGPCompressedData.ZIP);

    PGPUtil.writeFileToLiteralData(comData.open(bOut),
            PGPLiteralData.BINARY, new File(fileName));

    comData.close();

    JcePGPDataEncryptorBuilder c = new JcePGPDataEncryptorBuilder(PGPEncryptedData.CAST5).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom()).setProvider("BC");

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(c);

    JcePublicKeyKeyEncryptionMethodGenerator d = new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()).setSecureRandom(new SecureRandom());

    cPk.addMethod(d);

    byte[] bytes = bOut.toByteArray();

    OutputStream cOut = cPk.open(out, bytes.length);

    cOut.write(bytes);

    cOut.close();

    out.close();
}
 
Example #21
Source File: EncryptionUtility.java    From CameraV with GNU General Public License v3.0 2 votes vote down vote up
@SuppressWarnings("deprecation")
public final static void encrypt(InputStream is, OutputStream os, byte[] publicKey) throws NoSuchProviderException, PGPException, IOException {
	
	BouncyCastleProvider bc = new BouncyCastleProvider();
	int bufferSize = 1 << 16;
	
	Security.addProvider(bc);
	
	OutputStream aos = new ArmoredOutputStream(os);
	
	PGPEncryptedDataGenerator edg = new PGPEncryptedDataGenerator(PGPEncryptedData.AES_256, true, new SecureRandom(), bc);
	edg.addMethod(KeyUtility.extractPublicKeyFromBytes(publicKey));
	OutputStream encOs = edg.open(aos, new byte[bufferSize]);
	
	PGPCompressedDataGenerator cdg = new PGPCompressedDataGenerator(PGPCompressedData.ZIP);
	OutputStream compOs = cdg.open(encOs);
	
	PGPLiteralDataGenerator ldg = new PGPLiteralDataGenerator();
	OutputStream litOs = ldg.open(compOs, PGPLiteralData.BINARY, PGPLiteralData.CONSOLE, new Date(System.currentTimeMillis()), new byte[bufferSize]);
	
	byte[] buf = new byte[bufferSize];
	
	int len;
	while((len = is.read(buf)) > 0)
		litOs.write(buf, 0, len);
	
	litOs.flush();
	litOs.close();
	ldg.close();
	
	compOs.flush();
	compOs.close();
	cdg.close();
	
	encOs.flush();
	encOs.close();
	edg.close();
	
	aos.close();
	
	is.close();
		
}
 
Example #22
Source File: PgpHelper.java    From CameraV with GNU General Public License v3.0 2 votes vote down vote up
public void encryptStream(OutputStream out, InputStream in,String fileName, long fileLength, java.util.Date fileMod,
                        PGPPublicKey encKey, boolean armor, boolean withIntegrityCheck)
        throws IOException, NoSuchProviderException, PGPException {

    if (armor) {
        out = new ArmoredOutputStream(out);
    }

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(
            PGPCompressedData.ZIP);

    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
    OutputStream pOut = lData.open(out, PGPLiteralData.BINARY, fileName, fileLength, fileMod);

    IOUtils.copy(in, pOut);

    pOut.close();
    in.close();

    comData.close();

    BcPGPDataEncryptorBuilder c = new BcPGPDataEncryptorBuilder(PGPEncryptedData.AES_256).setWithIntegrityPacket(withIntegrityCheck).setSecureRandom(new SecureRandom());//.setProvider("BC");

    PGPEncryptedDataGenerator cPk = new PGPEncryptedDataGenerator(c);

    JcePublicKeyKeyEncryptionMethodGenerator d = new JcePublicKeyKeyEncryptionMethodGenerator(encKey).setProvider(new org.spongycastle.jce.provider.BouncyCastleProvider()).setSecureRandom(new SecureRandom());

    cPk.addMethod(d);

    byte[] bytes = bOut.toByteArray();

    OutputStream cOut = cPk.open(out, bytes.length);

    cOut.write(bytes);

    cOut.close();

    out.close();
}