SecretKeySpec

2023-05-16


/*
 * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

package javax.crypto.spec;

import java.security.MessageDigest;
import java.security.spec.KeySpec;
import java.util.Locale;
import javax.crypto.SecretKey;

/**
 * This class specifies a secret key in a provider-independent fashion.
 *
 * <p>It can be used to construct a <code>SecretKey</code> from a byte array,
 * without having to go through a (provider-based)
 * <code>SecretKeyFactory</code>.
 *
 * <p>This class is only useful for raw secret keys that can be represented as
 * a byte array and have no key parameters associated with them, e.g., DES or
 * Triple DES keys.
 *
 * @author Jan Luehe
 *
 * @see javax.crypto.SecretKey
 * @see javax.crypto.SecretKeyFactory
 * @since 1.4
 */
public class SecretKeySpec implements KeySpec, SecretKey {

    private static final long serialVersionUID = 6577238317307289933L;

    /**
     * The secret key.
     *
     * @serial
     */
    private byte[] key;

    /**
     * The name of the algorithm associated with this key.
     *
     * @serial
     */
    private String algorithm;

    /**
     * Constructs a secret key from the given byte array.
     *
     * <p>This constructor does not check if the given bytes indeed specify a
     * secret key of the specified algorithm. For example, if the algorithm is
     * DES, this constructor does not check if <code>key</code> is 8 bytes
     * long, and also does not check for weak or semi-weak keys.
     * In order for those checks to be performed, an algorithm-specific
     * <i>key specification</i> class (in this case:
     * {@link DESKeySpec DESKeySpec})
     * should be used.
     *
     * @param key the key material of the secret key. The contents of
     * the array are copied to protect against subsequent modification.
     * @param algorithm the name of the secret-key algorithm to be associated
     * with the given key material.
     * See Appendix A in the <a href=
     *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture Reference Guide</a>
     * for information about standard algorithm names.
     * @exception IllegalArgumentException if <code>algorithm</code>
     * is null or <code>key</code> is null or empty.
     */
    public SecretKeySpec(byte[] key, String algorithm) {
        if (key == null || algorithm == null) {
            throw new IllegalArgumentException("Missing argument");
        }
        if (key.length == 0) {
            throw new IllegalArgumentException("Empty key");
        }
        this.key = key.clone();
        this.algorithm = algorithm;
    }

    /**
     * Constructs a secret key from the given byte array, using the first
     * <code>len</code> bytes of <code>key</code>, starting at
     * <code>offset</code> inclusive.
     *
     * <p> The bytes that constitute the secret key are
     * those between <code>key[offset]</code> and
     * <code>key[offset+len-1]</code> inclusive.
     *
     * <p>This constructor does not check if the given bytes indeed specify a
     * secret key of the specified algorithm. For example, if the algorithm is
     * DES, this constructor does not check if <code>key</code> is 8 bytes
     * long, and also does not check for weak or semi-weak keys.
     * In order for those checks to be performed, an algorithm-specific key
     * specification class (in this case:
     * {@link DESKeySpec DESKeySpec})
     * must be used.
     *
     * @param key the key material of the secret key. The first
     * <code>len</code> bytes of the array beginning at
     * <code>offset</code> inclusive are copied to protect
     * against subsequent modification.
     * @param offset the offset in <code>key</code> where the key material
     * starts.
     * @param len the length of the key material.
     * @param algorithm the name of the secret-key algorithm to be associated
     * with the given key material.
     * See Appendix A in the <a href=
     *   "{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/security/crypto/CryptoSpec.html#AppA">
     * Java Cryptography Architecture Reference Guide</a>
     * for information about standard algorithm names.
     * @exception IllegalArgumentException if <code>algorithm</code>
     * is null or <code>key</code> is null, empty, or too short,
     * i.e. {@code key.length-offset<len}.
     * @exception ArrayIndexOutOfBoundsException is thrown if
     * <code>offset</code> or <code>len</code> index bytes outside the
     * <code>key</code>.
     */
    public SecretKeySpec(byte[] key, int offset, int len, String algorithm) {
        if (key == null || algorithm == null) {
            throw new IllegalArgumentException("Missing argument");
        }
        if (key.length == 0) {
            throw new IllegalArgumentException("Empty key");
        }
        if (key.length-offset < len) {
            throw new IllegalArgumentException
                ("Invalid offset/length combination");
        }
        if (len < 0) {
            throw new ArrayIndexOutOfBoundsException("len is negative");
        }
        this.key = new byte[len];
        System.arraycopy(key, offset, this.key, 0, len);
        this.algorithm = algorithm;
    }

    /**
     * Returns the name of the algorithm associated with this secret key.
     *
     * @return the secret key algorithm.
     */
    public String getAlgorithm() {
        return this.algorithm;
    }

    /**
     * Returns the name of the encoding format for this secret key.
     *
     * @return the string "RAW".
     */
    public String getFormat() {
        return "RAW";
    }

    /**
     * Returns the key material of this secret key.
     *
     * @return the key material. Returns a new array
     * each time this method is called.
     */
    public byte[] getEncoded() {
        return this.key.clone();
    }

    /**
     * Calculates a hash code value for the object.
     * Objects that are equal will also have the same hashcode.
     */
    public int hashCode() {
        int retval = 0;
        for (int i = 1; i < this.key.length; i++) {
            retval += this.key[i] * i;
        }
        if (this.algorithm.equalsIgnoreCase("TripleDES"))
            return (retval ^= "desede".hashCode());
        else
            return (retval ^=
                    this.algorithm.toLowerCase(Locale.ENGLISH).hashCode());
    }

   /**
     * Tests for equality between the specified object and this
     * object. Two SecretKeySpec objects are considered equal if
     * they are both SecretKey instances which have the
     * same case-insensitive algorithm name and key encoding.
     *
     * @param obj the object to test for equality with this object.
     *
     * @return true if the objects are considered equal, false if
     * <code>obj</code> is null or otherwise.
     */
    public boolean equals(Object obj) {
        if (this == obj)
            return true;

        if (!(obj instanceof SecretKey))
            return false;

        String thatAlg = ((SecretKey)obj).getAlgorithm();
        if (!(thatAlg.equalsIgnoreCase(this.algorithm))) {
            if ((!(thatAlg.equalsIgnoreCase("DESede"))
                 || !(this.algorithm.equalsIgnoreCase("TripleDES")))
                && (!(thatAlg.equalsIgnoreCase("TripleDES"))
                    || !(this.algorithm.equalsIgnoreCase("DESede"))))
            return false;
        }

        byte[] thatKey = ((SecretKey)obj).getEncoded();

        return MessageDigest.isEqual(this.key, thatKey);
    }
}
  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SecretKeySpec 的相关文章

  • Redis开源代码读书笔记九(Object模块)

    Object功能特性 61 61 支持REDIS STRING REDIS LIST REDIS SET REDIS ZSET REDIS HASH对象类型 61 61 支持对象引用计数 61 61 支持对象内存优化 61 61 支持对象比
  • 【C语言】函数默认实现和用户自定义实现编程方法 -- 【weak, strong alias】

    现在很多业务开发 xff0c 尤其是互联网应用 xff0c 绝大多数采用的是Java xff0c 这个不仅仅是Java语言的流行 xff0c 还有很多分布式框架都是采用的Java 而传统的C C 43 43 开发更为偏向底层等高效率基础功能
  • redis启动失败

    可能端口被占用 解决方法 xff08 1 xff09 打开cmd xff0c 查看端口6379是否被某个进程占用 xff0c 跳出一个空白cmd说明被占用 telnet 127 0 0 1 6379 xff08 2 xff09 重新打开一个
  • Linux下C语言实现文件遍历,支持嵌套和文件数量统计

    Linux命令行下有两个非常基本的命令 xff0c 一个是ls xff0c 一个是tree xff0c 其分别能够列出当前目录下的文件和树形方式嵌套显示目录结构 因为网络上有很多版本的文件遍历代码 xff0c 代码都没有整理过 xff0c
  • Linux系统参数配置简介

    Linux服务器在对应用程序进行优化配置的时候 xff0c 经常使用到sysctl和PAM两个模块对服务器进行优化 关于这两块的介绍也很多 xff0c 这里主要集中了相关内容 xff0c 并整体做了一个介绍 sysctl内核参数配置 使用
  • WindowsXp重启后,如何取消图标自动重排?

    问题现象 xff1a 在桌面右键 gt 排列图标 gt 自动排列 xff0c 功能取消后 xff08 对号去掉 xff09 xff0c 把图标拉到了桌面的右侧 可是注销或重启电脑之后 xff0c 图标又变成自动排列了 自动排列的对号也又自动
  • WindowsXp重启后,自定义任务栏丢失

    大致有以下几个原因导致自定义任务栏丢失 xff1a 第一 xff0c 系统设置 xff0c 重启时默认移除所有自定义任务栏 第二 xff0c 优化软件将自定义任务栏优化了 大致可以采用以下方法解决任务栏问题 xff1a 1 快速启动栏丢失
  • Linux应用程序之Helloworld入门

    对于初学者来说 xff08 本人就是 xff09 xff0c 如何开始写第一个程序至关重要 有的时候一个简单的问题会严重影响到学习的积极性和自信心 这里结合实际工作中的一些经验 xff0c 总结方法步骤 xff0c 对Linux下应用程序H
  • TCP Socket链接检测方法

    TCP网络应用程序开发中 xff0c 如果遇到了需要检查Socket链接问题 xff0c 通常是对这个TCP通道的时效性提出了要求 应用开发诉求 1 xff09 客户端需要了解管道提供正常数据通信链路 2 xff09 客户端需要确保管道异常
  • 一座逝去的里程碑VxWorks2Linux

    曾今有幸从事过VxWorks到Linux系统的应用层代码移植 xff0c 也没有总结过 只有涉及大量存量代码的公司才会存在该问题 xff0c 而实际情况证明 xff0c 即使有百万行代码的公司 xff0c 也会借助这种契机剥离API的依赖
  • 一个问题阻止Windows正确检查此机器的许可证

    遇到windows SP3更新问题 更新后 xff0c 系统启动弹出对话框提示 一个问题阻止Windows正确检查此机器的许可证 错误代码 xff1a 0x80070002 我的电脑问题解决方法 xff1a 从另外一台PC上复制了以下两个文
  • Linux下bash配置及执行顺序

    用户bash配置 1 bash history xff1a 记录了用户以前输入的命令 xff0c 2 bash login xff1a 如果 bash profile找不到 xff0c 则bash尝试读取这个脚本 3 bash logout
  • 在WindowsXp上如何设置默认其他浏览器

    设置默认浏览器 xff0c 相信大部分时间大家是默认打开IE或者其他浏览器的时候根据提示框设置的 以前我也从来不关注这个 xff0c 能用 xff0c 能上网看东西就可以了 但是越来越多的时间不使用IE了 xff0c 感觉有些工具或者Goo
  • Libsvm使用笔记【matlab】

    根据以下教程配置 xff1a 1038条消息 LIBSVM 繁拾简忆的博客 CSDN博客 https blog csdn net u014772862 category 6280683 html 目录 xff1a 一 libsvm使用 二
  • putty登录默认安装ubuntu,中文显示乱码问题

    putty是windows上常用的登录linux的终端工具 默认情况下安装的ubuntu xff0c 终端上显示的中文字符常常是乱码 这里给出一个简单的方法进行配置 确保ls命令能正常显示中文字符 第一步 xff1a 双击putty exe
  • C语言中#宏的一些用法和预编译宏展开问题

    宏定义大家都用过 xff0c 但是有些技巧性的宏应用 xff0c 在版本管理等方面有很重要的应用 这里我们介绍下 宏的一些用法 xff1a define Conn x y x y define ToChar x 64 x define To
  • 直接登录Windows桌面,不显示欢迎/登录屏幕

    Windows XP是一个比较安全的操作系统 xff0c 每次启动时都要求选择账户并输入密码 xff0c 对于公用电脑 xff0c 这样当然更安全 xff0c 但是如果这台电脑是一个人用 xff0c 每次都要选择帐户并输入密码实在太麻烦了
  • linux与linux,linux与windows,windows与linux之间SSH文件传输

    linux与linux之间传送文件 xff1a scp filename username 64 ip filename 例 xff1a gt scp appc daniel 64 10 141 44 203 home daniel Pas
  • 评:C语言18个经典问题答录

    C语言18个经典问题答录这个大家都看过 xff0c 自己也仔细看了一遍 xff0c 另外 xff0c 将一点感悟加注了一下 1 这样的初始化有什么问题 xff1f char p 61 malloc 10 编译器提示 非法初始式 云云 答 这

随机推荐