Example usage for org.bouncycastle.crypto.encodings PKCS1Encoding init

List of usage examples for org.bouncycastle.crypto.encodings PKCS1Encoding init

Introduction

In this page you can find the example usage for org.bouncycastle.crypto.encodings PKCS1Encoding init.

Prototype

public void init(boolean forEncryption, CipherParameters param) 

Source Link

Usage

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);
    byte[] decryptedSignatureDigest = pe.processBlock(signatureBytes, 0, signatureBytes.length);
    String decryptedSignatureDigestString = Hex.encodeHexString(decryptedSignatureDigest);
    return decryptedSignatureDigestString.equalsIgnoreCase(digest);
}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String rsaEncryptPassword(String publicKeyInPEM, String password) {
    String encrypted = "";
    try {//w w  w. j  av  a  2 s . c o m
        RSAKeyParameters rsaPublicKey;
        Reader reader = new StringReader(publicKeyInPEM);
        PemObject pemObj = new PemReader(reader).readPemObject();

        rsaPublicKey = (RSAKeyParameters) PublicKeyFactory.createKey(pemObj.getContent());

        byte[] bytesToEncrypt = password.getBytes(Charset.forName("UTF-8"));

        PKCS1Encoding encryptEngine = new PKCS1Encoding(new RSAEngine());
        encryptEngine.init(true, rsaPublicKey);
        encrypted = new String(
                Base64.encode(encryptEngine.processBlock(bytesToEncrypt, 0, bytesToEncrypt.length)),
                Charset.forName("UTF-8"));

    } catch (Exception ex) {
        logger.severe(" Failure attempting to encrypt via RSA.  \r\n PublicKeyInPEM:" + publicKeyInPEM
                + "\r\n Exception : " + ex.toString());
        throw new RuntimeException(
                " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : "
                        + ex.getMessage());
    }
    return encrypted;

}

From source file:com.logicoy.pdmp.pmpi.crypto.EncryptionClient.java

License:Apache License

public String rsaDecryptPassword(String PrivateKeyInPEM, String Base64Encrypted) {
    String decrypted = "";
    try {//w ww  .j  a  va2 s. c o m
        RSAKeyParameters rsaprivateKey;

        Reader reader = new StringReader(PrivateKeyInPEM);
        PemObject pemObj = new PemReader(reader).readPemObject();

        rsaprivateKey = (RSAKeyParameters) PrivateKeyFactory.createKey(pemObj.getContent());

        byte[] bytesToDecrypt = Base64.decode(Base64Encrypted);
        //byte[] bytesToDecrypt = Convert.FromBase64String(Base64Encrypted);

        PKCS1Encoding decryptEngine = new PKCS1Encoding(new RSAEngine());
        decryptEngine.init(false, rsaprivateKey);
        decrypted = new String(decryptEngine.processBlock(bytesToDecrypt, 0, bytesToDecrypt.length),
                Charset.forName("UTF-8"));
        //decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length));

    } catch (Exception ex) {
        //Without logging the private key lets get some info to make sure it looks like it could be a proper private key.
        String private_key_message = " Private key ";
        if (PrivateKeyInPEM.indexOf("----BEGIN PRIVATE KEY----") > 0) {
            private_key_message += " Has '----BEGIN PRIVATE KEY----' at pos "
                    + PrivateKeyInPEM.indexOf("----BEGIN PRIVATE KEY----");
        }
        if (PrivateKeyInPEM.indexOf("----END PRIVATE KEY----") > 0) {
            private_key_message += " Has '----END PRIVATE KEY----' at pos "
                    + PrivateKeyInPEM.indexOf("----END PRIVATE KEY----");
        }
        private_key_message += " Length : " + PrivateKeyInPEM.length();

        logger.log(Level.SEVERE,
                " Failure attempting to decrypt via RSA. \r\n Base64Encrypted string : " + Base64Encrypted
                        + " \r\n PrivateKeyInPEM " + private_key_message + " \r\n Exception : " + ex.toString(),
                ex);
        throw new RuntimeException(
                " Failure attempting to encrypt the RSA encrypted password. See Interface log for more details. Message : "
                        + ex.getMessage());
    }
    return decrypted.toString();
}

From source file:net.wstech2.me.httpsclient.CertificateValidatorUtils.java

License:Apache License

/**
 * /*from   w  ww  .j a v a2  s .co m*/
 * Inspected and display various informations from the Certificate passed as
 * parameter. Keys are presented in HEX values and ASN1 structures dumped
 * using ASN1Dump.dumpAsString.
 * 
 * This method is intended for debug purposes only.
 * 
 * 
 * @param cert
 *            The X509CertificateStructure to be inspected.
 * 
 */
public static void dumpCertificateInfo(org.bouncycastle.asn1.x509.Certificate cert) {
    boolean valid = false;
    TBSCertificate tbs = cert.getTBSCertificate();
    RSAEngine engine = new RSAEngine();
    SHA1Digest digest = new SHA1Digest();

    GenericSigner signer = new GenericSigner((engine), digest);
    RSAPublicKey signingKey;
    try {
        signingKey = RSAPublicKey.getInstance(cert.getSubjectPublicKeyInfo().parsePublicKey());

        HttpsConnectionUtils.logDebug("Public Key:[[" + cert.getSubjectPublicKeyInfo().parsePublicKey() + "]]");

        RSAKeyParameters keySpec = new RSAKeyParameters(false, signingKey.getModulus(),
                signingKey.getPublicExponent());
        signer.init(false, keySpec);
        HttpsConnectionUtils.logDebug("TBS DER object:[[" + tbs.getEncoded("DER") + "]]");

        signer.update(tbs.getEncoded(), 0, tbs.getEncoded().length);

        valid = signer.verifySignature(cert.getSignature().getBytes());

        HttpsConnectionUtils.logDebug("signer.verifySignature:[[" + valid + "]]");

        SHA1Digest d2 = new SHA1Digest();
        d2.update(tbs.getEncoded("DER"), 0, tbs.getEncoded("DER").length);
        byte[] hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("tbs.getDEREncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");
        DEROctetString asn1Hash = new DEROctetString(hash);
        HttpsConnectionUtils.logDebug(
                "ASN1 DEROctetString hash:[[" + new String(Hex.encode(asn1Hash.getEncoded("DER"))) + "]]");

        d2 = new SHA1Digest();
        d2.update(cert.getEncoded(), 0, cert.getEncoded().length);
        hash = new byte[d2.getDigestSize()];
        d2.doFinal(hash, 0);
        HttpsConnectionUtils.logDebug("cert.getEncoded() HASH:[[" + new String(Hex.encode(hash)) + "]]");

        byte[] signature = cert.getSignature().getBytes();
        HttpsConnectionUtils
                .logDebug("cert.getSignature().getBytes():[[" + new String(Hex.encode(signature)) + "]]");

        PKCS1Encoding engine2 = new PKCS1Encoding(new RSAEngine());
        engine2.init(false, keySpec);
        byte[] decryptedHash = engine2.processBlock(signature, 0, signature.length);
        HttpsConnectionUtils.logDebug("decryptedHash:[[" + new String(Hex.encode(decryptedHash)) + "]]");

        ASN1Object o = ASN1Primitive.fromByteArray(decryptedHash);
        HttpsConnectionUtils.logDebug(
                "decryptedHash.getDEREncoded():[[" + new String(Hex.encode(o.getEncoded("DER"))) + "]]");

        HttpsConnectionUtils.logDebug(
                "ASN1Dump.dumpAsString(decryptedHash,true):[[" + ASN1Dump.dumpAsString(o, true) + "]]");

        HttpsConnectionUtils.logDebug("engine.getInputBlockSize():[[" + engine2.getInputBlockSize() + "]]");

        HttpsConnectionUtils.logDebug("engine.getOutputBlockSize():[[" + engine2.getOutputBlockSize() + "]]");

        ASN1Sequence asn1SignSeq = (ASN1Sequence) ASN1Sequence.fromByteArray(decryptedHash);
        HttpsConnectionUtils
                .logDebug("Signature ASN1 Sequence:[[" + ASN1Dump.dumpAsString(asn1SignSeq, true) + "]]");

        AlgorithmIdentifier algorithm = AlgorithmIdentifier.getInstance(asn1SignSeq.getObjectAt(0));
        HttpsConnectionUtils.logDebug("AlgorithmIdentifier:[[" + ASN1Dump.dumpAsString(algorithm, true) + "]]");

        DEROctetString signedHash = (DEROctetString) DEROctetString.getInstance(asn1SignSeq.getObjectAt(1));
        HttpsConnectionUtils.logDebug("signedHash:[[" + ASN1Dump.dumpAsString(signedHash, true) + "]]");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static SignedDigest signDigest(byte dig[], BBytes peerid, RSAPrivateCrtKeyParameters key) {
    SignedDigest s = new SignedDigest();
    RSAEngine eng = new RSAEngine();
    byte pai[] = peerid.getBytes();
    byte signblock[] = new byte[dig.length + pai.length];
    System.arraycopy(dig, 0, signblock, 0, dig.length);
    System.arraycopy(pai, 0, signblock, dig.length, pai.length);
    PKCS1Encoding enc = new PKCS1Encoding(eng);
    enc.init(true, key);
    try {//  w  ww  . ja  v  a  2 s .co  m
        byte sig[] = enc.processBlock(signblock, 0, signblock.length);
        s.setDigest(new BBytes(dig));
        s.setPeerIdentifier(peerid);
        s.setSignature(new BBytes(sig));
        return s;
    } catch (InvalidCipherTextException e) {
        e.printStackTrace();
        throw new RuntimeException(e.getMessage());
    }
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static boolean verifySignedDigest(SignedDigest s, byte checkdig[], PublicKeySet pub) {
    if (!Arrays.equals(((BBytes) s.getDigest()).getBytes(), checkdig)) {
        return false;
    }//from   w  w w .ja  v  a  2 s.  co m
    RSAEngine eng = new RSAEngine();
    PKCS1Encoding enc = new PKCS1Encoding(eng);
    enc.init(false, (CipherParameters) pub.getPublicSigningKey());
    byte sig[] = ((BBytes) s.getSignature()).getBytes();
    try {
        byte decsig[] = enc.processBlock(sig, 0, sig.length);
        byte encdig[] = new byte[checkdig.length];
        System.arraycopy(decsig, 0, encdig, 0, encdig.length);
        byte encpeer[] = new byte[decsig.length - checkdig.length];
        System.arraycopy(decsig, checkdig.length, encpeer, 0, encpeer.length);
        byte[] genpeer = digestPublicKey(pub);
        boolean signmatch = Arrays.equals(encdig, checkdig);
        boolean idmatch = Arrays.equals(genpeer, encpeer);
        return signmatch && idmatch;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return false;
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static String decodePublicPost(BBytes enc, RSAPrivateCrtKeyParameters key) {
    try {/*from  ww w.  j ava2s  .  c om*/
        byte encdata[] = enc.getBytes();

        //Extract the header
        ByteBuffer bbuf = ByteBuffer.wrap(encdata);
        int headlen = bbuf.getInt();
        if (headlen > 4096) {
            throw new Exception("Header is too long: " + headlen);
        }
        byte head[] = new byte[headlen];
        System.arraycopy(encdata, Integer.SIZE / Byte.SIZE, head, 0, headlen);

        //Decode the header
        RSAEngine eng = new RSAEngine();
        PKCS1Encoding eng2 = new PKCS1Encoding(eng);
        eng2.init(false, key);

        byte dechead[] = eng2.processBlock(head, 0, head.length);
        if (dechead.length < (2 * Long.SIZE / Byte.SIZE)) {
            //Magic number can't be there, not enough data.
            return null;
        }
        ByteBuffer mbuf = ByteBuffer.wrap(dechead);
        long m0 = mbuf.getLong();
        long m1 = mbuf.getLong();
        if (m0 != 0x01234567) {
            return null;
        }
        if (m1 != 0x76543210) {
            return null;
        }
        //Exctract the symmetric key.
        byte skey[] = new byte[dechead.length - (2 * Long.SIZE / Byte.SIZE)];
        System.arraycopy(dechead, 2 * Long.SIZE / Byte.SIZE, skey, 0, skey.length);

        KeyParameter kp = new KeyParameter(skey);

        CBCBlockCipher aes = new CBCBlockCipher(new AESEngine());
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new PKCS7Padding());
        cipher.init(false, kp);

        int foffset = (Integer.SIZE / Byte.SIZE) + headlen;
        int enclen = encdata.length - foffset;
        byte[] output = new byte[cipher.getOutputSize(enclen)];
        int len = cipher.processBytes(encdata, foffset, enclen, output, 0);
        int len2 = cipher.doFinal(output, len);

        byte rawdata[] = new byte[len + len2];

        System.arraycopy(output, 0, rawdata, 0, rawdata.length);

        return new String(rawdata, Charset.forName("UTF-16BE"));
    } catch (Exception e) {
        //e.printStackTrace();         
    }
    return null;
}

From source file:org.ourfilesystem.security.SecurityTools.java

License:Open Source License

public static BBytes encodePublicPost(String raw, PublicKeySet pubkey) {
    try {//from   w  w w.j a v a 2 s. c  om
        byte strb[] = raw.getBytes(Charset.forName("UTF-16BE"));

        byte[] key = new byte[32];
        Random.nextBytes(key);
        KeyParameter kp = new KeyParameter(key);

        CBCBlockCipher aes = new CBCBlockCipher(new AESEngine());
        PaddedBufferedBlockCipher cipher = new PaddedBufferedBlockCipher(aes, new PKCS7Padding());
        cipher.init(true, kp);

        byte[] output = new byte[cipher.getOutputSize(strb.length)];
        int len = cipher.processBytes(strb, 0, strb.length, output, 0);
        cipher.doFinal(output, len);

        RSAEngine eng = new RSAEngine();

        byte headblk[] = new byte[(2 * Long.SIZE / Byte.SIZE) + key.length];
        ByteBuffer bbuf = ByteBuffer.wrap(headblk);
        bbuf.putLong(0x01234567); //magic number
        bbuf.putLong(0x76543210); //magic number
        System.arraycopy(key, 0, headblk, (2 * Long.SIZE / Byte.SIZE), key.length);

        PKCS1Encoding enc = new PKCS1Encoding(eng);
        enc.init(true, (CipherParameters) pubkey.getPublicEncryptionKey());

        byte enchead[] = enc.processBlock(headblk, 0, headblk.length);

        byte rslt[] = new byte[(Integer.SIZE / Byte.SIZE) + enchead.length + output.length];

        ByteBuffer rbuf = ByteBuffer.wrap(rslt);
        rbuf.putInt(enchead.length);
        System.arraycopy(enchead, 0, rslt, Integer.SIZE / Byte.SIZE, enchead.length);
        System.arraycopy(output, 0, rslt, (Integer.SIZE / Byte.SIZE) + enchead.length, output.length);

        BBytes orslt = new BBytes(rslt);
        return orslt;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * checks signature of PKCS1-padded SHA1 hash of the input
 * /*w ww . j  a v  a  2 s .  co  m*/
 * Hint: A different implementation of this method can be found in the svn history revision<=229. 
 * 
 * @param signature
 *            signature to check
 * @param signingKey
 *            public key from signing
 * @param input
 *            byte array, signature is made over
 * 
 * @return true, if the signature is correct
 * 
 */
public static boolean verifySignature(byte[] signature, RSAPublicKeyStructure signingKey, byte[] input) {
    byte[] hash = getDigest(input);

    try {
        RSAKeyParameters myRSAKeyParameters = new RSAKeyParameters(false, signingKey.getModulus(),
                signingKey.getPublicExponent());

        PKCS1Encoding pkcsAlg = new PKCS1Encoding(new RSAEngine());
        pkcsAlg.init(false, myRSAKeyParameters);

        byte[] decryptedSignature = pkcsAlg.processBlock(signature, 0, signature.length);

        return Encoding.arraysEqual(hash, decryptedSignature);

    } catch (Exception e) {
        log.log(Level.WARNING, "unexpected", e);
        return false;
    }
}

From source file:org.silvertunnel.netlib.layer.tor.util.Encryption.java

License:Open Source License

/**
 * sign some data using a private key and PKCS#1 v1.5 padding
 * // w  w  w.  j  a  v  a 2s.c  om
 * @param data
 *            the data to be signed
 * @param signingKey
 *            the key to sign the data
 * @return a signature
 */
public static byte[] signData(byte[] data, RSAKeyParameters signingKey) {
    try {
        byte[] hash = Encryption.getDigest(data);
        PKCS1Encoding pkcs1 = new PKCS1Encoding(new RSAEngine());
        pkcs1.init(true, signingKey);
        return pkcs1.processBlock(hash, 0, hash.length);
    } catch (InvalidCipherTextException e) {
        log.log(Level.WARNING, "Common.signData(): " + e.getMessage(), e);
        return null;
    }
}