首页 > 其他分享 >使用KeyPairGenerator生成公私钥对(oppo平台需要)

使用KeyPairGenerator生成公私钥对(oppo平台需要)

时间:2022-10-26 18:24:02浏览次数:64  
标签:return String keyMap KeyPairGenerator KEY 钥对 static public oppo

下面是oppo平台的生成公钥的要求

公钥需要使用 RSA 算法生成,1024 位,生成后使用 Base64 进行编码,编码后的长度是 216 位

Base64 使用了 Apache 的 commons-codec 工具包,这个我也提供下,也可以直接去maven仓库下载

https://repo1.maven.org/maven2/commons-codec/commons-codec/1.10/commons-codec-1.10.jar

public class MyRSAUtils {

    /**
     * \* 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * \* 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * \* 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * \* <p>
     * \* 生成密钥对(公钥和私钥)
     * \* </p>
     * <p>
     * \* @return
     * \* @throws Exception
     */

    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return base64Encode(key.getEncoded());
    }

    public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return base64Encode(key.getEncoded());
    }

    /**
     * \* 用base64编码
     * \* @param bytes
     * \* @return
     */
    private static String base64Encode(byte[] bytes) {
        return new String(Base64.encodeBase64(bytes));
    }

    public static void main(String[] args) throws Exception {
        Map<String, Object> pairs = MyRSAUtils.genKeyPair();
        System.out.println("公钥:" + MyRSAUtils.getPublicKey(pairs));
        System.out.println("私钥:" + MyRSAUtils.getPrivateKey(pairs));
    }
}

标签:return,String,keyMap,KeyPairGenerator,KEY,钥对,static,public,oppo
From: https://www.cnblogs.com/maowuge/p/16829505.html

相关文章

  • 扣动“车机互联”扳机,OPPO能成功“上岸”?
    (图片来源于网络,侵删)文|智能相对论作者|叶小安新能源汽车市场内迎来了新的挑战者——OPPOCarlink。只是,这位挑战者想夺下的不是智能汽车市场,而是车联网市场。今年的开发者大......
  • 有了潘塔纳尔这张王牌,OPPO能成为最佳生态伙伴吗?
    2020年中国IoT设备连接数量为74亿,今年预计达到105亿,人均7台智能设备。 智能设备以各种丰富的形态来到我们的生活中,从设备数量的发展来看,说了很多年的万物互联时代已经......
  • Opposites Attract
    Timmy&Sarahthinktheyareinlove,butaroundwheretheylive,theywillonlyknowoncetheypickaflowereach.Ifoneoftheflowershasanevennumberof......