当前位置:K88软件开发文章中心编程语言.NET.NET02 → 文章内容

java与.net平台之间进行RSA加密验证

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2019-1-3 0:48:57

ivateKey = getRSAPrivateKeyAsNetFormat(privateKeyBytes);
            writeKeyBytesToFile(netPrivateKey.getBytes(), netPrivateKeyPath);

            String netPublicKey = getRSAPublicKeyAsNetFormat(privateKeyBytes);
            writeKeyBytesToFile(netPublicKey.getBytes(), netPublicKeyPath);

        } catch (java.security.NoSuchAlgorithmException e) {
            System.out
                    .println("No such algorithm. Please check the JDK version."
                            + e.getCause());
        } catch (java.security.spec.InvalidKeySpecException ik) {
            System.out.println("Invalid Key Specs. Not valid Key files."
                    + ik.getCause());
        } catch (UnsupportedEncodingException ex) {
            System.out.println(ex);
        } catch (IOException ioe) {
            System.out.println("Files not found on specified path. "
                    + ioe.getCause());
        } catch (Exception ex1) {
            System.out.println(ex1);
        }

    }

    /**//**
     * Initialize only the private key.
     */
    private void initializePrivateKey(String privateKeyStr) {
        try {
            // Read key files back and decode them from BASE64
            byte[] privateKeyBytes = b64decode(privateKeyStr);

            // Convert back to public and private key objects
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
                    privateKeyBytes);
            privateKey = keyFactory.generatePrivate(privateKeySpec);
        } catch (InvalidKeySpecException e) {
            System.out.println("Invalid Key Specs. Not valid Key files."
                    + e.getCause());
        } catch (NoSuchAlgorithmException e) {
            System.out
                    .println("There is no such algorithm. Please check the JDK ver."
                            + e.getCause());
        }
    }

    /**//**
     * Signs the data and return the signature for a given data.
     *
     * @param toBeSigned
     *            Data to be signed
     * @return byte[] Signature
     */
    private byte[] signData(byte[] toBeSigned, String EncodedCert) {
        if (privateKey == null) {
            initializePrivateKey(EncodedCert);
        }
        try {
            Signature rsa = Signature.getInstance("SHA1withRSA");
            rsa.initSign(privateKey);
            rsa.update(toBeSigned);
            return rsa.sign();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex);
        } catch (InvalidKeyException in) {
            System.out
                    .println("Invalid Key file.Please check the key file path"
                            + in.getCause());
        } catch (SignatureException se) {
            System.out.println(se);
        }
        return null;
    }

    /**//**
     * Verifies the signature for the given bytes using the public key.
     *
     * @param signature
     *            Signature
     * @param data
     *            Data that was signed
     * @param EncodedCert
     *            public key string
     * @return boolean True if valid signature else false
     */
    private boolean verifySignature(byte[] signature, byte[] data,
            String EncodedCert) {
        try {
            initializePublicKey(EncodedCert);
            sign.initVerify(publicKey);
            sign.update(data);
            return sign.verify(signature);
        } catch (SignatureException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
        }

        return false;
    }

    /**//**
     * Initializes the public and private keys.
     */
    private void initializePublicKey(String publicKeyStr) {
        try {
            // Read key files back and decode them from BASE64
            byte[] publicKeyBytes = b64decode(publicKeyStr);

            // Convert back to public and private key objects
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");

            EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                    publicKeyBytes);
            publicKey = keyFactory.generatePublic(publicKeySpec);

        } catch (InvalidKeySpecException e) {
            System.out.println("Invalid Key Specs. Not valid Key files."
                    + e.getCause());
        } catch (NoSuchAlgorithmException e) {
            System.out
                    .println("There is no such algorithm. Please check the JDK ver."
                            + e.getCause());
        }
    }

//    /**
//     * Gets the RSA Public Key. The key idea is to make the key readable for
//     * .Net platform.
//     *
//     * @param key
//     *            RSAPublicKey
//     * @return String the public key that .Net platform can read
//     */
//    private String getRSAPublicKeyAsNetFormat(RSAPublicKey key) {
//
//        byte[] modulusBytes = key.getModulus().toByteArray();
//        modulusBytes = stripLeadingZeros(modulusBytes);
//        String modules = b64encode(modulusBytes);
//
//        byte[] exponentBytes = key.getPublicExponent().toByteArray();
//        String exponent = b64encode(exponentBytes);
//
//        String result = "modules : " + modules + "\r\n" + "exponent : "
//                + exponent;
//        return result;
//    }

    /**//**
     * Utility method to delete the leading zeros from the modulus.
     *
     * @param a
     *            modulus
     * @return modulus
     */
    private byte[] stripLeadingZeros(byte[] a) {
        int lastZero = -1;
        for (int i = 0; i < a.length; i++) {
            if (a[i] == 0) {
                lastZero = i;
            } else {
                break;
            }
        }
        lastZero++;
        byte[] result = new byte[a.length - lastZero];
        System.arraycopy(a, lastZero, result, 0, result.length);
        return result;
    }

    /**//**
     * Writes the bytes of the key in a file.
     *
     * @param key
     *            byte array of key data.
     * @param file
     *            File Name
     */
    private void writeKeyBytesToFile(byte[] key, String file)
            throws IOException {
        OutputStream out = new FileOutputStream(file);
        out.write(key);
        out.close();
    }

    // --- Returns XML encoded RSA private key string suitable for .NET
    // CryptoServiceProvider.FromXmlString(true) ------
    // --- Leading zero bytes (most significant) must be removed for XML
    // encoding for .NET; otherwise format error ---

    private String getRSAPrivateKeyAsNetFormat(byte[] encodedPrivkey) {
        try {
            StringBuffer buff = new StringBuff

上一页  [1] [2] [3] [4] [5]  下一页


java与.net平台之间进行RSA加密验证